AArch64ISelLowering.cpp revision 360784
1//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "AArch64ISelLowering.h"
14#include "AArch64CallingConvention.h"
15#include "AArch64ExpandImm.h"
16#include "AArch64MachineFunctionInfo.h"
17#include "AArch64PerfectShuffle.h"
18#include "AArch64RegisterInfo.h"
19#include "AArch64Subtarget.h"
20#include "MCTargetDesc/AArch64AddressingModes.h"
21#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/StringSwitch.h"
31#include "llvm/ADT/Triple.h"
32#include "llvm/ADT/Twine.h"
33#include "llvm/Analysis/VectorUtils.h"
34#include "llvm/CodeGen/CallingConvLower.h"
35#include "llvm/CodeGen/MachineBasicBlock.h"
36#include "llvm/CodeGen/MachineFrameInfo.h"
37#include "llvm/CodeGen/MachineFunction.h"
38#include "llvm/CodeGen/MachineInstr.h"
39#include "llvm/CodeGen/MachineInstrBuilder.h"
40#include "llvm/CodeGen/MachineMemOperand.h"
41#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/RuntimeLibcalls.h"
43#include "llvm/CodeGen/SelectionDAG.h"
44#include "llvm/CodeGen/SelectionDAGNodes.h"
45#include "llvm/CodeGen/TargetCallingConv.h"
46#include "llvm/CodeGen/TargetInstrInfo.h"
47#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"
53#include "llvm/IR/Function.h"
54#include "llvm/IR/GetElementPtrTypeIterator.h"
55#include "llvm/IR/GlobalValue.h"
56#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Instructions.h"
59#include "llvm/IR/IntrinsicInst.h"
60#include "llvm/IR/Intrinsics.h"
61#include "llvm/IR/IntrinsicsAArch64.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/OperandTraits.h"
64#include "llvm/IR/PatternMatch.h"
65#include "llvm/IR/Type.h"
66#include "llvm/IR/Use.h"
67#include "llvm/IR/Value.h"
68#include "llvm/MC/MCRegisterInfo.h"
69#include "llvm/Support/Casting.h"
70#include "llvm/Support/CodeGen.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/Compiler.h"
73#include "llvm/Support/Debug.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/KnownBits.h"
76#include "llvm/Support/MachineValueType.h"
77#include "llvm/Support/MathExtras.h"
78#include "llvm/Support/raw_ostream.h"
79#include "llvm/Target/TargetMachine.h"
80#include "llvm/Target/TargetOptions.h"
81#include <algorithm>
82#include <bitset>
83#include <cassert>
84#include <cctype>
85#include <cstdint>
86#include <cstdlib>
87#include <iterator>
88#include <limits>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94using namespace llvm::PatternMatch;
95
96#define DEBUG_TYPE "aarch64-lower"
97
98STATISTIC(NumTailCalls, "Number of tail calls");
99STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101
102static cl::opt<bool>
103EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
104                           cl::desc("Allow AArch64 SLI/SRI formation"),
105                           cl::init(false));
106
107// FIXME: The necessary dtprel relocations don't seem to be supported
108// well in the GNU bfd and gold linkers at the moment. Therefore, by
109// default, for now, fall back to GeneralDynamic code generation.
110cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
111    "aarch64-elf-ldtls-generation", cl::Hidden,
112    cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
113    cl::init(false));
114
115static cl::opt<bool>
116EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
117                         cl::desc("Enable AArch64 logical imm instruction "
118                                  "optimization"),
119                         cl::init(true));
120
121/// Value type used for condition codes.
122static const MVT MVT_CC = MVT::i32;
123
124AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
125                                             const AArch64Subtarget &STI)
126    : TargetLowering(TM), Subtarget(&STI) {
127  // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
128  // we have to make something up. Arbitrarily, choose ZeroOrOne.
129  setBooleanContents(ZeroOrOneBooleanContent);
130  // When comparing vectors the result sets the different elements in the
131  // vector to all-one or all-zero.
132  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
133
134  // Set up the register classes.
135  addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
136  addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
137
138  if (Subtarget->hasFPARMv8()) {
139    addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
140    addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
141    addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
142    addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
143  }
144
145  if (Subtarget->hasNEON()) {
146    addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
147    addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
148    // Someone set us up the NEON.
149    addDRTypeForNEON(MVT::v2f32);
150    addDRTypeForNEON(MVT::v8i8);
151    addDRTypeForNEON(MVT::v4i16);
152    addDRTypeForNEON(MVT::v2i32);
153    addDRTypeForNEON(MVT::v1i64);
154    addDRTypeForNEON(MVT::v1f64);
155    addDRTypeForNEON(MVT::v4f16);
156
157    addQRTypeForNEON(MVT::v4f32);
158    addQRTypeForNEON(MVT::v2f64);
159    addQRTypeForNEON(MVT::v16i8);
160    addQRTypeForNEON(MVT::v8i16);
161    addQRTypeForNEON(MVT::v4i32);
162    addQRTypeForNEON(MVT::v2i64);
163    addQRTypeForNEON(MVT::v8f16);
164  }
165
166  if (Subtarget->hasSVE()) {
167    // Add legal sve predicate types
168    addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
169    addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
170    addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
171    addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
172
173    // Add legal sve data types
174    addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
175    addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
176    addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
177    addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
178
179    addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
180    addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
181    addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
182    addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183    addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184    addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
185
186    for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
187      setOperationAction(ISD::SADDSAT, VT, Legal);
188      setOperationAction(ISD::UADDSAT, VT, Legal);
189      setOperationAction(ISD::SSUBSAT, VT, Legal);
190      setOperationAction(ISD::USUBSAT, VT, Legal);
191      setOperationAction(ISD::SMAX, VT, Legal);
192      setOperationAction(ISD::UMAX, VT, Legal);
193      setOperationAction(ISD::SMIN, VT, Legal);
194      setOperationAction(ISD::UMIN, VT, Legal);
195    }
196
197    for (auto VT :
198         { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
199           MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
200      setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
201  }
202
203  // Compute derived properties from the register classes
204  computeRegisterProperties(Subtarget->getRegisterInfo());
205
206  // Provide all sorts of operation actions
207  setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208  setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
209  setOperationAction(ISD::SETCC, MVT::i32, Custom);
210  setOperationAction(ISD::SETCC, MVT::i64, Custom);
211  setOperationAction(ISD::SETCC, MVT::f16, Custom);
212  setOperationAction(ISD::SETCC, MVT::f32, Custom);
213  setOperationAction(ISD::SETCC, MVT::f64, Custom);
214  setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
215  setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
216  setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
217  setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
218  setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
219  setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
220  setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
221  setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
222  setOperationAction(ISD::BRCOND, MVT::Other, Expand);
223  setOperationAction(ISD::BR_CC, MVT::i32, Custom);
224  setOperationAction(ISD::BR_CC, MVT::i64, Custom);
225  setOperationAction(ISD::BR_CC, MVT::f16, Custom);
226  setOperationAction(ISD::BR_CC, MVT::f32, Custom);
227  setOperationAction(ISD::BR_CC, MVT::f64, Custom);
228  setOperationAction(ISD::SELECT, MVT::i32, Custom);
229  setOperationAction(ISD::SELECT, MVT::i64, Custom);
230  setOperationAction(ISD::SELECT, MVT::f16, Custom);
231  setOperationAction(ISD::SELECT, MVT::f32, Custom);
232  setOperationAction(ISD::SELECT, MVT::f64, Custom);
233  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
234  setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
235  setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
236  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
237  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
238  setOperationAction(ISD::BR_JT, MVT::Other, Custom);
239  setOperationAction(ISD::JumpTable, MVT::i64, Custom);
240
241  setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
242  setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
243  setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
244
245  setOperationAction(ISD::FREM, MVT::f32, Expand);
246  setOperationAction(ISD::FREM, MVT::f64, Expand);
247  setOperationAction(ISD::FREM, MVT::f80, Expand);
248
249  setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
250
251  // Custom lowering hooks are needed for XOR
252  // to fold it into CSINC/CSINV.
253  setOperationAction(ISD::XOR, MVT::i32, Custom);
254  setOperationAction(ISD::XOR, MVT::i64, Custom);
255
256  // Virtually no operation on f128 is legal, but LLVM can't expand them when
257  // there's a valid register class, so we need custom operations in most cases.
258  setOperationAction(ISD::FABS, MVT::f128, Expand);
259  setOperationAction(ISD::FADD, MVT::f128, Custom);
260  setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
261  setOperationAction(ISD::FCOS, MVT::f128, Expand);
262  setOperationAction(ISD::FDIV, MVT::f128, Custom);
263  setOperationAction(ISD::FMA, MVT::f128, Expand);
264  setOperationAction(ISD::FMUL, MVT::f128, Custom);
265  setOperationAction(ISD::FNEG, MVT::f128, Expand);
266  setOperationAction(ISD::FPOW, MVT::f128, Expand);
267  setOperationAction(ISD::FREM, MVT::f128, Expand);
268  setOperationAction(ISD::FRINT, MVT::f128, Expand);
269  setOperationAction(ISD::FSIN, MVT::f128, Expand);
270  setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
271  setOperationAction(ISD::FSQRT, MVT::f128, Expand);
272  setOperationAction(ISD::FSUB, MVT::f128, Custom);
273  setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
274  setOperationAction(ISD::SETCC, MVT::f128, Custom);
275  setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
276  setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
277  setOperationAction(ISD::BR_CC, MVT::f128, Custom);
278  setOperationAction(ISD::SELECT, MVT::f128, Custom);
279  setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
280  setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
281
282  // Lowering for many of the conversions is actually specified by the non-f128
283  // type. The LowerXXX function will be trivial when f128 isn't involved.
284  setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
285  setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
286  setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
287  setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
288  setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
289  setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
290  setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
291  setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
292  setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
293  setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
294  setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
295  setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
296  setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
297  setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
298  setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
299  setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
300  setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
301  setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
302  setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
303  setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
304  setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
305  setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
306  setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
307  setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
308  setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
309  setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
310  setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
311  setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
312
313  // Variable arguments.
314  setOperationAction(ISD::VASTART, MVT::Other, Custom);
315  setOperationAction(ISD::VAARG, MVT::Other, Custom);
316  setOperationAction(ISD::VACOPY, MVT::Other, Custom);
317  setOperationAction(ISD::VAEND, MVT::Other, Expand);
318
319  // Variable-sized objects.
320  setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
321  setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
322
323  if (Subtarget->isTargetWindows())
324    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
325  else
326    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
327
328  // Constant pool entries
329  setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
330
331  // BlockAddress
332  setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
333
334  // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
335  setOperationAction(ISD::ADDC, MVT::i32, Custom);
336  setOperationAction(ISD::ADDE, MVT::i32, Custom);
337  setOperationAction(ISD::SUBC, MVT::i32, Custom);
338  setOperationAction(ISD::SUBE, MVT::i32, Custom);
339  setOperationAction(ISD::ADDC, MVT::i64, Custom);
340  setOperationAction(ISD::ADDE, MVT::i64, Custom);
341  setOperationAction(ISD::SUBC, MVT::i64, Custom);
342  setOperationAction(ISD::SUBE, MVT::i64, Custom);
343
344  // AArch64 lacks both left-rotate and popcount instructions.
345  setOperationAction(ISD::ROTL, MVT::i32, Expand);
346  setOperationAction(ISD::ROTL, MVT::i64, Expand);
347  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
348    setOperationAction(ISD::ROTL, VT, Expand);
349    setOperationAction(ISD::ROTR, VT, Expand);
350  }
351
352  // AArch64 doesn't have {U|S}MUL_LOHI.
353  setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
354  setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
355
356  setOperationAction(ISD::CTPOP, MVT::i32, Custom);
357  setOperationAction(ISD::CTPOP, MVT::i64, Custom);
358
359  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
360  setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
361  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
362    setOperationAction(ISD::SDIVREM, VT, Expand);
363    setOperationAction(ISD::UDIVREM, VT, Expand);
364  }
365  setOperationAction(ISD::SREM, MVT::i32, Expand);
366  setOperationAction(ISD::SREM, MVT::i64, Expand);
367  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
368  setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
369  setOperationAction(ISD::UREM, MVT::i32, Expand);
370  setOperationAction(ISD::UREM, MVT::i64, Expand);
371
372  // Custom lower Add/Sub/Mul with overflow.
373  setOperationAction(ISD::SADDO, MVT::i32, Custom);
374  setOperationAction(ISD::SADDO, MVT::i64, Custom);
375  setOperationAction(ISD::UADDO, MVT::i32, Custom);
376  setOperationAction(ISD::UADDO, MVT::i64, Custom);
377  setOperationAction(ISD::SSUBO, MVT::i32, Custom);
378  setOperationAction(ISD::SSUBO, MVT::i64, Custom);
379  setOperationAction(ISD::USUBO, MVT::i32, Custom);
380  setOperationAction(ISD::USUBO, MVT::i64, Custom);
381  setOperationAction(ISD::SMULO, MVT::i32, Custom);
382  setOperationAction(ISD::SMULO, MVT::i64, Custom);
383  setOperationAction(ISD::UMULO, MVT::i32, Custom);
384  setOperationAction(ISD::UMULO, MVT::i64, Custom);
385
386  setOperationAction(ISD::FSIN, MVT::f32, Expand);
387  setOperationAction(ISD::FSIN, MVT::f64, Expand);
388  setOperationAction(ISD::FCOS, MVT::f32, Expand);
389  setOperationAction(ISD::FCOS, MVT::f64, Expand);
390  setOperationAction(ISD::FPOW, MVT::f32, Expand);
391  setOperationAction(ISD::FPOW, MVT::f64, Expand);
392  setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
393  setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
394  if (Subtarget->hasFullFP16())
395    setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
396  else
397    setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
398
399  setOperationAction(ISD::FREM,    MVT::f16,   Promote);
400  setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
401  setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
402  setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
403  setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
404  setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
405  setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
406  setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
407  setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
408  setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
409  setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
410  setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
411  setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
412  setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
413  setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
414  setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
415  setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
416  setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
417  setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
418  setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
419  setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
420  setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
421  setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
422  setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
423  setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
424  setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
425  setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
426  setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
427  setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
428  setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
429  setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
430  setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
431  setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
432
433  if (!Subtarget->hasFullFP16()) {
434    setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
435    setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
436    setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
437    setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
438    setOperationAction(ISD::FADD,        MVT::f16,  Promote);
439    setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
440    setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
441    setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
442    setOperationAction(ISD::FMA,         MVT::f16,  Promote);
443    setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
444    setOperationAction(ISD::FABS,        MVT::f16,  Promote);
445    setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
446    setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
447    setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
448    setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
449    setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
450    setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
451    setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
452    setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
453    setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
454    setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
455    setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
456
457    // promote v4f16 to v4f32 when that is known to be safe.
458    setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
459    setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
460    setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
461    setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
462    AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
463    AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
464    AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
465    AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
466
467    setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
468    setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
469    setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
470    setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
471    setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
472    setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
473    setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
474    setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
475    setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
476    setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
477    setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
478    setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
479    setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
480    setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
481    setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
482
483    setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
484    setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
485    setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
486    setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
487    setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
488    setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
489    setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
490    setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
491    setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
492    setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
493    setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
494    setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
495    setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
496    setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
497    setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
498    setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
499    setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
500    setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
501    setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
502    setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
503  }
504
505  // AArch64 has implementations of a lot of rounding-like FP operations.
506  for (MVT Ty : {MVT::f32, MVT::f64}) {
507    setOperationAction(ISD::FFLOOR, Ty, Legal);
508    setOperationAction(ISD::FNEARBYINT, Ty, Legal);
509    setOperationAction(ISD::FCEIL, Ty, Legal);
510    setOperationAction(ISD::FRINT, Ty, Legal);
511    setOperationAction(ISD::FTRUNC, Ty, Legal);
512    setOperationAction(ISD::FROUND, Ty, Legal);
513    setOperationAction(ISD::FMINNUM, Ty, Legal);
514    setOperationAction(ISD::FMAXNUM, Ty, Legal);
515    setOperationAction(ISD::FMINIMUM, Ty, Legal);
516    setOperationAction(ISD::FMAXIMUM, Ty, Legal);
517    setOperationAction(ISD::LROUND, Ty, Legal);
518    setOperationAction(ISD::LLROUND, Ty, Legal);
519    setOperationAction(ISD::LRINT, Ty, Legal);
520    setOperationAction(ISD::LLRINT, Ty, Legal);
521  }
522
523  if (Subtarget->hasFullFP16()) {
524    setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
525    setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
526    setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
527    setOperationAction(ISD::FRINT,   MVT::f16, Legal);
528    setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
529    setOperationAction(ISD::FROUND,  MVT::f16, Legal);
530    setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
531    setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
532    setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
533    setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
534  }
535
536  setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
537
538  setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
539
540  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
541  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
542  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
543  setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
544  setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
545
546  // 128-bit loads and stores can be done without expanding
547  setOperationAction(ISD::LOAD, MVT::i128, Custom);
548  setOperationAction(ISD::STORE, MVT::i128, Custom);
549
550  // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
551  // This requires the Performance Monitors extension.
552  if (Subtarget->hasPerfMon())
553    setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
554
555  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
556      getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
557    // Issue __sincos_stret if available.
558    setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
559    setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
560  } else {
561    setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
562    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
563  }
564
565  if (Subtarget->getTargetTriple().isOSMSVCRT()) {
566    // MSVCRT doesn't have powi; fall back to pow
567    setLibcallName(RTLIB::POWI_F32, nullptr);
568    setLibcallName(RTLIB::POWI_F64, nullptr);
569  }
570
571  // Make floating-point constants legal for the large code model, so they don't
572  // become loads from the constant pool.
573  if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
574    setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
575    setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
576  }
577
578  // AArch64 does not have floating-point extending loads, i1 sign-extending
579  // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
580  for (MVT VT : MVT::fp_valuetypes()) {
581    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
582    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
583    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
584    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
585  }
586  for (MVT VT : MVT::integer_valuetypes())
587    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
588
589  setTruncStoreAction(MVT::f32, MVT::f16, Expand);
590  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
591  setTruncStoreAction(MVT::f64, MVT::f16, Expand);
592  setTruncStoreAction(MVT::f128, MVT::f80, Expand);
593  setTruncStoreAction(MVT::f128, MVT::f64, Expand);
594  setTruncStoreAction(MVT::f128, MVT::f32, Expand);
595  setTruncStoreAction(MVT::f128, MVT::f16, Expand);
596
597  setOperationAction(ISD::BITCAST, MVT::i16, Custom);
598  setOperationAction(ISD::BITCAST, MVT::f16, Custom);
599
600  // Indexed loads and stores are supported.
601  for (unsigned im = (unsigned)ISD::PRE_INC;
602       im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
603    setIndexedLoadAction(im, MVT::i8, Legal);
604    setIndexedLoadAction(im, MVT::i16, Legal);
605    setIndexedLoadAction(im, MVT::i32, Legal);
606    setIndexedLoadAction(im, MVT::i64, Legal);
607    setIndexedLoadAction(im, MVT::f64, Legal);
608    setIndexedLoadAction(im, MVT::f32, Legal);
609    setIndexedLoadAction(im, MVT::f16, Legal);
610    setIndexedStoreAction(im, MVT::i8, Legal);
611    setIndexedStoreAction(im, MVT::i16, Legal);
612    setIndexedStoreAction(im, MVT::i32, Legal);
613    setIndexedStoreAction(im, MVT::i64, Legal);
614    setIndexedStoreAction(im, MVT::f64, Legal);
615    setIndexedStoreAction(im, MVT::f32, Legal);
616    setIndexedStoreAction(im, MVT::f16, Legal);
617  }
618
619  // Trap.
620  setOperationAction(ISD::TRAP, MVT::Other, Legal);
621  if (Subtarget->isTargetWindows())
622    setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623
624  // We combine OR nodes for bitfield operations.
625  setTargetDAGCombine(ISD::OR);
626  // Try to create BICs for vector ANDs.
627  setTargetDAGCombine(ISD::AND);
628
629  // Vector add and sub nodes may conceal a high-half opportunity.
630  // Also, try to fold ADD into CSINC/CSINV..
631  setTargetDAGCombine(ISD::ADD);
632  setTargetDAGCombine(ISD::SUB);
633  setTargetDAGCombine(ISD::SRL);
634  setTargetDAGCombine(ISD::XOR);
635  setTargetDAGCombine(ISD::SINT_TO_FP);
636  setTargetDAGCombine(ISD::UINT_TO_FP);
637
638  setTargetDAGCombine(ISD::FP_TO_SINT);
639  setTargetDAGCombine(ISD::FP_TO_UINT);
640  setTargetDAGCombine(ISD::FDIV);
641
642  setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
643
644  setTargetDAGCombine(ISD::ANY_EXTEND);
645  setTargetDAGCombine(ISD::ZERO_EXTEND);
646  setTargetDAGCombine(ISD::SIGN_EXTEND);
647  setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
648  setTargetDAGCombine(ISD::CONCAT_VECTORS);
649  setTargetDAGCombine(ISD::STORE);
650  if (Subtarget->supportsAddressTopByteIgnored())
651    setTargetDAGCombine(ISD::LOAD);
652
653  setTargetDAGCombine(ISD::MUL);
654
655  setTargetDAGCombine(ISD::SELECT);
656  setTargetDAGCombine(ISD::VSELECT);
657
658  setTargetDAGCombine(ISD::INTRINSIC_VOID);
659  setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
660  setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
661
662  setTargetDAGCombine(ISD::GlobalAddress);
663
664  // In case of strict alignment, avoid an excessive number of byte wide stores.
665  MaxStoresPerMemsetOptSize = 8;
666  MaxStoresPerMemset = Subtarget->requiresStrictAlign()
667                       ? MaxStoresPerMemsetOptSize : 32;
668
669  MaxGluedStoresPerMemcpy = 4;
670  MaxStoresPerMemcpyOptSize = 4;
671  MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
672                       ? MaxStoresPerMemcpyOptSize : 16;
673
674  MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
675
676  MaxLoadsPerMemcmpOptSize = 4;
677  MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
678                      ? MaxLoadsPerMemcmpOptSize : 8;
679
680  setStackPointerRegisterToSaveRestore(AArch64::SP);
681
682  setSchedulingPreference(Sched::Hybrid);
683
684  EnableExtLdPromotion = true;
685
686  // Set required alignment.
687  setMinFunctionAlignment(Align(4));
688  // Set preferred alignments.
689  setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
690  setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
691
692  // Only change the limit for entries in a jump table if specified by
693  // the sub target, but not at the command line.
694  unsigned MaxJT = STI.getMaximumJumpTableSize();
695  if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
696    setMaximumJumpTableSize(MaxJT);
697
698  setHasExtractBitsInsn(true);
699
700  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
701
702  if (Subtarget->hasNEON()) {
703    // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
704    // silliness like this:
705    setOperationAction(ISD::FABS, MVT::v1f64, Expand);
706    setOperationAction(ISD::FADD, MVT::v1f64, Expand);
707    setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
708    setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
709    setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
710    setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
711    setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
712    setOperationAction(ISD::FMA, MVT::v1f64, Expand);
713    setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
714    setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
715    setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
716    setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
717    setOperationAction(ISD::FREM, MVT::v1f64, Expand);
718    setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
719    setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
720    setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
721    setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
722    setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
723    setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
724    setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
725    setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
726    setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
727    setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
728    setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
729    setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
730
731    setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
732    setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
733    setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
734    setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
735    setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
736
737    setOperationAction(ISD::MUL, MVT::v1i64, Expand);
738
739    // AArch64 doesn't have a direct vector ->f32 conversion instructions for
740    // elements smaller than i32, so promote the input to i32 first.
741    setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
742    setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
743    // i8 vector elements also need promotion to i32 for v8i8
744    setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
745    setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
746    // Similarly, there is no direct i32 -> f64 vector conversion instruction.
747    setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
748    setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
749    setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
750    setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
751    // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
752    // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
753    setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
754    setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
755
756    if (Subtarget->hasFullFP16()) {
757      setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
758      setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
759      setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
760      setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
761    } else {
762      // when AArch64 doesn't have fullfp16 support, promote the input
763      // to i32 first.
764      setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
765      setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
766      setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
767      setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
768    }
769
770    setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
771    setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
772
773    // AArch64 doesn't have MUL.2d:
774    setOperationAction(ISD::MUL, MVT::v2i64, Expand);
775    // Custom handling for some quad-vector types to detect MULL.
776    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
777    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
778    setOperationAction(ISD::MUL, MVT::v2i64, Custom);
779
780    for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
781                    MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
782      // Vector reductions
783      setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
784      setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
785      setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
786      setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
787      setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
788
789      // Saturates
790      setOperationAction(ISD::SADDSAT, VT, Legal);
791      setOperationAction(ISD::UADDSAT, VT, Legal);
792      setOperationAction(ISD::SSUBSAT, VT, Legal);
793      setOperationAction(ISD::USUBSAT, VT, Legal);
794    }
795    for (MVT VT : { MVT::v4f16, MVT::v2f32,
796                    MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
797      setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
798      setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
799    }
800
801    setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
802    setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
803    // Likewise, narrowing and extending vector loads/stores aren't handled
804    // directly.
805    for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
806      setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
807
808      if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
809        setOperationAction(ISD::MULHS, VT, Legal);
810        setOperationAction(ISD::MULHU, VT, Legal);
811      } else {
812        setOperationAction(ISD::MULHS, VT, Expand);
813        setOperationAction(ISD::MULHU, VT, Expand);
814      }
815      setOperationAction(ISD::SMUL_LOHI, VT, Expand);
816      setOperationAction(ISD::UMUL_LOHI, VT, Expand);
817
818      setOperationAction(ISD::BSWAP, VT, Expand);
819      setOperationAction(ISD::CTTZ, VT, Expand);
820
821      for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
822        setTruncStoreAction(VT, InnerVT, Expand);
823        setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
824        setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
825        setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
826      }
827    }
828
829    // AArch64 has implementations of a lot of rounding-like FP operations.
830    for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
831      setOperationAction(ISD::FFLOOR, Ty, Legal);
832      setOperationAction(ISD::FNEARBYINT, Ty, Legal);
833      setOperationAction(ISD::FCEIL, Ty, Legal);
834      setOperationAction(ISD::FRINT, Ty, Legal);
835      setOperationAction(ISD::FTRUNC, Ty, Legal);
836      setOperationAction(ISD::FROUND, Ty, Legal);
837    }
838
839    if (Subtarget->hasFullFP16()) {
840      for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
841        setOperationAction(ISD::FFLOOR, Ty, Legal);
842        setOperationAction(ISD::FNEARBYINT, Ty, Legal);
843        setOperationAction(ISD::FCEIL, Ty, Legal);
844        setOperationAction(ISD::FRINT, Ty, Legal);
845        setOperationAction(ISD::FTRUNC, Ty, Legal);
846        setOperationAction(ISD::FROUND, Ty, Legal);
847      }
848    }
849
850    setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
851  }
852
853  if (Subtarget->hasSVE()) {
854    // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
855    // splat of 0 or undef) once vector selects supported in SVE codegen. See
856    // D68877 for more details.
857    for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
858      if (isTypeLegal(VT))
859        setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
860    }
861    setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
862    setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
863  }
864
865  PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
866}
867
868void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
869  assert(VT.isVector() && "VT should be a vector type");
870
871  if (VT.isFloatingPoint()) {
872    MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
873    setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
874    setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
875  }
876
877  // Mark vector float intrinsics as expand.
878  if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
879    setOperationAction(ISD::FSIN, VT, Expand);
880    setOperationAction(ISD::FCOS, VT, Expand);
881    setOperationAction(ISD::FPOW, VT, Expand);
882    setOperationAction(ISD::FLOG, VT, Expand);
883    setOperationAction(ISD::FLOG2, VT, Expand);
884    setOperationAction(ISD::FLOG10, VT, Expand);
885    setOperationAction(ISD::FEXP, VT, Expand);
886    setOperationAction(ISD::FEXP2, VT, Expand);
887
888    // But we do support custom-lowering for FCOPYSIGN.
889    setOperationAction(ISD::FCOPYSIGN, VT, Custom);
890  }
891
892  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
893  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
894  setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
895  setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
896  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
897  setOperationAction(ISD::SRA, VT, Custom);
898  setOperationAction(ISD::SRL, VT, Custom);
899  setOperationAction(ISD::SHL, VT, Custom);
900  setOperationAction(ISD::OR, VT, Custom);
901  setOperationAction(ISD::SETCC, VT, Custom);
902  setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
903
904  setOperationAction(ISD::SELECT, VT, Expand);
905  setOperationAction(ISD::SELECT_CC, VT, Expand);
906  setOperationAction(ISD::VSELECT, VT, Expand);
907  for (MVT InnerVT : MVT::all_valuetypes())
908    setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
909
910  // CNT supports only B element sizes, then use UADDLP to widen.
911  if (VT != MVT::v8i8 && VT != MVT::v16i8)
912    setOperationAction(ISD::CTPOP, VT, Custom);
913
914  setOperationAction(ISD::UDIV, VT, Expand);
915  setOperationAction(ISD::SDIV, VT, Expand);
916  setOperationAction(ISD::UREM, VT, Expand);
917  setOperationAction(ISD::SREM, VT, Expand);
918  setOperationAction(ISD::FREM, VT, Expand);
919
920  setOperationAction(ISD::FP_TO_SINT, VT, Custom);
921  setOperationAction(ISD::FP_TO_UINT, VT, Custom);
922
923  if (!VT.isFloatingPoint())
924    setOperationAction(ISD::ABS, VT, Legal);
925
926  // [SU][MIN|MAX] are available for all NEON types apart from i64.
927  if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
928    for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
929      setOperationAction(Opcode, VT, Legal);
930
931  // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
932  if (VT.isFloatingPoint() &&
933      (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
934    for (unsigned Opcode :
935         {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
936      setOperationAction(Opcode, VT, Legal);
937
938  if (Subtarget->isLittleEndian()) {
939    for (unsigned im = (unsigned)ISD::PRE_INC;
940         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
941      setIndexedLoadAction(im, VT, Legal);
942      setIndexedStoreAction(im, VT, Legal);
943    }
944  }
945}
946
947void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
948  addRegisterClass(VT, &AArch64::FPR64RegClass);
949  addTypeForNEON(VT, MVT::v2i32);
950}
951
952void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
953  addRegisterClass(VT, &AArch64::FPR128RegClass);
954  addTypeForNEON(VT, MVT::v4i32);
955}
956
957EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
958                                              EVT VT) const {
959  if (!VT.isVector())
960    return MVT::i32;
961  return VT.changeVectorElementTypeToInteger();
962}
963
964static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
965                               const APInt &Demanded,
966                               TargetLowering::TargetLoweringOpt &TLO,
967                               unsigned NewOpc) {
968  uint64_t OldImm = Imm, NewImm, Enc;
969  uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
970
971  // Return if the immediate is already all zeros, all ones, a bimm32 or a
972  // bimm64.
973  if (Imm == 0 || Imm == Mask ||
974      AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
975    return false;
976
977  unsigned EltSize = Size;
978  uint64_t DemandedBits = Demanded.getZExtValue();
979
980  // Clear bits that are not demanded.
981  Imm &= DemandedBits;
982
983  while (true) {
984    // The goal here is to set the non-demanded bits in a way that minimizes
985    // the number of switching between 0 and 1. In order to achieve this goal,
986    // we set the non-demanded bits to the value of the preceding demanded bits.
987    // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
988    // non-demanded bit), we copy bit0 (1) to the least significant 'x',
989    // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
990    // The final result is 0b11000011.
991    uint64_t NonDemandedBits = ~DemandedBits;
992    uint64_t InvertedImm = ~Imm & DemandedBits;
993    uint64_t RotatedImm =
994        ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
995        NonDemandedBits;
996    uint64_t Sum = RotatedImm + NonDemandedBits;
997    bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
998    uint64_t Ones = (Sum + Carry) & NonDemandedBits;
999    NewImm = (Imm | Ones) & Mask;
1000
1001    // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1002    // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1003    // we halve the element size and continue the search.
1004    if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1005      break;
1006
1007    // We cannot shrink the element size any further if it is 2-bits.
1008    if (EltSize == 2)
1009      return false;
1010
1011    EltSize /= 2;
1012    Mask >>= EltSize;
1013    uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1014
1015    // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1016    if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1017      return false;
1018
1019    // Merge the upper and lower halves of Imm and DemandedBits.
1020    Imm |= Hi;
1021    DemandedBits |= DemandedBitsHi;
1022  }
1023
1024  ++NumOptimizedImms;
1025
1026  // Replicate the element across the register width.
1027  while (EltSize < Size) {
1028    NewImm |= NewImm << EltSize;
1029    EltSize *= 2;
1030  }
1031
1032  (void)OldImm;
1033  assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1034         "demanded bits should never be altered");
1035  assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1036
1037  // Create the new constant immediate node.
1038  EVT VT = Op.getValueType();
1039  SDLoc DL(Op);
1040  SDValue New;
1041
1042  // If the new constant immediate is all-zeros or all-ones, let the target
1043  // independent DAG combine optimize this node.
1044  if (NewImm == 0 || NewImm == OrigMask) {
1045    New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1046                          TLO.DAG.getConstant(NewImm, DL, VT));
1047  // Otherwise, create a machine node so that target independent DAG combine
1048  // doesn't undo this optimization.
1049  } else {
1050    Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1051    SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1052    New = SDValue(
1053        TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1054  }
1055
1056  return TLO.CombineTo(Op, New);
1057}
1058
1059bool AArch64TargetLowering::targetShrinkDemandedConstant(
1060    SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1061  // Delay this optimization to as late as possible.
1062  if (!TLO.LegalOps)
1063    return false;
1064
1065  if (!EnableOptimizeLogicalImm)
1066    return false;
1067
1068  EVT VT = Op.getValueType();
1069  if (VT.isVector())
1070    return false;
1071
1072  unsigned Size = VT.getSizeInBits();
1073  assert((Size == 32 || Size == 64) &&
1074         "i32 or i64 is expected after legalization.");
1075
1076  // Exit early if we demand all bits.
1077  if (Demanded.countPopulation() == Size)
1078    return false;
1079
1080  unsigned NewOpc;
1081  switch (Op.getOpcode()) {
1082  default:
1083    return false;
1084  case ISD::AND:
1085    NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1086    break;
1087  case ISD::OR:
1088    NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1089    break;
1090  case ISD::XOR:
1091    NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1092    break;
1093  }
1094  ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1095  if (!C)
1096    return false;
1097  uint64_t Imm = C->getZExtValue();
1098  return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1099}
1100
1101/// computeKnownBitsForTargetNode - Determine which of the bits specified in
1102/// Mask are known to be either zero or one and return them Known.
1103void AArch64TargetLowering::computeKnownBitsForTargetNode(
1104    const SDValue Op, KnownBits &Known,
1105    const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1106  switch (Op.getOpcode()) {
1107  default:
1108    break;
1109  case AArch64ISD::CSEL: {
1110    KnownBits Known2;
1111    Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1112    Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1113    Known.Zero &= Known2.Zero;
1114    Known.One &= Known2.One;
1115    break;
1116  }
1117  case AArch64ISD::LOADgot:
1118  case AArch64ISD::ADDlow: {
1119    if (!Subtarget->isTargetILP32())
1120      break;
1121    // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1122    Known.Zero = APInt::getHighBitsSet(64, 32);
1123    break;
1124  }
1125  case ISD::INTRINSIC_W_CHAIN: {
1126    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1127    Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1128    switch (IntID) {
1129    default: return;
1130    case Intrinsic::aarch64_ldaxr:
1131    case Intrinsic::aarch64_ldxr: {
1132      unsigned BitWidth = Known.getBitWidth();
1133      EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1134      unsigned MemBits = VT.getScalarSizeInBits();
1135      Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1136      return;
1137    }
1138    }
1139    break;
1140  }
1141  case ISD::INTRINSIC_WO_CHAIN:
1142  case ISD::INTRINSIC_VOID: {
1143    unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1144    switch (IntNo) {
1145    default:
1146      break;
1147    case Intrinsic::aarch64_neon_umaxv:
1148    case Intrinsic::aarch64_neon_uminv: {
1149      // Figure out the datatype of the vector operand. The UMINV instruction
1150      // will zero extend the result, so we can mark as known zero all the
1151      // bits larger than the element datatype. 32-bit or larget doesn't need
1152      // this as those are legal types and will be handled by isel directly.
1153      MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1154      unsigned BitWidth = Known.getBitWidth();
1155      if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1156        assert(BitWidth >= 8 && "Unexpected width!");
1157        APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1158        Known.Zero |= Mask;
1159      } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1160        assert(BitWidth >= 16 && "Unexpected width!");
1161        APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1162        Known.Zero |= Mask;
1163      }
1164      break;
1165    } break;
1166    }
1167  }
1168  }
1169}
1170
1171MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1172                                                  EVT) const {
1173  return MVT::i64;
1174}
1175
1176bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1177    EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1178    bool *Fast) const {
1179  if (Subtarget->requiresStrictAlign())
1180    return false;
1181
1182  if (Fast) {
1183    // Some CPUs are fine with unaligned stores except for 128-bit ones.
1184    *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1185            // See comments in performSTORECombine() for more details about
1186            // these conditions.
1187
1188            // Code that uses clang vector extensions can mark that it
1189            // wants unaligned accesses to be treated as fast by
1190            // underspecifying alignment to be 1 or 2.
1191            Align <= 2 ||
1192
1193            // Disregard v2i64. Memcpy lowering produces those and splitting
1194            // them regresses performance on micro-benchmarks and olden/bh.
1195            VT == MVT::v2i64;
1196  }
1197  return true;
1198}
1199
1200// Same as above but handling LLTs instead.
1201bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1202    LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1203    bool *Fast) const {
1204  if (Subtarget->requiresStrictAlign())
1205    return false;
1206
1207  if (Fast) {
1208    // Some CPUs are fine with unaligned stores except for 128-bit ones.
1209    *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1210            Ty.getSizeInBytes() != 16 ||
1211            // See comments in performSTORECombine() for more details about
1212            // these conditions.
1213
1214            // Code that uses clang vector extensions can mark that it
1215            // wants unaligned accesses to be treated as fast by
1216            // underspecifying alignment to be 1 or 2.
1217            Align <= 2 ||
1218
1219            // Disregard v2i64. Memcpy lowering produces those and splitting
1220            // them regresses performance on micro-benchmarks and olden/bh.
1221            Ty == LLT::vector(2, 64);
1222  }
1223  return true;
1224}
1225
1226FastISel *
1227AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1228                                      const TargetLibraryInfo *libInfo) const {
1229  return AArch64::createFastISel(funcInfo, libInfo);
1230}
1231
1232const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1233  switch ((AArch64ISD::NodeType)Opcode) {
1234  case AArch64ISD::FIRST_NUMBER:      break;
1235  case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1236  case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1237  case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1238  case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1239  case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1240  case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1241  case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1242  case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1243  case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1244  case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1245  case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1246  case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1247  case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1248  case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1249  case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1250  case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1251  case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1252  case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1253  case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1254  case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1255  case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1256  case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1257  case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1258  case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1259  case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1260  case AArch64ISD::STRICT_FCMP:       return "AArch64ISD::STRICT_FCMP";
1261  case AArch64ISD::STRICT_FCMPE:      return "AArch64ISD::STRICT_FCMPE";
1262  case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1263  case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1264  case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1265  case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1266  case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1267  case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1268  case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1269  case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1270  case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1271  case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1272  case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1273  case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1274  case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1275  case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1276  case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1277  case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1278  case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1279  case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1280  case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1281  case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1282  case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1283  case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1284  case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1285  case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1286  case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1287  case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1288  case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1289  case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1290  case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1291  case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1292  case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1293  case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1294  case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1295  case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1296  case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1297  case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1298  case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1299  case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1300  case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1301  case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1302  case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1303  case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1304  case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1305  case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1306  case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1307  case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1308  case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1309  case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1310  case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1311  case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1312  case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1313  case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1314  case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1315  case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1316  case AArch64ISD::SMAXV_PRED:        return "AArch64ISD::SMAXV_PRED";
1317  case AArch64ISD::UMAXV_PRED:        return "AArch64ISD::UMAXV_PRED";
1318  case AArch64ISD::SMINV_PRED:        return "AArch64ISD::SMINV_PRED";
1319  case AArch64ISD::UMINV_PRED:        return "AArch64ISD::UMINV_PRED";
1320  case AArch64ISD::ORV_PRED:          return "AArch64ISD::ORV_PRED";
1321  case AArch64ISD::EORV_PRED:         return "AArch64ISD::EORV_PRED";
1322  case AArch64ISD::ANDV_PRED:         return "AArch64ISD::ANDV_PRED";
1323  case AArch64ISD::CLASTA_N:          return "AArch64ISD::CLASTA_N";
1324  case AArch64ISD::CLASTB_N:          return "AArch64ISD::CLASTB_N";
1325  case AArch64ISD::LASTA:             return "AArch64ISD::LASTA";
1326  case AArch64ISD::LASTB:             return "AArch64ISD::LASTB";
1327  case AArch64ISD::REV:               return "AArch64ISD::REV";
1328  case AArch64ISD::TBL:               return "AArch64ISD::TBL";
1329  case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1330  case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1331  case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1332  case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1333  case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1334  case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1335  case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1336  case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1337  case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1338  case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1339  case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1340  case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1341  case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1342  case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1343  case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1344  case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1345  case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1346  case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1347  case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1348  case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1349  case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1350  case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1351  case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1352  case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1353  case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1354  case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1355  case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1356  case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1357  case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1358  case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1359  case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1360  case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1361  case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1362  case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1363  case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1364  case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1365  case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1366  case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1367  case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1368  case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1369  case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1370  case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1371  case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1372  case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1373  case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1374  case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1375  case AArch64ISD::STG:               return "AArch64ISD::STG";
1376  case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1377  case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1378  case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1379  case AArch64ISD::SUNPKHI:           return "AArch64ISD::SUNPKHI";
1380  case AArch64ISD::SUNPKLO:           return "AArch64ISD::SUNPKLO";
1381  case AArch64ISD::UUNPKHI:           return "AArch64ISD::UUNPKHI";
1382  case AArch64ISD::UUNPKLO:           return "AArch64ISD::UUNPKLO";
1383  case AArch64ISD::INSR:              return "AArch64ISD::INSR";
1384  case AArch64ISD::PTEST:             return "AArch64ISD::PTEST";
1385  case AArch64ISD::PTRUE:             return "AArch64ISD::PTRUE";
1386  case AArch64ISD::GLD1:              return "AArch64ISD::GLD1";
1387  case AArch64ISD::GLD1_SCALED:       return "AArch64ISD::GLD1_SCALED";
1388  case AArch64ISD::GLD1_SXTW:         return "AArch64ISD::GLD1_SXTW";
1389  case AArch64ISD::GLD1_UXTW:         return "AArch64ISD::GLD1_UXTW";
1390  case AArch64ISD::GLD1_SXTW_SCALED:  return "AArch64ISD::GLD1_SXTW_SCALED";
1391  case AArch64ISD::GLD1_UXTW_SCALED:  return "AArch64ISD::GLD1_UXTW_SCALED";
1392  case AArch64ISD::GLD1_IMM:          return "AArch64ISD::GLD1_IMM";
1393  case AArch64ISD::GLD1S:             return "AArch64ISD::GLD1S";
1394  case AArch64ISD::GLD1S_SCALED:      return "AArch64ISD::GLD1S_SCALED";
1395  case AArch64ISD::GLD1S_SXTW:        return "AArch64ISD::GLD1S_SXTW";
1396  case AArch64ISD::GLD1S_UXTW:        return "AArch64ISD::GLD1S_UXTW";
1397  case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED";
1398  case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED";
1399  case AArch64ISD::GLD1S_IMM:         return "AArch64ISD::GLD1S_IMM";
1400  case AArch64ISD::SST1:              return "AArch64ISD::SST1";
1401  case AArch64ISD::SST1_SCALED:       return "AArch64ISD::SST1_SCALED";
1402  case AArch64ISD::SST1_SXTW:         return "AArch64ISD::SST1_SXTW";
1403  case AArch64ISD::SST1_UXTW:         return "AArch64ISD::SST1_UXTW";
1404  case AArch64ISD::SST1_SXTW_SCALED:  return "AArch64ISD::SST1_SXTW_SCALED";
1405  case AArch64ISD::SST1_UXTW_SCALED:  return "AArch64ISD::SST1_UXTW_SCALED";
1406  case AArch64ISD::SST1_IMM:          return "AArch64ISD::SST1_IMM";
1407  case AArch64ISD::LDP:               return "AArch64ISD::LDP";
1408  case AArch64ISD::STP:               return "AArch64ISD::STP";
1409  }
1410  return nullptr;
1411}
1412
1413MachineBasicBlock *
1414AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1415                                    MachineBasicBlock *MBB) const {
1416  // We materialise the F128CSEL pseudo-instruction as some control flow and a
1417  // phi node:
1418
1419  // OrigBB:
1420  //     [... previous instrs leading to comparison ...]
1421  //     b.ne TrueBB
1422  //     b EndBB
1423  // TrueBB:
1424  //     ; Fallthrough
1425  // EndBB:
1426  //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1427
1428  MachineFunction *MF = MBB->getParent();
1429  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1430  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1431  DebugLoc DL = MI.getDebugLoc();
1432  MachineFunction::iterator It = ++MBB->getIterator();
1433
1434  Register DestReg = MI.getOperand(0).getReg();
1435  Register IfTrueReg = MI.getOperand(1).getReg();
1436  Register IfFalseReg = MI.getOperand(2).getReg();
1437  unsigned CondCode = MI.getOperand(3).getImm();
1438  bool NZCVKilled = MI.getOperand(4).isKill();
1439
1440  MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1441  MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1442  MF->insert(It, TrueBB);
1443  MF->insert(It, EndBB);
1444
1445  // Transfer rest of current basic-block to EndBB
1446  EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1447                MBB->end());
1448  EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1449
1450  BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1451  BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1452  MBB->addSuccessor(TrueBB);
1453  MBB->addSuccessor(EndBB);
1454
1455  // TrueBB falls through to the end.
1456  TrueBB->addSuccessor(EndBB);
1457
1458  if (!NZCVKilled) {
1459    TrueBB->addLiveIn(AArch64::NZCV);
1460    EndBB->addLiveIn(AArch64::NZCV);
1461  }
1462
1463  BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1464      .addReg(IfTrueReg)
1465      .addMBB(TrueBB)
1466      .addReg(IfFalseReg)
1467      .addMBB(MBB);
1468
1469  MI.eraseFromParent();
1470  return EndBB;
1471}
1472
1473MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1474       MachineInstr &MI, MachineBasicBlock *BB) const {
1475  assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1476             BB->getParent()->getFunction().getPersonalityFn())) &&
1477         "SEH does not use catchret!");
1478  return BB;
1479}
1480
1481MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1482     MachineInstr &MI, MachineBasicBlock *BB) const {
1483  MI.eraseFromParent();
1484  return BB;
1485}
1486
1487MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1488    MachineInstr &MI, MachineBasicBlock *BB) const {
1489  switch (MI.getOpcode()) {
1490  default:
1491#ifndef NDEBUG
1492    MI.dump();
1493#endif
1494    llvm_unreachable("Unexpected instruction for custom inserter!");
1495
1496  case AArch64::F128CSEL:
1497    return EmitF128CSEL(MI, BB);
1498
1499  case TargetOpcode::STACKMAP:
1500  case TargetOpcode::PATCHPOINT:
1501    return emitPatchPoint(MI, BB);
1502
1503  case AArch64::CATCHRET:
1504    return EmitLoweredCatchRet(MI, BB);
1505  case AArch64::CATCHPAD:
1506    return EmitLoweredCatchPad(MI, BB);
1507  }
1508}
1509
1510//===----------------------------------------------------------------------===//
1511// AArch64 Lowering private implementation.
1512//===----------------------------------------------------------------------===//
1513
1514//===----------------------------------------------------------------------===//
1515// Lowering Code
1516//===----------------------------------------------------------------------===//
1517
1518/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1519/// CC
1520static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1521  switch (CC) {
1522  default:
1523    llvm_unreachable("Unknown condition code!");
1524  case ISD::SETNE:
1525    return AArch64CC::NE;
1526  case ISD::SETEQ:
1527    return AArch64CC::EQ;
1528  case ISD::SETGT:
1529    return AArch64CC::GT;
1530  case ISD::SETGE:
1531    return AArch64CC::GE;
1532  case ISD::SETLT:
1533    return AArch64CC::LT;
1534  case ISD::SETLE:
1535    return AArch64CC::LE;
1536  case ISD::SETUGT:
1537    return AArch64CC::HI;
1538  case ISD::SETUGE:
1539    return AArch64CC::HS;
1540  case ISD::SETULT:
1541    return AArch64CC::LO;
1542  case ISD::SETULE:
1543    return AArch64CC::LS;
1544  }
1545}
1546
1547/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1548static void changeFPCCToAArch64CC(ISD::CondCode CC,
1549                                  AArch64CC::CondCode &CondCode,
1550                                  AArch64CC::CondCode &CondCode2) {
1551  CondCode2 = AArch64CC::AL;
1552  switch (CC) {
1553  default:
1554    llvm_unreachable("Unknown FP condition!");
1555  case ISD::SETEQ:
1556  case ISD::SETOEQ:
1557    CondCode = AArch64CC::EQ;
1558    break;
1559  case ISD::SETGT:
1560  case ISD::SETOGT:
1561    CondCode = AArch64CC::GT;
1562    break;
1563  case ISD::SETGE:
1564  case ISD::SETOGE:
1565    CondCode = AArch64CC::GE;
1566    break;
1567  case ISD::SETOLT:
1568    CondCode = AArch64CC::MI;
1569    break;
1570  case ISD::SETOLE:
1571    CondCode = AArch64CC::LS;
1572    break;
1573  case ISD::SETONE:
1574    CondCode = AArch64CC::MI;
1575    CondCode2 = AArch64CC::GT;
1576    break;
1577  case ISD::SETO:
1578    CondCode = AArch64CC::VC;
1579    break;
1580  case ISD::SETUO:
1581    CondCode = AArch64CC::VS;
1582    break;
1583  case ISD::SETUEQ:
1584    CondCode = AArch64CC::EQ;
1585    CondCode2 = AArch64CC::VS;
1586    break;
1587  case ISD::SETUGT:
1588    CondCode = AArch64CC::HI;
1589    break;
1590  case ISD::SETUGE:
1591    CondCode = AArch64CC::PL;
1592    break;
1593  case ISD::SETLT:
1594  case ISD::SETULT:
1595    CondCode = AArch64CC::LT;
1596    break;
1597  case ISD::SETLE:
1598  case ISD::SETULE:
1599    CondCode = AArch64CC::LE;
1600    break;
1601  case ISD::SETNE:
1602  case ISD::SETUNE:
1603    CondCode = AArch64CC::NE;
1604    break;
1605  }
1606}
1607
1608/// Convert a DAG fp condition code to an AArch64 CC.
1609/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1610/// should be AND'ed instead of OR'ed.
1611static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1612                                     AArch64CC::CondCode &CondCode,
1613                                     AArch64CC::CondCode &CondCode2) {
1614  CondCode2 = AArch64CC::AL;
1615  switch (CC) {
1616  default:
1617    changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1618    assert(CondCode2 == AArch64CC::AL);
1619    break;
1620  case ISD::SETONE:
1621    // (a one b)
1622    // == ((a olt b) || (a ogt b))
1623    // == ((a ord b) && (a une b))
1624    CondCode = AArch64CC::VC;
1625    CondCode2 = AArch64CC::NE;
1626    break;
1627  case ISD::SETUEQ:
1628    // (a ueq b)
1629    // == ((a uno b) || (a oeq b))
1630    // == ((a ule b) && (a uge b))
1631    CondCode = AArch64CC::PL;
1632    CondCode2 = AArch64CC::LE;
1633    break;
1634  }
1635}
1636
1637/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1638/// CC usable with the vector instructions. Fewer operations are available
1639/// without a real NZCV register, so we have to use less efficient combinations
1640/// to get the same effect.
1641static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1642                                        AArch64CC::CondCode &CondCode,
1643                                        AArch64CC::CondCode &CondCode2,
1644                                        bool &Invert) {
1645  Invert = false;
1646  switch (CC) {
1647  default:
1648    // Mostly the scalar mappings work fine.
1649    changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1650    break;
1651  case ISD::SETUO:
1652    Invert = true;
1653    LLVM_FALLTHROUGH;
1654  case ISD::SETO:
1655    CondCode = AArch64CC::MI;
1656    CondCode2 = AArch64CC::GE;
1657    break;
1658  case ISD::SETUEQ:
1659  case ISD::SETULT:
1660  case ISD::SETULE:
1661  case ISD::SETUGT:
1662  case ISD::SETUGE:
1663    // All of the compare-mask comparisons are ordered, but we can switch
1664    // between the two by a double inversion. E.g. ULE == !OGT.
1665    Invert = true;
1666    changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1667                          CondCode, CondCode2);
1668    break;
1669  }
1670}
1671
1672static bool isLegalArithImmed(uint64_t C) {
1673  // Matches AArch64DAGToDAGISel::SelectArithImmed().
1674  bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1675  LLVM_DEBUG(dbgs() << "Is imm " << C
1676                    << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1677  return IsLegal;
1678}
1679
1680// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1681// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1682// can be set differently by this operation. It comes down to whether
1683// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1684// everything is fine. If not then the optimization is wrong. Thus general
1685// comparisons are only valid if op2 != 0.
1686//
1687// So, finally, the only LLVM-native comparisons that don't mention C and V
1688// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1689// the absence of information about op2.
1690static bool isCMN(SDValue Op, ISD::CondCode CC) {
1691  return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1692         (CC == ISD::SETEQ || CC == ISD::SETNE);
1693}
1694
1695static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1696                                      SelectionDAG &DAG, SDValue Chain,
1697                                      bool IsSignaling) {
1698  EVT VT = LHS.getValueType();
1699  assert(VT != MVT::f128);
1700  assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1701  unsigned Opcode =
1702      IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1703  return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1704}
1705
1706static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1707                              const SDLoc &dl, SelectionDAG &DAG) {
1708  EVT VT = LHS.getValueType();
1709  const bool FullFP16 =
1710    static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1711
1712  if (VT.isFloatingPoint()) {
1713    assert(VT != MVT::f128);
1714    if (VT == MVT::f16 && !FullFP16) {
1715      LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1716      RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1717      VT = MVT::f32;
1718    }
1719    return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1720  }
1721
1722  // The CMP instruction is just an alias for SUBS, and representing it as
1723  // SUBS means that it's possible to get CSE with subtract operations.
1724  // A later phase can perform the optimization of setting the destination
1725  // register to WZR/XZR if it ends up being unused.
1726  unsigned Opcode = AArch64ISD::SUBS;
1727
1728  if (isCMN(RHS, CC)) {
1729    // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1730    Opcode = AArch64ISD::ADDS;
1731    RHS = RHS.getOperand(1);
1732  } else if (isCMN(LHS, CC)) {
1733    // As we are looking for EQ/NE compares, the operands can be commuted ; can
1734    // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1735    Opcode = AArch64ISD::ADDS;
1736    LHS = LHS.getOperand(1);
1737  } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1738             !isUnsignedIntSetCC(CC)) {
1739    // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1740    // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1741    // of the signed comparisons.
1742    Opcode = AArch64ISD::ANDS;
1743    RHS = LHS.getOperand(1);
1744    LHS = LHS.getOperand(0);
1745  }
1746
1747  return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1748      .getValue(1);
1749}
1750
1751/// \defgroup AArch64CCMP CMP;CCMP matching
1752///
1753/// These functions deal with the formation of CMP;CCMP;... sequences.
1754/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1755/// a comparison. They set the NZCV flags to a predefined value if their
1756/// predicate is false. This allows to express arbitrary conjunctions, for
1757/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1758/// expressed as:
1759///   cmp A
1760///   ccmp B, inv(CB), CA
1761///   check for CB flags
1762///
1763/// This naturally lets us implement chains of AND operations with SETCC
1764/// operands. And we can even implement some other situations by transforming
1765/// them:
1766///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1767///     negating the flags used in a CCMP/FCCMP operations.
1768///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1769///     by negating the flags we test for afterwards. i.e.
1770///     NEG (CMP CCMP CCCMP ...) can be implemented.
1771///   - Note that we can only ever negate all previously processed results.
1772///     What we can not implement by flipping the flags to test is a negation
1773///     of two sub-trees (because the negation affects all sub-trees emitted so
1774///     far, so the 2nd sub-tree we emit would also affect the first).
1775/// With those tools we can implement some OR operations:
1776///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1777///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1778///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1779///     elimination rules from earlier to implement the whole thing as a
1780///     CCMP/FCCMP chain.
1781///
1782/// As complete example:
1783///     or (or (setCA (cmp A)) (setCB (cmp B)))
1784///        (and (setCC (cmp C)) (setCD (cmp D)))"
1785/// can be reassociated to:
1786///     or (and (setCC (cmp C)) setCD (cmp D))
1787//         (or (setCA (cmp A)) (setCB (cmp B)))
1788/// can be transformed to:
1789///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1790///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1791/// which can be implemented as:
1792///   cmp C
1793///   ccmp D, inv(CD), CC
1794///   ccmp A, CA, inv(CD)
1795///   ccmp B, CB, inv(CA)
1796///   check for CB flags
1797///
1798/// A counterexample is "or (and A B) (and C D)" which translates to
1799/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1800/// can only implement 1 of the inner (not) operations, but not both!
1801/// @{
1802
1803/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1804static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1805                                         ISD::CondCode CC, SDValue CCOp,
1806                                         AArch64CC::CondCode Predicate,
1807                                         AArch64CC::CondCode OutCC,
1808                                         const SDLoc &DL, SelectionDAG &DAG) {
1809  unsigned Opcode = 0;
1810  const bool FullFP16 =
1811    static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1812
1813  if (LHS.getValueType().isFloatingPoint()) {
1814    assert(LHS.getValueType() != MVT::f128);
1815    if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1816      LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1817      RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1818    }
1819    Opcode = AArch64ISD::FCCMP;
1820  } else if (RHS.getOpcode() == ISD::SUB) {
1821    SDValue SubOp0 = RHS.getOperand(0);
1822    if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1823      // See emitComparison() on why we can only do this for SETEQ and SETNE.
1824      Opcode = AArch64ISD::CCMN;
1825      RHS = RHS.getOperand(1);
1826    }
1827  }
1828  if (Opcode == 0)
1829    Opcode = AArch64ISD::CCMP;
1830
1831  SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1832  AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1833  unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1834  SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1835  return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1836}
1837
1838/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1839/// expressed as a conjunction. See \ref AArch64CCMP.
1840/// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1841///                     changing the conditions on the SETCC tests.
1842///                     (this means we can call emitConjunctionRec() with
1843///                      Negate==true on this sub-tree)
1844/// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1845///                     cannot do the negation naturally. We are required to
1846///                     emit the subtree first in this case.
1847/// \param WillNegate   Is true if are called when the result of this
1848///                     subexpression must be negated. This happens when the
1849///                     outer expression is an OR. We can use this fact to know
1850///                     that we have a double negation (or (or ...) ...) that
1851///                     can be implemented for free.
1852static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1853                               bool &MustBeFirst, bool WillNegate,
1854                               unsigned Depth = 0) {
1855  if (!Val.hasOneUse())
1856    return false;
1857  unsigned Opcode = Val->getOpcode();
1858  if (Opcode == ISD::SETCC) {
1859    if (Val->getOperand(0).getValueType() == MVT::f128)
1860      return false;
1861    CanNegate = true;
1862    MustBeFirst = false;
1863    return true;
1864  }
1865  // Protect against exponential runtime and stack overflow.
1866  if (Depth > 6)
1867    return false;
1868  if (Opcode == ISD::AND || Opcode == ISD::OR) {
1869    bool IsOR = Opcode == ISD::OR;
1870    SDValue O0 = Val->getOperand(0);
1871    SDValue O1 = Val->getOperand(1);
1872    bool CanNegateL;
1873    bool MustBeFirstL;
1874    if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1875      return false;
1876    bool CanNegateR;
1877    bool MustBeFirstR;
1878    if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1879      return false;
1880
1881    if (MustBeFirstL && MustBeFirstR)
1882      return false;
1883
1884    if (IsOR) {
1885      // For an OR expression we need to be able to naturally negate at least
1886      // one side or we cannot do the transformation at all.
1887      if (!CanNegateL && !CanNegateR)
1888        return false;
1889      // If we the result of the OR will be negated and we can naturally negate
1890      // the leafs, then this sub-tree as a whole negates naturally.
1891      CanNegate = WillNegate && CanNegateL && CanNegateR;
1892      // If we cannot naturally negate the whole sub-tree, then this must be
1893      // emitted first.
1894      MustBeFirst = !CanNegate;
1895    } else {
1896      assert(Opcode == ISD::AND && "Must be OR or AND");
1897      // We cannot naturally negate an AND operation.
1898      CanNegate = false;
1899      MustBeFirst = MustBeFirstL || MustBeFirstR;
1900    }
1901    return true;
1902  }
1903  return false;
1904}
1905
1906/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1907/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1908/// Tries to transform the given i1 producing node @p Val to a series compare
1909/// and conditional compare operations. @returns an NZCV flags producing node
1910/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1911/// transformation was not possible.
1912/// \p Negate is true if we want this sub-tree being negated just by changing
1913/// SETCC conditions.
1914static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1915    AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1916    AArch64CC::CondCode Predicate) {
1917  // We're at a tree leaf, produce a conditional comparison operation.
1918  unsigned Opcode = Val->getOpcode();
1919  if (Opcode == ISD::SETCC) {
1920    SDValue LHS = Val->getOperand(0);
1921    SDValue RHS = Val->getOperand(1);
1922    ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1923    bool isInteger = LHS.getValueType().isInteger();
1924    if (Negate)
1925      CC = getSetCCInverse(CC, LHS.getValueType());
1926    SDLoc DL(Val);
1927    // Determine OutCC and handle FP special case.
1928    if (isInteger) {
1929      OutCC = changeIntCCToAArch64CC(CC);
1930    } else {
1931      assert(LHS.getValueType().isFloatingPoint());
1932      AArch64CC::CondCode ExtraCC;
1933      changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1934      // Some floating point conditions can't be tested with a single condition
1935      // code. Construct an additional comparison in this case.
1936      if (ExtraCC != AArch64CC::AL) {
1937        SDValue ExtraCmp;
1938        if (!CCOp.getNode())
1939          ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1940        else
1941          ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1942                                               ExtraCC, DL, DAG);
1943        CCOp = ExtraCmp;
1944        Predicate = ExtraCC;
1945      }
1946    }
1947
1948    // Produce a normal comparison if we are first in the chain
1949    if (!CCOp)
1950      return emitComparison(LHS, RHS, CC, DL, DAG);
1951    // Otherwise produce a ccmp.
1952    return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1953                                     DAG);
1954  }
1955  assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1956
1957  bool IsOR = Opcode == ISD::OR;
1958
1959  SDValue LHS = Val->getOperand(0);
1960  bool CanNegateL;
1961  bool MustBeFirstL;
1962  bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1963  assert(ValidL && "Valid conjunction/disjunction tree");
1964  (void)ValidL;
1965
1966  SDValue RHS = Val->getOperand(1);
1967  bool CanNegateR;
1968  bool MustBeFirstR;
1969  bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1970  assert(ValidR && "Valid conjunction/disjunction tree");
1971  (void)ValidR;
1972
1973  // Swap sub-tree that must come first to the right side.
1974  if (MustBeFirstL) {
1975    assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1976    std::swap(LHS, RHS);
1977    std::swap(CanNegateL, CanNegateR);
1978    std::swap(MustBeFirstL, MustBeFirstR);
1979  }
1980
1981  bool NegateR;
1982  bool NegateAfterR;
1983  bool NegateL;
1984  bool NegateAfterAll;
1985  if (Opcode == ISD::OR) {
1986    // Swap the sub-tree that we can negate naturally to the left.
1987    if (!CanNegateL) {
1988      assert(CanNegateR && "at least one side must be negatable");
1989      assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1990      assert(!Negate);
1991      std::swap(LHS, RHS);
1992      NegateR = false;
1993      NegateAfterR = true;
1994    } else {
1995      // Negate the left sub-tree if possible, otherwise negate the result.
1996      NegateR = CanNegateR;
1997      NegateAfterR = !CanNegateR;
1998    }
1999    NegateL = true;
2000    NegateAfterAll = !Negate;
2001  } else {
2002    assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2003    assert(!Negate && "Valid conjunction/disjunction tree");
2004
2005    NegateL = false;
2006    NegateR = false;
2007    NegateAfterR = false;
2008    NegateAfterAll = false;
2009  }
2010
2011  // Emit sub-trees.
2012  AArch64CC::CondCode RHSCC;
2013  SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2014  if (NegateAfterR)
2015    RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2016  SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2017  if (NegateAfterAll)
2018    OutCC = AArch64CC::getInvertedCondCode(OutCC);
2019  return CmpL;
2020}
2021
2022/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2023/// In some cases this is even possible with OR operations in the expression.
2024/// See \ref AArch64CCMP.
2025/// \see emitConjunctionRec().
2026static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2027                               AArch64CC::CondCode &OutCC) {
2028  bool DummyCanNegate;
2029  bool DummyMustBeFirst;
2030  if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2031    return SDValue();
2032
2033  return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2034}
2035
2036/// @}
2037
2038/// Returns how profitable it is to fold a comparison's operand's shift and/or
2039/// extension operations.
2040static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2041  auto isSupportedExtend = [&](SDValue V) {
2042    if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2043      return true;
2044
2045    if (V.getOpcode() == ISD::AND)
2046      if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2047        uint64_t Mask = MaskCst->getZExtValue();
2048        return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2049      }
2050
2051    return false;
2052  };
2053
2054  if (!Op.hasOneUse())
2055    return 0;
2056
2057  if (isSupportedExtend(Op))
2058    return 1;
2059
2060  unsigned Opc = Op.getOpcode();
2061  if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2062    if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2063      uint64_t Shift = ShiftCst->getZExtValue();
2064      if (isSupportedExtend(Op.getOperand(0)))
2065        return (Shift <= 4) ? 2 : 1;
2066      EVT VT = Op.getValueType();
2067      if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2068        return 1;
2069    }
2070
2071  return 0;
2072}
2073
2074static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2075                             SDValue &AArch64cc, SelectionDAG &DAG,
2076                             const SDLoc &dl) {
2077  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2078    EVT VT = RHS.getValueType();
2079    uint64_t C = RHSC->getZExtValue();
2080    if (!isLegalArithImmed(C)) {
2081      // Constant does not fit, try adjusting it by one?
2082      switch (CC) {
2083      default:
2084        break;
2085      case ISD::SETLT:
2086      case ISD::SETGE:
2087        if ((VT == MVT::i32 && C != 0x80000000 &&
2088             isLegalArithImmed((uint32_t)(C - 1))) ||
2089            (VT == MVT::i64 && C != 0x80000000ULL &&
2090             isLegalArithImmed(C - 1ULL))) {
2091          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2092          C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2093          RHS = DAG.getConstant(C, dl, VT);
2094        }
2095        break;
2096      case ISD::SETULT:
2097      case ISD::SETUGE:
2098        if ((VT == MVT::i32 && C != 0 &&
2099             isLegalArithImmed((uint32_t)(C - 1))) ||
2100            (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2101          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2102          C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2103          RHS = DAG.getConstant(C, dl, VT);
2104        }
2105        break;
2106      case ISD::SETLE:
2107      case ISD::SETGT:
2108        if ((VT == MVT::i32 && C != INT32_MAX &&
2109             isLegalArithImmed((uint32_t)(C + 1))) ||
2110            (VT == MVT::i64 && C != INT64_MAX &&
2111             isLegalArithImmed(C + 1ULL))) {
2112          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2113          C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2114          RHS = DAG.getConstant(C, dl, VT);
2115        }
2116        break;
2117      case ISD::SETULE:
2118      case ISD::SETUGT:
2119        if ((VT == MVT::i32 && C != UINT32_MAX &&
2120             isLegalArithImmed((uint32_t)(C + 1))) ||
2121            (VT == MVT::i64 && C != UINT64_MAX &&
2122             isLegalArithImmed(C + 1ULL))) {
2123          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2124          C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2125          RHS = DAG.getConstant(C, dl, VT);
2126        }
2127        break;
2128      }
2129    }
2130  }
2131
2132  // Comparisons are canonicalized so that the RHS operand is simpler than the
2133  // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2134  // can fold some shift+extend operations on the RHS operand, so swap the
2135  // operands if that can be done.
2136  //
2137  // For example:
2138  //    lsl     w13, w11, #1
2139  //    cmp     w13, w12
2140  // can be turned into:
2141  //    cmp     w12, w11, lsl #1
2142  if (!isa<ConstantSDNode>(RHS) ||
2143      !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2144    SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2145
2146    if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2147      std::swap(LHS, RHS);
2148      CC = ISD::getSetCCSwappedOperands(CC);
2149    }
2150  }
2151
2152  SDValue Cmp;
2153  AArch64CC::CondCode AArch64CC;
2154  if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2155    const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2156
2157    // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2158    // For the i8 operand, the largest immediate is 255, so this can be easily
2159    // encoded in the compare instruction. For the i16 operand, however, the
2160    // largest immediate cannot be encoded in the compare.
2161    // Therefore, use a sign extending load and cmn to avoid materializing the
2162    // -1 constant. For example,
2163    // movz w1, #65535
2164    // ldrh w0, [x0, #0]
2165    // cmp w0, w1
2166    // >
2167    // ldrsh w0, [x0, #0]
2168    // cmn w0, #1
2169    // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2170    // if and only if (sext LHS) == (sext RHS). The checks are in place to
2171    // ensure both the LHS and RHS are truly zero extended and to make sure the
2172    // transformation is profitable.
2173    if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2174        cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2175        cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2176        LHS.getNode()->hasNUsesOfValue(1, 0)) {
2177      int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2178      if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2179        SDValue SExt =
2180            DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2181                        DAG.getValueType(MVT::i16));
2182        Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2183                                                   RHS.getValueType()),
2184                             CC, dl, DAG);
2185        AArch64CC = changeIntCCToAArch64CC(CC);
2186      }
2187    }
2188
2189    if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2190      if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2191        if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2192          AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2193      }
2194    }
2195  }
2196
2197  if (!Cmp) {
2198    Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2199    AArch64CC = changeIntCCToAArch64CC(CC);
2200  }
2201  AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2202  return Cmp;
2203}
2204
2205static std::pair<SDValue, SDValue>
2206getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2207  assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2208         "Unsupported value type");
2209  SDValue Value, Overflow;
2210  SDLoc DL(Op);
2211  SDValue LHS = Op.getOperand(0);
2212  SDValue RHS = Op.getOperand(1);
2213  unsigned Opc = 0;
2214  switch (Op.getOpcode()) {
2215  default:
2216    llvm_unreachable("Unknown overflow instruction!");
2217  case ISD::SADDO:
2218    Opc = AArch64ISD::ADDS;
2219    CC = AArch64CC::VS;
2220    break;
2221  case ISD::UADDO:
2222    Opc = AArch64ISD::ADDS;
2223    CC = AArch64CC::HS;
2224    break;
2225  case ISD::SSUBO:
2226    Opc = AArch64ISD::SUBS;
2227    CC = AArch64CC::VS;
2228    break;
2229  case ISD::USUBO:
2230    Opc = AArch64ISD::SUBS;
2231    CC = AArch64CC::LO;
2232    break;
2233  // Multiply needs a little bit extra work.
2234  case ISD::SMULO:
2235  case ISD::UMULO: {
2236    CC = AArch64CC::NE;
2237    bool IsSigned = Op.getOpcode() == ISD::SMULO;
2238    if (Op.getValueType() == MVT::i32) {
2239      unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2240      // For a 32 bit multiply with overflow check we want the instruction
2241      // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2242      // need to generate the following pattern:
2243      // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2244      LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2245      RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2246      SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2247      SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2248                                DAG.getConstant(0, DL, MVT::i64));
2249      // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2250      // operation. We need to clear out the upper 32 bits, because we used a
2251      // widening multiply that wrote all 64 bits. In the end this should be a
2252      // noop.
2253      Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2254      if (IsSigned) {
2255        // The signed overflow check requires more than just a simple check for
2256        // any bit set in the upper 32 bits of the result. These bits could be
2257        // just the sign bits of a negative number. To perform the overflow
2258        // check we have to arithmetic shift right the 32nd bit of the result by
2259        // 31 bits. Then we compare the result to the upper 32 bits.
2260        SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2261                                        DAG.getConstant(32, DL, MVT::i64));
2262        UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2263        SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2264                                        DAG.getConstant(31, DL, MVT::i64));
2265        // It is important that LowerBits is last, otherwise the arithmetic
2266        // shift will not be folded into the compare (SUBS).
2267        SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2268        Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2269                       .getValue(1);
2270      } else {
2271        // The overflow check for unsigned multiply is easy. We only need to
2272        // check if any of the upper 32 bits are set. This can be done with a
2273        // CMP (shifted register). For that we need to generate the following
2274        // pattern:
2275        // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2276        SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2277                                        DAG.getConstant(32, DL, MVT::i64));
2278        SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2279        Overflow =
2280            DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2281                        DAG.getConstant(0, DL, MVT::i64),
2282                        UpperBits).getValue(1);
2283      }
2284      break;
2285    }
2286    assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2287    // For the 64 bit multiply
2288    Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2289    if (IsSigned) {
2290      SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2291      SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2292                                      DAG.getConstant(63, DL, MVT::i64));
2293      // It is important that LowerBits is last, otherwise the arithmetic
2294      // shift will not be folded into the compare (SUBS).
2295      SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2296      Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2297                     .getValue(1);
2298    } else {
2299      SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2300      SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2301      Overflow =
2302          DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2303                      DAG.getConstant(0, DL, MVT::i64),
2304                      UpperBits).getValue(1);
2305    }
2306    break;
2307  }
2308  } // switch (...)
2309
2310  if (Opc) {
2311    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2312
2313    // Emit the AArch64 operation with overflow check.
2314    Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2315    Overflow = Value.getValue(1);
2316  }
2317  return std::make_pair(Value, Overflow);
2318}
2319
2320SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2321                                             RTLIB::Libcall Call) const {
2322  bool IsStrict = Op->isStrictFPOpcode();
2323  unsigned Offset = IsStrict ? 1 : 0;
2324  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2325  SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2326  MakeLibCallOptions CallOptions;
2327  SDValue Result;
2328  SDLoc dl(Op);
2329  std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2330                                        CallOptions, dl, Chain);
2331  return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2332}
2333
2334// Returns true if the given Op is the overflow flag result of an overflow
2335// intrinsic operation.
2336static bool isOverflowIntrOpRes(SDValue Op) {
2337  unsigned Opc = Op.getOpcode();
2338  return (Op.getResNo() == 1 &&
2339          (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2340           Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2341}
2342
2343static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2344  SDValue Sel = Op.getOperand(0);
2345  SDValue Other = Op.getOperand(1);
2346  SDLoc dl(Sel);
2347
2348  // If the operand is an overflow checking operation, invert the condition
2349  // code and kill the Not operation. I.e., transform:
2350  // (xor (overflow_op_bool, 1))
2351  //   -->
2352  // (csel 1, 0, invert(cc), overflow_op_bool)
2353  // ... which later gets transformed to just a cset instruction with an
2354  // inverted condition code, rather than a cset + eor sequence.
2355  if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2356    // Only lower legal XALUO ops.
2357    if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2358      return SDValue();
2359
2360    SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2361    SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2362    AArch64CC::CondCode CC;
2363    SDValue Value, Overflow;
2364    std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2365    SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2366    return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2367                       CCVal, Overflow);
2368  }
2369  // If neither operand is a SELECT_CC, give up.
2370  if (Sel.getOpcode() != ISD::SELECT_CC)
2371    std::swap(Sel, Other);
2372  if (Sel.getOpcode() != ISD::SELECT_CC)
2373    return Op;
2374
2375  // The folding we want to perform is:
2376  // (xor x, (select_cc a, b, cc, 0, -1) )
2377  //   -->
2378  // (csel x, (xor x, -1), cc ...)
2379  //
2380  // The latter will get matched to a CSINV instruction.
2381
2382  ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2383  SDValue LHS = Sel.getOperand(0);
2384  SDValue RHS = Sel.getOperand(1);
2385  SDValue TVal = Sel.getOperand(2);
2386  SDValue FVal = Sel.getOperand(3);
2387
2388  // FIXME: This could be generalized to non-integer comparisons.
2389  if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2390    return Op;
2391
2392  ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2393  ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2394
2395  // The values aren't constants, this isn't the pattern we're looking for.
2396  if (!CFVal || !CTVal)
2397    return Op;
2398
2399  // We can commute the SELECT_CC by inverting the condition.  This
2400  // might be needed to make this fit into a CSINV pattern.
2401  if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2402    std::swap(TVal, FVal);
2403    std::swap(CTVal, CFVal);
2404    CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2405  }
2406
2407  // If the constants line up, perform the transform!
2408  if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2409    SDValue CCVal;
2410    SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2411
2412    FVal = Other;
2413    TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2414                       DAG.getConstant(-1ULL, dl, Other.getValueType()));
2415
2416    return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2417                       CCVal, Cmp);
2418  }
2419
2420  return Op;
2421}
2422
2423static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2424  EVT VT = Op.getValueType();
2425
2426  // Let legalize expand this if it isn't a legal type yet.
2427  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2428    return SDValue();
2429
2430  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2431
2432  unsigned Opc;
2433  bool ExtraOp = false;
2434  switch (Op.getOpcode()) {
2435  default:
2436    llvm_unreachable("Invalid code");
2437  case ISD::ADDC:
2438    Opc = AArch64ISD::ADDS;
2439    break;
2440  case ISD::SUBC:
2441    Opc = AArch64ISD::SUBS;
2442    break;
2443  case ISD::ADDE:
2444    Opc = AArch64ISD::ADCS;
2445    ExtraOp = true;
2446    break;
2447  case ISD::SUBE:
2448    Opc = AArch64ISD::SBCS;
2449    ExtraOp = true;
2450    break;
2451  }
2452
2453  if (!ExtraOp)
2454    return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2455  return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2456                     Op.getOperand(2));
2457}
2458
2459static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2460  // Let legalize expand this if it isn't a legal type yet.
2461  if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2462    return SDValue();
2463
2464  SDLoc dl(Op);
2465  AArch64CC::CondCode CC;
2466  // The actual operation that sets the overflow or carry flag.
2467  SDValue Value, Overflow;
2468  std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2469
2470  // We use 0 and 1 as false and true values.
2471  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2472  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2473
2474  // We use an inverted condition, because the conditional select is inverted
2475  // too. This will allow it to be selected to a single instruction:
2476  // CSINC Wd, WZR, WZR, invert(cond).
2477  SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2478  Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2479                         CCVal, Overflow);
2480
2481  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2482  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2483}
2484
2485// Prefetch operands are:
2486// 1: Address to prefetch
2487// 2: bool isWrite
2488// 3: int locality (0 = no locality ... 3 = extreme locality)
2489// 4: bool isDataCache
2490static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2491  SDLoc DL(Op);
2492  unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2493  unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2494  unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2495
2496  bool IsStream = !Locality;
2497  // When the locality number is set
2498  if (Locality) {
2499    // The front-end should have filtered out the out-of-range values
2500    assert(Locality <= 3 && "Prefetch locality out-of-range");
2501    // The locality degree is the opposite of the cache speed.
2502    // Put the number the other way around.
2503    // The encoding starts at 0 for level 1
2504    Locality = 3 - Locality;
2505  }
2506
2507  // built the mask value encoding the expected behavior.
2508  unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2509                   (!IsData << 3) |     // IsDataCache bit
2510                   (Locality << 1) |    // Cache level bits
2511                   (unsigned)IsStream;  // Stream bit
2512  return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2513                     DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2514}
2515
2516SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2517                                              SelectionDAG &DAG) const {
2518  assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2519
2520  RTLIB::Libcall LC;
2521  LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2522
2523  return LowerF128Call(Op, DAG, LC);
2524}
2525
2526SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2527                                             SelectionDAG &DAG) const {
2528  bool IsStrict = Op->isStrictFPOpcode();
2529  SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2530  if (SrcVal.getValueType() != MVT::f128) {
2531    // It's legal except when f128 is involved
2532    return Op;
2533  }
2534
2535  RTLIB::Libcall LC;
2536  LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType());
2537
2538  // FP_ROUND node has a second operand indicating whether it is known to be
2539  // precise. That doesn't take part in the LibCall so we can't directly use
2540  // LowerF128Call.
2541  MakeLibCallOptions CallOptions;
2542  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2543  SDValue Result;
2544  SDLoc dl(Op);
2545  std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2546                                        CallOptions, dl, Chain);
2547  return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2548}
2549
2550SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2551                                                    SelectionDAG &DAG) const {
2552  // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2553  // Any additional optimization in this function should be recorded
2554  // in the cost tables.
2555  EVT InVT = Op.getOperand(0).getValueType();
2556  EVT VT = Op.getValueType();
2557  unsigned NumElts = InVT.getVectorNumElements();
2558
2559  // f16 conversions are promoted to f32 when full fp16 is not supported.
2560  if (InVT.getVectorElementType() == MVT::f16 &&
2561      !Subtarget->hasFullFP16()) {
2562    MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2563    SDLoc dl(Op);
2564    return DAG.getNode(
2565        Op.getOpcode(), dl, Op.getValueType(),
2566        DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2567  }
2568
2569  if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2570    SDLoc dl(Op);
2571    SDValue Cv =
2572        DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2573                    Op.getOperand(0));
2574    return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2575  }
2576
2577  if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2578    SDLoc dl(Op);
2579    MVT ExtVT =
2580        MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2581                         VT.getVectorNumElements());
2582    SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2583    return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2584  }
2585
2586  // Type changing conversions are illegal.
2587  return Op;
2588}
2589
2590SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2591                                              SelectionDAG &DAG) const {
2592  bool IsStrict = Op->isStrictFPOpcode();
2593  SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2594
2595  if (SrcVal.getValueType().isVector())
2596    return LowerVectorFP_TO_INT(Op, DAG);
2597
2598  // f16 conversions are promoted to f32 when full fp16 is not supported.
2599  if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2600    assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2601    SDLoc dl(Op);
2602    return DAG.getNode(
2603        Op.getOpcode(), dl, Op.getValueType(),
2604        DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2605  }
2606
2607  if (SrcVal.getValueType() != MVT::f128) {
2608    // It's legal except when f128 is involved
2609    return Op;
2610  }
2611
2612  RTLIB::Libcall LC;
2613  if (Op.getOpcode() == ISD::FP_TO_SINT ||
2614      Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2615    LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2616  else
2617    LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2618
2619  return LowerF128Call(Op, DAG, LC);
2620}
2621
2622static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2623  // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2624  // Any additional optimization in this function should be recorded
2625  // in the cost tables.
2626  EVT VT = Op.getValueType();
2627  SDLoc dl(Op);
2628  SDValue In = Op.getOperand(0);
2629  EVT InVT = In.getValueType();
2630
2631  if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2632    MVT CastVT =
2633        MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2634                         InVT.getVectorNumElements());
2635    In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2636    return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2637  }
2638
2639  if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2640    unsigned CastOpc =
2641        Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2642    EVT CastVT = VT.changeVectorElementTypeToInteger();
2643    In = DAG.getNode(CastOpc, dl, CastVT, In);
2644    return DAG.getNode(Op.getOpcode(), dl, VT, In);
2645  }
2646
2647  return Op;
2648}
2649
2650SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2651                                            SelectionDAG &DAG) const {
2652  if (Op.getValueType().isVector())
2653    return LowerVectorINT_TO_FP(Op, DAG);
2654
2655  bool IsStrict = Op->isStrictFPOpcode();
2656  SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2657
2658  // f16 conversions are promoted to f32 when full fp16 is not supported.
2659  if (Op.getValueType() == MVT::f16 &&
2660      !Subtarget->hasFullFP16()) {
2661    assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2662    SDLoc dl(Op);
2663    return DAG.getNode(
2664        ISD::FP_ROUND, dl, MVT::f16,
2665        DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2666        DAG.getIntPtrConstant(0, dl));
2667  }
2668
2669  // i128 conversions are libcalls.
2670  if (SrcVal.getValueType() == MVT::i128)
2671    return SDValue();
2672
2673  // Other conversions are legal, unless it's to the completely software-based
2674  // fp128.
2675  if (Op.getValueType() != MVT::f128)
2676    return Op;
2677
2678  RTLIB::Libcall LC;
2679  if (Op.getOpcode() == ISD::SINT_TO_FP ||
2680      Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2681    LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2682  else
2683    LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2684
2685  return LowerF128Call(Op, DAG, LC);
2686}
2687
2688SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2689                                            SelectionDAG &DAG) const {
2690  // For iOS, we want to call an alternative entry point: __sincos_stret,
2691  // which returns the values in two S / D registers.
2692  SDLoc dl(Op);
2693  SDValue Arg = Op.getOperand(0);
2694  EVT ArgVT = Arg.getValueType();
2695  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2696
2697  ArgListTy Args;
2698  ArgListEntry Entry;
2699
2700  Entry.Node = Arg;
2701  Entry.Ty = ArgTy;
2702  Entry.IsSExt = false;
2703  Entry.IsZExt = false;
2704  Args.push_back(Entry);
2705
2706  RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2707                                        : RTLIB::SINCOS_STRET_F32;
2708  const char *LibcallName = getLibcallName(LC);
2709  SDValue Callee =
2710      DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2711
2712  StructType *RetTy = StructType::get(ArgTy, ArgTy);
2713  TargetLowering::CallLoweringInfo CLI(DAG);
2714  CLI.setDebugLoc(dl)
2715      .setChain(DAG.getEntryNode())
2716      .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2717
2718  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2719  return CallResult.first;
2720}
2721
2722static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2723  if (Op.getValueType() != MVT::f16)
2724    return SDValue();
2725
2726  assert(Op.getOperand(0).getValueType() == MVT::i16);
2727  SDLoc DL(Op);
2728
2729  Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2730  Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2731  return SDValue(
2732      DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2733                         DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2734      0);
2735}
2736
2737static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2738  if (OrigVT.getSizeInBits() >= 64)
2739    return OrigVT;
2740
2741  assert(OrigVT.isSimple() && "Expecting a simple value type");
2742
2743  MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2744  switch (OrigSimpleTy) {
2745  default: llvm_unreachable("Unexpected Vector Type");
2746  case MVT::v2i8:
2747  case MVT::v2i16:
2748     return MVT::v2i32;
2749  case MVT::v4i8:
2750    return  MVT::v4i16;
2751  }
2752}
2753
2754static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2755                                                 const EVT &OrigTy,
2756                                                 const EVT &ExtTy,
2757                                                 unsigned ExtOpcode) {
2758  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2759  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2760  // 64-bits we need to insert a new extension so that it will be 64-bits.
2761  assert(ExtTy.is128BitVector() && "Unexpected extension size");
2762  if (OrigTy.getSizeInBits() >= 64)
2763    return N;
2764
2765  // Must extend size to at least 64 bits to be used as an operand for VMULL.
2766  EVT NewVT = getExtensionTo64Bits(OrigTy);
2767
2768  return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2769}
2770
2771static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2772                                   bool isSigned) {
2773  EVT VT = N->getValueType(0);
2774
2775  if (N->getOpcode() != ISD::BUILD_VECTOR)
2776    return false;
2777
2778  for (const SDValue &Elt : N->op_values()) {
2779    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2780      unsigned EltSize = VT.getScalarSizeInBits();
2781      unsigned HalfSize = EltSize / 2;
2782      if (isSigned) {
2783        if (!isIntN(HalfSize, C->getSExtValue()))
2784          return false;
2785      } else {
2786        if (!isUIntN(HalfSize, C->getZExtValue()))
2787          return false;
2788      }
2789      continue;
2790    }
2791    return false;
2792  }
2793
2794  return true;
2795}
2796
2797static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2798  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2799    return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2800                                             N->getOperand(0)->getValueType(0),
2801                                             N->getValueType(0),
2802                                             N->getOpcode());
2803
2804  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2805  EVT VT = N->getValueType(0);
2806  SDLoc dl(N);
2807  unsigned EltSize = VT.getScalarSizeInBits() / 2;
2808  unsigned NumElts = VT.getVectorNumElements();
2809  MVT TruncVT = MVT::getIntegerVT(EltSize);
2810  SmallVector<SDValue, 8> Ops;
2811  for (unsigned i = 0; i != NumElts; ++i) {
2812    ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2813    const APInt &CInt = C->getAPIntValue();
2814    // Element types smaller than 32 bits are not legal, so use i32 elements.
2815    // The values are implicitly truncated so sext vs. zext doesn't matter.
2816    Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2817  }
2818  return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2819}
2820
2821static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2822  return N->getOpcode() == ISD::SIGN_EXTEND ||
2823         isExtendedBUILD_VECTOR(N, DAG, true);
2824}
2825
2826static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2827  return N->getOpcode() == ISD::ZERO_EXTEND ||
2828         isExtendedBUILD_VECTOR(N, DAG, false);
2829}
2830
2831static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2832  unsigned Opcode = N->getOpcode();
2833  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2834    SDNode *N0 = N->getOperand(0).getNode();
2835    SDNode *N1 = N->getOperand(1).getNode();
2836    return N0->hasOneUse() && N1->hasOneUse() &&
2837      isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2838  }
2839  return false;
2840}
2841
2842static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2843  unsigned Opcode = N->getOpcode();
2844  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2845    SDNode *N0 = N->getOperand(0).getNode();
2846    SDNode *N1 = N->getOperand(1).getNode();
2847    return N0->hasOneUse() && N1->hasOneUse() &&
2848      isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2849  }
2850  return false;
2851}
2852
2853SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2854                                                SelectionDAG &DAG) const {
2855  // The rounding mode is in bits 23:22 of the FPSCR.
2856  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2857  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2858  // so that the shift + and get folded into a bitfield extract.
2859  SDLoc dl(Op);
2860
2861  SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2862                                DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2863                                                MVT::i64));
2864  SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2865  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2866                                  DAG.getConstant(1U << 22, dl, MVT::i32));
2867  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2868                              DAG.getConstant(22, dl, MVT::i32));
2869  return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2870                     DAG.getConstant(3, dl, MVT::i32));
2871}
2872
2873static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2874  // Multiplications are only custom-lowered for 128-bit vectors so that
2875  // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2876  EVT VT = Op.getValueType();
2877  assert(VT.is128BitVector() && VT.isInteger() &&
2878         "unexpected type for custom-lowering ISD::MUL");
2879  SDNode *N0 = Op.getOperand(0).getNode();
2880  SDNode *N1 = Op.getOperand(1).getNode();
2881  unsigned NewOpc = 0;
2882  bool isMLA = false;
2883  bool isN0SExt = isSignExtended(N0, DAG);
2884  bool isN1SExt = isSignExtended(N1, DAG);
2885  if (isN0SExt && isN1SExt)
2886    NewOpc = AArch64ISD::SMULL;
2887  else {
2888    bool isN0ZExt = isZeroExtended(N0, DAG);
2889    bool isN1ZExt = isZeroExtended(N1, DAG);
2890    if (isN0ZExt && isN1ZExt)
2891      NewOpc = AArch64ISD::UMULL;
2892    else if (isN1SExt || isN1ZExt) {
2893      // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2894      // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2895      if (isN1SExt && isAddSubSExt(N0, DAG)) {
2896        NewOpc = AArch64ISD::SMULL;
2897        isMLA = true;
2898      } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2899        NewOpc =  AArch64ISD::UMULL;
2900        isMLA = true;
2901      } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2902        std::swap(N0, N1);
2903        NewOpc =  AArch64ISD::UMULL;
2904        isMLA = true;
2905      }
2906    }
2907
2908    if (!NewOpc) {
2909      if (VT == MVT::v2i64)
2910        // Fall through to expand this.  It is not legal.
2911        return SDValue();
2912      else
2913        // Other vector multiplications are legal.
2914        return Op;
2915    }
2916  }
2917
2918  // Legalize to a S/UMULL instruction
2919  SDLoc DL(Op);
2920  SDValue Op0;
2921  SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2922  if (!isMLA) {
2923    Op0 = skipExtensionForVectorMULL(N0, DAG);
2924    assert(Op0.getValueType().is64BitVector() &&
2925           Op1.getValueType().is64BitVector() &&
2926           "unexpected types for extended operands to VMULL");
2927    return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2928  }
2929  // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2930  // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2931  // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2932  SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2933  SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2934  EVT Op1VT = Op1.getValueType();
2935  return DAG.getNode(N0->getOpcode(), DL, VT,
2936                     DAG.getNode(NewOpc, DL, VT,
2937                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2938                     DAG.getNode(NewOpc, DL, VT,
2939                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2940}
2941
2942SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2943                                                     SelectionDAG &DAG) const {
2944  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2945  SDLoc dl(Op);
2946  switch (IntNo) {
2947  default: return SDValue();    // Don't custom lower most intrinsics.
2948  case Intrinsic::thread_pointer: {
2949    EVT PtrVT = getPointerTy(DAG.getDataLayout());
2950    return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2951  }
2952  case Intrinsic::aarch64_neon_abs: {
2953    EVT Ty = Op.getValueType();
2954    if (Ty == MVT::i64) {
2955      SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2956                                   Op.getOperand(1));
2957      Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2958      return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2959    } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2960      return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2961    } else {
2962      report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2963    }
2964  }
2965  case Intrinsic::aarch64_neon_smax:
2966    return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2967                       Op.getOperand(1), Op.getOperand(2));
2968  case Intrinsic::aarch64_neon_umax:
2969    return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2970                       Op.getOperand(1), Op.getOperand(2));
2971  case Intrinsic::aarch64_neon_smin:
2972    return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2973                       Op.getOperand(1), Op.getOperand(2));
2974  case Intrinsic::aarch64_neon_umin:
2975    return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2976                       Op.getOperand(1), Op.getOperand(2));
2977
2978  case Intrinsic::aarch64_sve_sunpkhi:
2979    return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
2980                       Op.getOperand(1));
2981  case Intrinsic::aarch64_sve_sunpklo:
2982    return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
2983                       Op.getOperand(1));
2984  case Intrinsic::aarch64_sve_uunpkhi:
2985    return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
2986                       Op.getOperand(1));
2987  case Intrinsic::aarch64_sve_uunpklo:
2988    return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
2989                       Op.getOperand(1));
2990  case Intrinsic::aarch64_sve_clasta_n:
2991    return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
2992                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2993  case Intrinsic::aarch64_sve_clastb_n:
2994    return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
2995                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2996  case Intrinsic::aarch64_sve_lasta:
2997    return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
2998                       Op.getOperand(1), Op.getOperand(2));
2999  case Intrinsic::aarch64_sve_lastb:
3000    return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3001                       Op.getOperand(1), Op.getOperand(2));
3002  case Intrinsic::aarch64_sve_rev:
3003    return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3004                       Op.getOperand(1));
3005  case Intrinsic::aarch64_sve_tbl:
3006    return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3007                       Op.getOperand(1), Op.getOperand(2));
3008  case Intrinsic::aarch64_sve_trn1:
3009    return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3010                       Op.getOperand(1), Op.getOperand(2));
3011  case Intrinsic::aarch64_sve_trn2:
3012    return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3013                       Op.getOperand(1), Op.getOperand(2));
3014  case Intrinsic::aarch64_sve_uzp1:
3015    return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3016                       Op.getOperand(1), Op.getOperand(2));
3017  case Intrinsic::aarch64_sve_uzp2:
3018    return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3019                       Op.getOperand(1), Op.getOperand(2));
3020  case Intrinsic::aarch64_sve_zip1:
3021    return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3022                       Op.getOperand(1), Op.getOperand(2));
3023  case Intrinsic::aarch64_sve_zip2:
3024    return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3025                       Op.getOperand(1), Op.getOperand(2));
3026  case Intrinsic::aarch64_sve_ptrue:
3027    return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3028                       Op.getOperand(1));
3029
3030  case Intrinsic::aarch64_sve_insr: {
3031    SDValue Scalar = Op.getOperand(2);
3032    EVT ScalarTy = Scalar.getValueType();
3033    if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3034      Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3035
3036    return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3037                       Op.getOperand(1), Scalar);
3038  }
3039
3040  case Intrinsic::localaddress: {
3041    const auto &MF = DAG.getMachineFunction();
3042    const auto *RegInfo = Subtarget->getRegisterInfo();
3043    unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3044    return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3045                              Op.getSimpleValueType());
3046  }
3047
3048  case Intrinsic::eh_recoverfp: {
3049    // FIXME: This needs to be implemented to correctly handle highly aligned
3050    // stack objects. For now we simply return the incoming FP. Refer D53541
3051    // for more details.
3052    SDValue FnOp = Op.getOperand(1);
3053    SDValue IncomingFPOp = Op.getOperand(2);
3054    GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3055    auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3056    if (!Fn)
3057      report_fatal_error(
3058          "llvm.eh.recoverfp must take a function as the first argument");
3059    return IncomingFPOp;
3060  }
3061  }
3062}
3063
3064bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3065  return ExtVal.getValueType().isScalableVector();
3066}
3067
3068// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3069static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3070                                        EVT VT, EVT MemVT,
3071                                        SelectionDAG &DAG) {
3072  assert(VT.isVector() && "VT should be a vector type");
3073  assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3074
3075  SDValue Value = ST->getValue();
3076
3077  // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3078  // the word lane which represent the v4i8 subvector.  It optimizes the store
3079  // to:
3080  //
3081  //   xtn  v0.8b, v0.8h
3082  //   str  s0, [x0]
3083
3084  SDValue Undef = DAG.getUNDEF(MVT::i16);
3085  SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3086                                        {Undef, Undef, Undef, Undef});
3087
3088  SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3089                                 Value, UndefVec);
3090  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3091
3092  Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3093  SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3094                                     Trunc, DAG.getConstant(0, DL, MVT::i64));
3095
3096  return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3097                      ST->getBasePtr(), ST->getMemOperand());
3098}
3099
3100// Custom lowering for any store, vector or scalar and/or default or with
3101// a truncate operations.  Currently only custom lower truncate operation
3102// from vector v4i16 to v4i8 or volatile stores of i128.
3103SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3104                                          SelectionDAG &DAG) const {
3105  SDLoc Dl(Op);
3106  StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3107  assert (StoreNode && "Can only custom lower store nodes");
3108
3109  SDValue Value = StoreNode->getValue();
3110
3111  EVT VT = Value.getValueType();
3112  EVT MemVT = StoreNode->getMemoryVT();
3113
3114  if (VT.isVector()) {
3115    unsigned AS = StoreNode->getAddressSpace();
3116    unsigned Align = StoreNode->getAlignment();
3117    if (Align < MemVT.getStoreSize() &&
3118        !allowsMisalignedMemoryAccesses(MemVT, AS, Align,
3119                                        StoreNode->getMemOperand()->getFlags(),
3120                                        nullptr)) {
3121      return scalarizeVectorStore(StoreNode, DAG);
3122    }
3123
3124    if (StoreNode->isTruncatingStore()) {
3125      return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3126    }
3127  } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3128    assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3129    SDValue Lo =
3130        DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3131                    DAG.getConstant(0, Dl, MVT::i64));
3132    SDValue Hi =
3133        DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3134                    DAG.getConstant(1, Dl, MVT::i64));
3135    SDValue Result = DAG.getMemIntrinsicNode(
3136        AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3137        {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3138        StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3139    return Result;
3140  }
3141
3142  return SDValue();
3143}
3144
3145SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3146                                              SelectionDAG &DAG) const {
3147  LLVM_DEBUG(dbgs() << "Custom lowering: ");
3148  LLVM_DEBUG(Op.dump());
3149
3150  switch (Op.getOpcode()) {
3151  default:
3152    llvm_unreachable("unimplemented operand");
3153    return SDValue();
3154  case ISD::BITCAST:
3155    return LowerBITCAST(Op, DAG);
3156  case ISD::GlobalAddress:
3157    return LowerGlobalAddress(Op, DAG);
3158  case ISD::GlobalTLSAddress:
3159    return LowerGlobalTLSAddress(Op, DAG);
3160  case ISD::SETCC:
3161  case ISD::STRICT_FSETCC:
3162  case ISD::STRICT_FSETCCS:
3163    return LowerSETCC(Op, DAG);
3164  case ISD::BR_CC:
3165    return LowerBR_CC(Op, DAG);
3166  case ISD::SELECT:
3167    return LowerSELECT(Op, DAG);
3168  case ISD::SELECT_CC:
3169    return LowerSELECT_CC(Op, DAG);
3170  case ISD::JumpTable:
3171    return LowerJumpTable(Op, DAG);
3172  case ISD::BR_JT:
3173    return LowerBR_JT(Op, DAG);
3174  case ISD::ConstantPool:
3175    return LowerConstantPool(Op, DAG);
3176  case ISD::BlockAddress:
3177    return LowerBlockAddress(Op, DAG);
3178  case ISD::VASTART:
3179    return LowerVASTART(Op, DAG);
3180  case ISD::VACOPY:
3181    return LowerVACOPY(Op, DAG);
3182  case ISD::VAARG:
3183    return LowerVAARG(Op, DAG);
3184  case ISD::ADDC:
3185  case ISD::ADDE:
3186  case ISD::SUBC:
3187  case ISD::SUBE:
3188    return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3189  case ISD::SADDO:
3190  case ISD::UADDO:
3191  case ISD::SSUBO:
3192  case ISD::USUBO:
3193  case ISD::SMULO:
3194  case ISD::UMULO:
3195    return LowerXALUO(Op, DAG);
3196  case ISD::FADD:
3197    return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3198  case ISD::FSUB:
3199    return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3200  case ISD::FMUL:
3201    return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3202  case ISD::FDIV:
3203    return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3204  case ISD::FP_ROUND:
3205  case ISD::STRICT_FP_ROUND:
3206    return LowerFP_ROUND(Op, DAG);
3207  case ISD::FP_EXTEND:
3208    return LowerFP_EXTEND(Op, DAG);
3209  case ISD::FRAMEADDR:
3210    return LowerFRAMEADDR(Op, DAG);
3211  case ISD::SPONENTRY:
3212    return LowerSPONENTRY(Op, DAG);
3213  case ISD::RETURNADDR:
3214    return LowerRETURNADDR(Op, DAG);
3215  case ISD::ADDROFRETURNADDR:
3216    return LowerADDROFRETURNADDR(Op, DAG);
3217  case ISD::INSERT_VECTOR_ELT:
3218    return LowerINSERT_VECTOR_ELT(Op, DAG);
3219  case ISD::EXTRACT_VECTOR_ELT:
3220    return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3221  case ISD::BUILD_VECTOR:
3222    return LowerBUILD_VECTOR(Op, DAG);
3223  case ISD::VECTOR_SHUFFLE:
3224    return LowerVECTOR_SHUFFLE(Op, DAG);
3225  case ISD::SPLAT_VECTOR:
3226    return LowerSPLAT_VECTOR(Op, DAG);
3227  case ISD::EXTRACT_SUBVECTOR:
3228    return LowerEXTRACT_SUBVECTOR(Op, DAG);
3229  case ISD::SRA:
3230  case ISD::SRL:
3231  case ISD::SHL:
3232    return LowerVectorSRA_SRL_SHL(Op, DAG);
3233  case ISD::SHL_PARTS:
3234    return LowerShiftLeftParts(Op, DAG);
3235  case ISD::SRL_PARTS:
3236  case ISD::SRA_PARTS:
3237    return LowerShiftRightParts(Op, DAG);
3238  case ISD::CTPOP:
3239    return LowerCTPOP(Op, DAG);
3240  case ISD::FCOPYSIGN:
3241    return LowerFCOPYSIGN(Op, DAG);
3242  case ISD::OR:
3243    return LowerVectorOR(Op, DAG);
3244  case ISD::XOR:
3245    return LowerXOR(Op, DAG);
3246  case ISD::PREFETCH:
3247    return LowerPREFETCH(Op, DAG);
3248  case ISD::SINT_TO_FP:
3249  case ISD::UINT_TO_FP:
3250  case ISD::STRICT_SINT_TO_FP:
3251  case ISD::STRICT_UINT_TO_FP:
3252    return LowerINT_TO_FP(Op, DAG);
3253  case ISD::FP_TO_SINT:
3254  case ISD::FP_TO_UINT:
3255  case ISD::STRICT_FP_TO_SINT:
3256  case ISD::STRICT_FP_TO_UINT:
3257    return LowerFP_TO_INT(Op, DAG);
3258  case ISD::FSINCOS:
3259    return LowerFSINCOS(Op, DAG);
3260  case ISD::FLT_ROUNDS_:
3261    return LowerFLT_ROUNDS_(Op, DAG);
3262  case ISD::MUL:
3263    return LowerMUL(Op, DAG);
3264  case ISD::INTRINSIC_WO_CHAIN:
3265    return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3266  case ISD::STORE:
3267    return LowerSTORE(Op, DAG);
3268  case ISD::VECREDUCE_ADD:
3269  case ISD::VECREDUCE_SMAX:
3270  case ISD::VECREDUCE_SMIN:
3271  case ISD::VECREDUCE_UMAX:
3272  case ISD::VECREDUCE_UMIN:
3273  case ISD::VECREDUCE_FMAX:
3274  case ISD::VECREDUCE_FMIN:
3275    return LowerVECREDUCE(Op, DAG);
3276  case ISD::ATOMIC_LOAD_SUB:
3277    return LowerATOMIC_LOAD_SUB(Op, DAG);
3278  case ISD::ATOMIC_LOAD_AND:
3279    return LowerATOMIC_LOAD_AND(Op, DAG);
3280  case ISD::DYNAMIC_STACKALLOC:
3281    return LowerDYNAMIC_STACKALLOC(Op, DAG);
3282  }
3283}
3284
3285//===----------------------------------------------------------------------===//
3286//                      Calling Convention Implementation
3287//===----------------------------------------------------------------------===//
3288
3289/// Selects the correct CCAssignFn for a given CallingConvention value.
3290CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3291                                                     bool IsVarArg) const {
3292  switch (CC) {
3293  default:
3294    report_fatal_error("Unsupported calling convention.");
3295  case CallingConv::AArch64_SVE_VectorCall:
3296    // Calling SVE functions is currently not yet supported.
3297    report_fatal_error("Unsupported calling convention.");
3298  case CallingConv::WebKit_JS:
3299    return CC_AArch64_WebKit_JS;
3300  case CallingConv::GHC:
3301    return CC_AArch64_GHC;
3302  case CallingConv::C:
3303  case CallingConv::Fast:
3304  case CallingConv::PreserveMost:
3305  case CallingConv::CXX_FAST_TLS:
3306  case CallingConv::Swift:
3307    if (Subtarget->isTargetWindows() && IsVarArg)
3308      return CC_AArch64_Win64_VarArg;
3309    if (!Subtarget->isTargetDarwin())
3310      return CC_AArch64_AAPCS;
3311    if (!IsVarArg)
3312      return CC_AArch64_DarwinPCS;
3313    return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3314                                      : CC_AArch64_DarwinPCS_VarArg;
3315   case CallingConv::Win64:
3316    return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3317   case CallingConv::CFGuard_Check:
3318     return CC_AArch64_Win64_CFGuard_Check;
3319   case CallingConv::AArch64_VectorCall:
3320     return CC_AArch64_AAPCS;
3321  }
3322}
3323
3324CCAssignFn *
3325AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3326  return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3327                                      : RetCC_AArch64_AAPCS;
3328}
3329
3330SDValue AArch64TargetLowering::LowerFormalArguments(
3331    SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3332    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3333    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3334  MachineFunction &MF = DAG.getMachineFunction();
3335  MachineFrameInfo &MFI = MF.getFrameInfo();
3336  bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3337
3338  // Assign locations to all of the incoming arguments.
3339  SmallVector<CCValAssign, 16> ArgLocs;
3340  DenseMap<unsigned, SDValue> CopiedRegs;
3341  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3342                 *DAG.getContext());
3343
3344  // At this point, Ins[].VT may already be promoted to i32. To correctly
3345  // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3346  // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3347  // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3348  // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3349  // LocVT.
3350  unsigned NumArgs = Ins.size();
3351  Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3352  unsigned CurArgIdx = 0;
3353  for (unsigned i = 0; i != NumArgs; ++i) {
3354    MVT ValVT = Ins[i].VT;
3355    if (Ins[i].isOrigArg()) {
3356      std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3357      CurArgIdx = Ins[i].getOrigArgIndex();
3358
3359      // Get type of the original argument.
3360      EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3361                                  /*AllowUnknown*/ true);
3362      MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3363      // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3364      if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3365        ValVT = MVT::i8;
3366      else if (ActualMVT == MVT::i16)
3367        ValVT = MVT::i16;
3368    }
3369    CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3370    bool Res =
3371        AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3372    assert(!Res && "Call operand has unhandled type");
3373    (void)Res;
3374  }
3375  assert(ArgLocs.size() == Ins.size());
3376  SmallVector<SDValue, 16> ArgValues;
3377  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3378    CCValAssign &VA = ArgLocs[i];
3379
3380    if (Ins[i].Flags.isByVal()) {
3381      // Byval is used for HFAs in the PCS, but the system should work in a
3382      // non-compliant manner for larger structs.
3383      EVT PtrVT = getPointerTy(DAG.getDataLayout());
3384      int Size = Ins[i].Flags.getByValSize();
3385      unsigned NumRegs = (Size + 7) / 8;
3386
3387      // FIXME: This works on big-endian for composite byvals, which are the common
3388      // case. It should also work for fundamental types too.
3389      unsigned FrameIdx =
3390        MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3391      SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3392      InVals.push_back(FrameIdxN);
3393
3394      continue;
3395    }
3396
3397    SDValue ArgValue;
3398    if (VA.isRegLoc()) {
3399      // Arguments stored in registers.
3400      EVT RegVT = VA.getLocVT();
3401      const TargetRegisterClass *RC;
3402
3403      if (RegVT == MVT::i32)
3404        RC = &AArch64::GPR32RegClass;
3405      else if (RegVT == MVT::i64)
3406        RC = &AArch64::GPR64RegClass;
3407      else if (RegVT == MVT::f16)
3408        RC = &AArch64::FPR16RegClass;
3409      else if (RegVT == MVT::f32)
3410        RC = &AArch64::FPR32RegClass;
3411      else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3412        RC = &AArch64::FPR64RegClass;
3413      else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3414        RC = &AArch64::FPR128RegClass;
3415      else if (RegVT.isScalableVector() &&
3416               RegVT.getVectorElementType() == MVT::i1)
3417        RC = &AArch64::PPRRegClass;
3418      else if (RegVT.isScalableVector())
3419        RC = &AArch64::ZPRRegClass;
3420      else
3421        llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3422
3423      // Transform the arguments in physical registers into virtual ones.
3424      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3425      ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3426
3427      // If this is an 8, 16 or 32-bit value, it is really passed promoted
3428      // to 64 bits.  Insert an assert[sz]ext to capture this, then
3429      // truncate to the right size.
3430      switch (VA.getLocInfo()) {
3431      default:
3432        llvm_unreachable("Unknown loc info!");
3433      case CCValAssign::Full:
3434        break;
3435      case CCValAssign::Indirect:
3436        assert(VA.getValVT().isScalableVector() &&
3437               "Only scalable vectors can be passed indirectly");
3438        llvm_unreachable("Spilling of SVE vectors not yet implemented");
3439      case CCValAssign::BCvt:
3440        ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3441        break;
3442      case CCValAssign::AExt:
3443      case CCValAssign::SExt:
3444      case CCValAssign::ZExt:
3445        break;
3446      case CCValAssign::AExtUpper:
3447        ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3448                               DAG.getConstant(32, DL, RegVT));
3449        ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3450        break;
3451      }
3452    } else { // VA.isRegLoc()
3453      assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3454      unsigned ArgOffset = VA.getLocMemOffset();
3455      unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3456
3457      uint32_t BEAlign = 0;
3458      if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3459          !Ins[i].Flags.isInConsecutiveRegs())
3460        BEAlign = 8 - ArgSize;
3461
3462      int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3463
3464      // Create load nodes to retrieve arguments from the stack.
3465      SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3466
3467      // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3468      ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3469      MVT MemVT = VA.getValVT();
3470
3471      switch (VA.getLocInfo()) {
3472      default:
3473        break;
3474      case CCValAssign::Trunc:
3475      case CCValAssign::BCvt:
3476        MemVT = VA.getLocVT();
3477        break;
3478      case CCValAssign::Indirect:
3479        assert(VA.getValVT().isScalableVector() &&
3480               "Only scalable vectors can be passed indirectly");
3481        llvm_unreachable("Spilling of SVE vectors not yet implemented");
3482      case CCValAssign::SExt:
3483        ExtType = ISD::SEXTLOAD;
3484        break;
3485      case CCValAssign::ZExt:
3486        ExtType = ISD::ZEXTLOAD;
3487        break;
3488      case CCValAssign::AExt:
3489        ExtType = ISD::EXTLOAD;
3490        break;
3491      }
3492
3493      ArgValue = DAG.getExtLoad(
3494          ExtType, DL, VA.getLocVT(), Chain, FIN,
3495          MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3496          MemVT);
3497
3498    }
3499    if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3500      ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3501                             ArgValue, DAG.getValueType(MVT::i32));
3502    InVals.push_back(ArgValue);
3503  }
3504
3505  // varargs
3506  AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3507  if (isVarArg) {
3508    if (!Subtarget->isTargetDarwin() || IsWin64) {
3509      // The AAPCS variadic function ABI is identical to the non-variadic
3510      // one. As a result there may be more arguments in registers and we should
3511      // save them for future reference.
3512      // Win64 variadic functions also pass arguments in registers, but all float
3513      // arguments are passed in integer registers.
3514      saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3515    }
3516
3517    // This will point to the next argument passed via stack.
3518    unsigned StackOffset = CCInfo.getNextStackOffset();
3519    // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3520    StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3521    FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3522
3523    if (MFI.hasMustTailInVarArgFunc()) {
3524      SmallVector<MVT, 2> RegParmTypes;
3525      RegParmTypes.push_back(MVT::i64);
3526      RegParmTypes.push_back(MVT::f128);
3527      // Compute the set of forwarded registers. The rest are scratch.
3528      SmallVectorImpl<ForwardedRegister> &Forwards =
3529                                       FuncInfo->getForwardedMustTailRegParms();
3530      CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3531                                               CC_AArch64_AAPCS);
3532
3533      // Conservatively forward X8, since it might be used for aggregate return.
3534      if (!CCInfo.isAllocated(AArch64::X8)) {
3535        unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3536        Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3537      }
3538    }
3539  }
3540
3541  // On Windows, InReg pointers must be returned, so record the pointer in a
3542  // virtual register at the start of the function so it can be returned in the
3543  // epilogue.
3544  if (IsWin64) {
3545    for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3546      if (Ins[I].Flags.isInReg()) {
3547        assert(!FuncInfo->getSRetReturnReg());
3548
3549        MVT PtrTy = getPointerTy(DAG.getDataLayout());
3550        Register Reg =
3551            MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3552        FuncInfo->setSRetReturnReg(Reg);
3553
3554        SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3555        Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3556        break;
3557      }
3558    }
3559  }
3560
3561  unsigned StackArgSize = CCInfo.getNextStackOffset();
3562  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3563  if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3564    // This is a non-standard ABI so by fiat I say we're allowed to make full
3565    // use of the stack area to be popped, which must be aligned to 16 bytes in
3566    // any case:
3567    StackArgSize = alignTo(StackArgSize, 16);
3568
3569    // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3570    // a multiple of 16.
3571    FuncInfo->setArgumentStackToRestore(StackArgSize);
3572
3573    // This realignment carries over to the available bytes below. Our own
3574    // callers will guarantee the space is free by giving an aligned value to
3575    // CALLSEQ_START.
3576  }
3577  // Even if we're not expected to free up the space, it's useful to know how
3578  // much is there while considering tail calls (because we can reuse it).
3579  FuncInfo->setBytesInStackArgArea(StackArgSize);
3580
3581  if (Subtarget->hasCustomCallingConv())
3582    Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3583
3584  return Chain;
3585}
3586
3587void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3588                                                SelectionDAG &DAG,
3589                                                const SDLoc &DL,
3590                                                SDValue &Chain) const {
3591  MachineFunction &MF = DAG.getMachineFunction();
3592  MachineFrameInfo &MFI = MF.getFrameInfo();
3593  AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3594  auto PtrVT = getPointerTy(DAG.getDataLayout());
3595  bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3596
3597  SmallVector<SDValue, 8> MemOps;
3598
3599  static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3600                                          AArch64::X3, AArch64::X4, AArch64::X5,
3601                                          AArch64::X6, AArch64::X7 };
3602  static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3603  unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3604
3605  unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3606  int GPRIdx = 0;
3607  if (GPRSaveSize != 0) {
3608    if (IsWin64) {
3609      GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3610      if (GPRSaveSize & 15)
3611        // The extra size here, if triggered, will always be 8.
3612        MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3613    } else
3614      GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3615
3616    SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3617
3618    for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3619      unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3620      SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3621      SDValue Store = DAG.getStore(
3622          Val.getValue(1), DL, Val, FIN,
3623          IsWin64
3624              ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3625                                                  GPRIdx,
3626                                                  (i - FirstVariadicGPR) * 8)
3627              : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3628      MemOps.push_back(Store);
3629      FIN =
3630          DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3631    }
3632  }
3633  FuncInfo->setVarArgsGPRIndex(GPRIdx);
3634  FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3635
3636  if (Subtarget->hasFPARMv8() && !IsWin64) {
3637    static const MCPhysReg FPRArgRegs[] = {
3638        AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3639        AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3640    static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3641    unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3642
3643    unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3644    int FPRIdx = 0;
3645    if (FPRSaveSize != 0) {
3646      FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3647
3648      SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3649
3650      for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3651        unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3652        SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3653
3654        SDValue Store = DAG.getStore(
3655            Val.getValue(1), DL, Val, FIN,
3656            MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3657        MemOps.push_back(Store);
3658        FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3659                          DAG.getConstant(16, DL, PtrVT));
3660      }
3661    }
3662    FuncInfo->setVarArgsFPRIndex(FPRIdx);
3663    FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3664  }
3665
3666  if (!MemOps.empty()) {
3667    Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3668  }
3669}
3670
3671/// LowerCallResult - Lower the result values of a call into the
3672/// appropriate copies out of appropriate physical registers.
3673SDValue AArch64TargetLowering::LowerCallResult(
3674    SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3675    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3676    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3677    SDValue ThisVal) const {
3678  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3679                          ? RetCC_AArch64_WebKit_JS
3680                          : RetCC_AArch64_AAPCS;
3681  // Assign locations to each value returned by this call.
3682  SmallVector<CCValAssign, 16> RVLocs;
3683  DenseMap<unsigned, SDValue> CopiedRegs;
3684  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3685                 *DAG.getContext());
3686  CCInfo.AnalyzeCallResult(Ins, RetCC);
3687
3688  // Copy all of the result registers out of their specified physreg.
3689  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3690    CCValAssign VA = RVLocs[i];
3691
3692    // Pass 'this' value directly from the argument to return value, to avoid
3693    // reg unit interference
3694    if (i == 0 && isThisReturn) {
3695      assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3696             "unexpected return calling convention register assignment");
3697      InVals.push_back(ThisVal);
3698      continue;
3699    }
3700
3701    // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3702    // allows one use of a physreg per block.
3703    SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3704    if (!Val) {
3705      Val =
3706          DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3707      Chain = Val.getValue(1);
3708      InFlag = Val.getValue(2);
3709      CopiedRegs[VA.getLocReg()] = Val;
3710    }
3711
3712    switch (VA.getLocInfo()) {
3713    default:
3714      llvm_unreachable("Unknown loc info!");
3715    case CCValAssign::Full:
3716      break;
3717    case CCValAssign::BCvt:
3718      Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3719      break;
3720    case CCValAssign::AExtUpper:
3721      Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3722                        DAG.getConstant(32, DL, VA.getLocVT()));
3723      LLVM_FALLTHROUGH;
3724    case CCValAssign::AExt:
3725      LLVM_FALLTHROUGH;
3726    case CCValAssign::ZExt:
3727      Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3728      break;
3729    }
3730
3731    InVals.push_back(Val);
3732  }
3733
3734  return Chain;
3735}
3736
3737/// Return true if the calling convention is one that we can guarantee TCO for.
3738static bool canGuaranteeTCO(CallingConv::ID CC) {
3739  return CC == CallingConv::Fast;
3740}
3741
3742/// Return true if we might ever do TCO for calls with this calling convention.
3743static bool mayTailCallThisCC(CallingConv::ID CC) {
3744  switch (CC) {
3745  case CallingConv::C:
3746  case CallingConv::PreserveMost:
3747  case CallingConv::Swift:
3748    return true;
3749  default:
3750    return canGuaranteeTCO(CC);
3751  }
3752}
3753
3754bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3755    SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3756    const SmallVectorImpl<ISD::OutputArg> &Outs,
3757    const SmallVectorImpl<SDValue> &OutVals,
3758    const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3759  if (!mayTailCallThisCC(CalleeCC))
3760    return false;
3761
3762  MachineFunction &MF = DAG.getMachineFunction();
3763  const Function &CallerF = MF.getFunction();
3764  CallingConv::ID CallerCC = CallerF.getCallingConv();
3765  bool CCMatch = CallerCC == CalleeCC;
3766
3767  // Byval parameters hand the function a pointer directly into the stack area
3768  // we want to reuse during a tail call. Working around this *is* possible (see
3769  // X86) but less efficient and uglier in LowerCall.
3770  for (Function::const_arg_iterator i = CallerF.arg_begin(),
3771                                    e = CallerF.arg_end();
3772       i != e; ++i) {
3773    if (i->hasByValAttr())
3774      return false;
3775
3776    // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3777    // In this case, it is necessary to save/restore X0 in the callee. Tail
3778    // call opt interferes with this. So we disable tail call opt when the
3779    // caller has an argument with "inreg" attribute.
3780
3781    // FIXME: Check whether the callee also has an "inreg" argument.
3782    if (i->hasInRegAttr())
3783      return false;
3784  }
3785
3786  if (getTargetMachine().Options.GuaranteedTailCallOpt)
3787    return canGuaranteeTCO(CalleeCC) && CCMatch;
3788
3789  // Externally-defined functions with weak linkage should not be
3790  // tail-called on AArch64 when the OS does not support dynamic
3791  // pre-emption of symbols, as the AAELF spec requires normal calls
3792  // to undefined weak functions to be replaced with a NOP or jump to the
3793  // next instruction. The behaviour of branch instructions in this
3794  // situation (as used for tail calls) is implementation-defined, so we
3795  // cannot rely on the linker replacing the tail call with a return.
3796  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3797    const GlobalValue *GV = G->getGlobal();
3798    const Triple &TT = getTargetMachine().getTargetTriple();
3799    if (GV->hasExternalWeakLinkage() &&
3800        (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3801      return false;
3802  }
3803
3804  // Now we search for cases where we can use a tail call without changing the
3805  // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3806  // concept.
3807
3808  // I want anyone implementing a new calling convention to think long and hard
3809  // about this assert.
3810  assert((!isVarArg || CalleeCC == CallingConv::C) &&
3811         "Unexpected variadic calling convention");
3812
3813  LLVMContext &C = *DAG.getContext();
3814  if (isVarArg && !Outs.empty()) {
3815    // At least two cases here: if caller is fastcc then we can't have any
3816    // memory arguments (we'd be expected to clean up the stack afterwards). If
3817    // caller is C then we could potentially use its argument area.
3818
3819    // FIXME: for now we take the most conservative of these in both cases:
3820    // disallow all variadic memory operands.
3821    SmallVector<CCValAssign, 16> ArgLocs;
3822    CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3823
3824    CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3825    for (const CCValAssign &ArgLoc : ArgLocs)
3826      if (!ArgLoc.isRegLoc())
3827        return false;
3828  }
3829
3830  // Check that the call results are passed in the same way.
3831  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3832                                  CCAssignFnForCall(CalleeCC, isVarArg),
3833                                  CCAssignFnForCall(CallerCC, isVarArg)))
3834    return false;
3835  // The callee has to preserve all registers the caller needs to preserve.
3836  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3837  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3838  if (!CCMatch) {
3839    const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3840    if (Subtarget->hasCustomCallingConv()) {
3841      TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3842      TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3843    }
3844    if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3845      return false;
3846  }
3847
3848  // Nothing more to check if the callee is taking no arguments
3849  if (Outs.empty())
3850    return true;
3851
3852  SmallVector<CCValAssign, 16> ArgLocs;
3853  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3854
3855  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3856
3857  const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3858
3859  // If the stack arguments for this call do not fit into our own save area then
3860  // the call cannot be made tail.
3861  if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3862    return false;
3863
3864  const MachineRegisterInfo &MRI = MF.getRegInfo();
3865  if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3866    return false;
3867
3868  return true;
3869}
3870
3871SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3872                                                   SelectionDAG &DAG,
3873                                                   MachineFrameInfo &MFI,
3874                                                   int ClobberedFI) const {
3875  SmallVector<SDValue, 8> ArgChains;
3876  int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3877  int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3878
3879  // Include the original chain at the beginning of the list. When this is
3880  // used by target LowerCall hooks, this helps legalize find the
3881  // CALLSEQ_BEGIN node.
3882  ArgChains.push_back(Chain);
3883
3884  // Add a chain value for each stack argument corresponding
3885  for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3886                            UE = DAG.getEntryNode().getNode()->use_end();
3887       U != UE; ++U)
3888    if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3889      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3890        if (FI->getIndex() < 0) {
3891          int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3892          int64_t InLastByte = InFirstByte;
3893          InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3894
3895          if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3896              (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3897            ArgChains.push_back(SDValue(L, 1));
3898        }
3899
3900  // Build a tokenfactor for all the chains.
3901  return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3902}
3903
3904bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3905                                                   bool TailCallOpt) const {
3906  return CallCC == CallingConv::Fast && TailCallOpt;
3907}
3908
3909/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3910/// and add input and output parameter nodes.
3911SDValue
3912AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3913                                 SmallVectorImpl<SDValue> &InVals) const {
3914  SelectionDAG &DAG = CLI.DAG;
3915  SDLoc &DL = CLI.DL;
3916  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3917  SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3918  SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3919  SDValue Chain = CLI.Chain;
3920  SDValue Callee = CLI.Callee;
3921  bool &IsTailCall = CLI.IsTailCall;
3922  CallingConv::ID CallConv = CLI.CallConv;
3923  bool IsVarArg = CLI.IsVarArg;
3924
3925  MachineFunction &MF = DAG.getMachineFunction();
3926  MachineFunction::CallSiteInfo CSInfo;
3927  bool IsThisReturn = false;
3928
3929  AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3930  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3931  bool IsSibCall = false;
3932
3933  if (IsTailCall) {
3934    // Check if it's really possible to do a tail call.
3935    IsTailCall = isEligibleForTailCallOptimization(
3936        Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3937    if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3938      report_fatal_error("failed to perform tail call elimination on a call "
3939                         "site marked musttail");
3940
3941    // A sibling call is one where we're under the usual C ABI and not planning
3942    // to change that but can still do a tail call:
3943    if (!TailCallOpt && IsTailCall)
3944      IsSibCall = true;
3945
3946    if (IsTailCall)
3947      ++NumTailCalls;
3948  }
3949
3950  // Analyze operands of the call, assigning locations to each operand.
3951  SmallVector<CCValAssign, 16> ArgLocs;
3952  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3953                 *DAG.getContext());
3954
3955  if (IsVarArg) {
3956    // Handle fixed and variable vector arguments differently.
3957    // Variable vector arguments always go into memory.
3958    unsigned NumArgs = Outs.size();
3959
3960    for (unsigned i = 0; i != NumArgs; ++i) {
3961      MVT ArgVT = Outs[i].VT;
3962      ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3963      CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3964                                               /*IsVarArg=*/ !Outs[i].IsFixed);
3965      bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3966      assert(!Res && "Call operand has unhandled type");
3967      (void)Res;
3968    }
3969  } else {
3970    // At this point, Outs[].VT may already be promoted to i32. To correctly
3971    // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3972    // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3973    // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3974    // we use a special version of AnalyzeCallOperands to pass in ValVT and
3975    // LocVT.
3976    unsigned NumArgs = Outs.size();
3977    for (unsigned i = 0; i != NumArgs; ++i) {
3978      MVT ValVT = Outs[i].VT;
3979      // Get type of the original argument.
3980      EVT ActualVT = getValueType(DAG.getDataLayout(),
3981                                  CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3982                                  /*AllowUnknown*/ true);
3983      MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3984      ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3985      // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3986      if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3987        ValVT = MVT::i8;
3988      else if (ActualMVT == MVT::i16)
3989        ValVT = MVT::i16;
3990
3991      CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3992      bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3993      assert(!Res && "Call operand has unhandled type");
3994      (void)Res;
3995    }
3996  }
3997
3998  // Get a count of how many bytes are to be pushed on the stack.
3999  unsigned NumBytes = CCInfo.getNextStackOffset();
4000
4001  if (IsSibCall) {
4002    // Since we're not changing the ABI to make this a tail call, the memory
4003    // operands are already available in the caller's incoming argument space.
4004    NumBytes = 0;
4005  }
4006
4007  // FPDiff is the byte offset of the call's argument area from the callee's.
4008  // Stores to callee stack arguments will be placed in FixedStackSlots offset
4009  // by this amount for a tail call. In a sibling call it must be 0 because the
4010  // caller will deallocate the entire stack and the callee still expects its
4011  // arguments to begin at SP+0. Completely unused for non-tail calls.
4012  int FPDiff = 0;
4013
4014  if (IsTailCall && !IsSibCall) {
4015    unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4016
4017    // Since callee will pop argument stack as a tail call, we must keep the
4018    // popped size 16-byte aligned.
4019    NumBytes = alignTo(NumBytes, 16);
4020
4021    // FPDiff will be negative if this tail call requires more space than we
4022    // would automatically have in our incoming argument space. Positive if we
4023    // can actually shrink the stack.
4024    FPDiff = NumReusableBytes - NumBytes;
4025
4026    // The stack pointer must be 16-byte aligned at all times it's used for a
4027    // memory operation, which in practice means at *all* times and in
4028    // particular across call boundaries. Therefore our own arguments started at
4029    // a 16-byte aligned SP and the delta applied for the tail call should
4030    // satisfy the same constraint.
4031    assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4032  }
4033
4034  // Adjust the stack pointer for the new arguments...
4035  // These operations are automatically eliminated by the prolog/epilog pass
4036  if (!IsSibCall)
4037    Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4038
4039  SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4040                                        getPointerTy(DAG.getDataLayout()));
4041
4042  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4043  SmallSet<unsigned, 8> RegsUsed;
4044  SmallVector<SDValue, 8> MemOpChains;
4045  auto PtrVT = getPointerTy(DAG.getDataLayout());
4046
4047  if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
4048    const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4049    for (const auto &F : Forwards) {
4050      SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4051       RegsToPass.emplace_back(F.PReg, Val);
4052    }
4053  }
4054
4055  // Walk the register/memloc assignments, inserting copies/loads.
4056  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4057    CCValAssign &VA = ArgLocs[i];
4058    SDValue Arg = OutVals[i];
4059    ISD::ArgFlagsTy Flags = Outs[i].Flags;
4060
4061    // Promote the value if needed.
4062    switch (VA.getLocInfo()) {
4063    default:
4064      llvm_unreachable("Unknown loc info!");
4065    case CCValAssign::Full:
4066      break;
4067    case CCValAssign::SExt:
4068      Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4069      break;
4070    case CCValAssign::ZExt:
4071      Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4072      break;
4073    case CCValAssign::AExt:
4074      if (Outs[i].ArgVT == MVT::i1) {
4075        // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4076        Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4077        Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4078      }
4079      Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4080      break;
4081    case CCValAssign::AExtUpper:
4082      assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4083      Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4084      Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4085                        DAG.getConstant(32, DL, VA.getLocVT()));
4086      break;
4087    case CCValAssign::BCvt:
4088      Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4089      break;
4090    case CCValAssign::Trunc:
4091      Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4092      break;
4093    case CCValAssign::FPExt:
4094      Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4095      break;
4096    case CCValAssign::Indirect:
4097      assert(VA.getValVT().isScalableVector() &&
4098             "Only scalable vectors can be passed indirectly");
4099      llvm_unreachable("Spilling of SVE vectors not yet implemented");
4100    }
4101
4102    if (VA.isRegLoc()) {
4103      if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4104          Outs[0].VT == MVT::i64) {
4105        assert(VA.getLocVT() == MVT::i64 &&
4106               "unexpected calling convention register assignment");
4107        assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4108               "unexpected use of 'returned'");
4109        IsThisReturn = true;
4110      }
4111      if (RegsUsed.count(VA.getLocReg())) {
4112        // If this register has already been used then we're trying to pack
4113        // parts of an [N x i32] into an X-register. The extension type will
4114        // take care of putting the two halves in the right place but we have to
4115        // combine them.
4116        SDValue &Bits =
4117            std::find_if(RegsToPass.begin(), RegsToPass.end(),
4118                         [=](const std::pair<unsigned, SDValue> &Elt) {
4119                           return Elt.first == VA.getLocReg();
4120                         })
4121                ->second;
4122        Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4123        // Call site info is used for function's parameter entry value
4124        // tracking. For now we track only simple cases when parameter
4125        // is transferred through whole register.
4126        CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4127                                    [&VA](MachineFunction::ArgRegPair ArgReg) {
4128                                      return ArgReg.Reg == VA.getLocReg();
4129                                    }),
4130                     CSInfo.end());
4131      } else {
4132        RegsToPass.emplace_back(VA.getLocReg(), Arg);
4133        RegsUsed.insert(VA.getLocReg());
4134        const TargetOptions &Options = DAG.getTarget().Options;
4135        if (Options.EnableDebugEntryValues)
4136          CSInfo.emplace_back(VA.getLocReg(), i);
4137      }
4138    } else {
4139      assert(VA.isMemLoc());
4140
4141      SDValue DstAddr;
4142      MachinePointerInfo DstInfo;
4143
4144      // FIXME: This works on big-endian for composite byvals, which are the
4145      // common case. It should also work for fundamental types too.
4146      uint32_t BEAlign = 0;
4147      unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4148                                        : VA.getValVT().getSizeInBits();
4149      OpSize = (OpSize + 7) / 8;
4150      if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4151          !Flags.isInConsecutiveRegs()) {
4152        if (OpSize < 8)
4153          BEAlign = 8 - OpSize;
4154      }
4155      unsigned LocMemOffset = VA.getLocMemOffset();
4156      int32_t Offset = LocMemOffset + BEAlign;
4157      SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4158      PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4159
4160      if (IsTailCall) {
4161        Offset = Offset + FPDiff;
4162        int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4163
4164        DstAddr = DAG.getFrameIndex(FI, PtrVT);
4165        DstInfo =
4166            MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4167
4168        // Make sure any stack arguments overlapping with where we're storing
4169        // are loaded before this eventual operation. Otherwise they'll be
4170        // clobbered.
4171        Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4172      } else {
4173        SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4174
4175        DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4176        DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4177                                               LocMemOffset);
4178      }
4179
4180      if (Outs[i].Flags.isByVal()) {
4181        SDValue SizeNode =
4182            DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4183        SDValue Cpy = DAG.getMemcpy(
4184            Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
4185            /*isVol = */ false, /*AlwaysInline = */ false,
4186            /*isTailCall = */ false,
4187            DstInfo, MachinePointerInfo());
4188
4189        MemOpChains.push_back(Cpy);
4190      } else {
4191        // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4192        // promoted to a legal register type i32, we should truncate Arg back to
4193        // i1/i8/i16.
4194        if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4195            VA.getValVT() == MVT::i16)
4196          Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4197
4198        SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4199        MemOpChains.push_back(Store);
4200      }
4201    }
4202  }
4203
4204  if (!MemOpChains.empty())
4205    Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4206
4207  // Build a sequence of copy-to-reg nodes chained together with token chain
4208  // and flag operands which copy the outgoing args into the appropriate regs.
4209  SDValue InFlag;
4210  for (auto &RegToPass : RegsToPass) {
4211    Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4212                             RegToPass.second, InFlag);
4213    InFlag = Chain.getValue(1);
4214  }
4215
4216  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4217  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4218  // node so that legalize doesn't hack it.
4219  if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4220    auto GV = G->getGlobal();
4221    unsigned OpFlags =
4222        Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4223    if (OpFlags & AArch64II::MO_GOT) {
4224      Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4225      Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4226    } else {
4227      const GlobalValue *GV = G->getGlobal();
4228      Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4229    }
4230  } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4231    if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4232        Subtarget->isTargetMachO()) {
4233      const char *Sym = S->getSymbol();
4234      Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4235      Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4236    } else {
4237      const char *Sym = S->getSymbol();
4238      Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4239    }
4240  }
4241
4242  // We don't usually want to end the call-sequence here because we would tidy
4243  // the frame up *after* the call, however in the ABI-changing tail-call case
4244  // we've carefully laid out the parameters so that when sp is reset they'll be
4245  // in the correct location.
4246  if (IsTailCall && !IsSibCall) {
4247    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4248                               DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4249    InFlag = Chain.getValue(1);
4250  }
4251
4252  std::vector<SDValue> Ops;
4253  Ops.push_back(Chain);
4254  Ops.push_back(Callee);
4255
4256  if (IsTailCall) {
4257    // Each tail call may have to adjust the stack by a different amount, so
4258    // this information must travel along with the operation for eventual
4259    // consumption by emitEpilogue.
4260    Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4261  }
4262
4263  // Add argument registers to the end of the list so that they are known live
4264  // into the call.
4265  for (auto &RegToPass : RegsToPass)
4266    Ops.push_back(DAG.getRegister(RegToPass.first,
4267                                  RegToPass.second.getValueType()));
4268
4269  // Check callee args/returns for SVE registers and set calling convention
4270  // accordingly.
4271  if (CallConv == CallingConv::C) {
4272    bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4273      return Out.VT.isScalableVector();
4274    });
4275    bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4276      return In.VT.isScalableVector();
4277    });
4278
4279    if (CalleeInSVE || CalleeOutSVE)
4280      CallConv = CallingConv::AArch64_SVE_VectorCall;
4281  }
4282
4283  // Add a register mask operand representing the call-preserved registers.
4284  const uint32_t *Mask;
4285  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4286  if (IsThisReturn) {
4287    // For 'this' returns, use the X0-preserving mask if applicable
4288    Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4289    if (!Mask) {
4290      IsThisReturn = false;
4291      Mask = TRI->getCallPreservedMask(MF, CallConv);
4292    }
4293  } else
4294    Mask = TRI->getCallPreservedMask(MF, CallConv);
4295
4296  if (Subtarget->hasCustomCallingConv())
4297    TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4298
4299  if (TRI->isAnyArgRegReserved(MF))
4300    TRI->emitReservedArgRegCallError(MF);
4301
4302  assert(Mask && "Missing call preserved mask for calling convention");
4303  Ops.push_back(DAG.getRegisterMask(Mask));
4304
4305  if (InFlag.getNode())
4306    Ops.push_back(InFlag);
4307
4308  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4309
4310  // If we're doing a tall call, use a TC_RETURN here rather than an
4311  // actual call instruction.
4312  if (IsTailCall) {
4313    MF.getFrameInfo().setHasTailCall();
4314    SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4315    DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4316    return Ret;
4317  }
4318
4319  // Returns a chain and a flag for retval copy to use.
4320  Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4321  InFlag = Chain.getValue(1);
4322  DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4323
4324  uint64_t CalleePopBytes =
4325      DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4326
4327  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4328                             DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4329                             InFlag, DL);
4330  if (!Ins.empty())
4331    InFlag = Chain.getValue(1);
4332
4333  // Handle result values, copying them out of physregs into vregs that we
4334  // return.
4335  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4336                         InVals, IsThisReturn,
4337                         IsThisReturn ? OutVals[0] : SDValue());
4338}
4339
4340bool AArch64TargetLowering::CanLowerReturn(
4341    CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4342    const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4343  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4344                          ? RetCC_AArch64_WebKit_JS
4345                          : RetCC_AArch64_AAPCS;
4346  SmallVector<CCValAssign, 16> RVLocs;
4347  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4348  return CCInfo.CheckReturn(Outs, RetCC);
4349}
4350
4351SDValue
4352AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4353                                   bool isVarArg,
4354                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
4355                                   const SmallVectorImpl<SDValue> &OutVals,
4356                                   const SDLoc &DL, SelectionDAG &DAG) const {
4357  auto &MF = DAG.getMachineFunction();
4358  auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4359
4360  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4361                          ? RetCC_AArch64_WebKit_JS
4362                          : RetCC_AArch64_AAPCS;
4363  SmallVector<CCValAssign, 16> RVLocs;
4364  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4365                 *DAG.getContext());
4366  CCInfo.AnalyzeReturn(Outs, RetCC);
4367
4368  // Copy the result values into the output registers.
4369  SDValue Flag;
4370  SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4371  SmallSet<unsigned, 4> RegsUsed;
4372  for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4373       ++i, ++realRVLocIdx) {
4374    CCValAssign &VA = RVLocs[i];
4375    assert(VA.isRegLoc() && "Can only return in registers!");
4376    SDValue Arg = OutVals[realRVLocIdx];
4377
4378    switch (VA.getLocInfo()) {
4379    default:
4380      llvm_unreachable("Unknown loc info!");
4381    case CCValAssign::Full:
4382      if (Outs[i].ArgVT == MVT::i1) {
4383        // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4384        // value. This is strictly redundant on Darwin (which uses "zeroext
4385        // i1"), but will be optimised out before ISel.
4386        Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4387        Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4388      }
4389      break;
4390    case CCValAssign::BCvt:
4391      Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4392      break;
4393    case CCValAssign::AExt:
4394    case CCValAssign::ZExt:
4395      Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4396      break;
4397    case CCValAssign::AExtUpper:
4398      assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4399      Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4400      Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4401                        DAG.getConstant(32, DL, VA.getLocVT()));
4402      break;
4403    }
4404
4405    if (RegsUsed.count(VA.getLocReg())) {
4406      SDValue &Bits =
4407          std::find_if(RetVals.begin(), RetVals.end(),
4408                       [=](const std::pair<unsigned, SDValue> &Elt) {
4409                         return Elt.first == VA.getLocReg();
4410                       })
4411              ->second;
4412      Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4413    } else {
4414      RetVals.emplace_back(VA.getLocReg(), Arg);
4415      RegsUsed.insert(VA.getLocReg());
4416    }
4417  }
4418
4419  SmallVector<SDValue, 4> RetOps(1, Chain);
4420  for (auto &RetVal : RetVals) {
4421    Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4422    Flag = Chain.getValue(1);
4423    RetOps.push_back(
4424        DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4425  }
4426
4427  // Windows AArch64 ABIs require that for returning structs by value we copy
4428  // the sret argument into X0 for the return.
4429  // We saved the argument into a virtual register in the entry block,
4430  // so now we copy the value out and into X0.
4431  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4432    SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4433                                     getPointerTy(MF.getDataLayout()));
4434
4435    unsigned RetValReg = AArch64::X0;
4436    Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4437    Flag = Chain.getValue(1);
4438
4439    RetOps.push_back(
4440      DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4441  }
4442
4443  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4444  const MCPhysReg *I =
4445      TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4446  if (I) {
4447    for (; *I; ++I) {
4448      if (AArch64::GPR64RegClass.contains(*I))
4449        RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4450      else if (AArch64::FPR64RegClass.contains(*I))
4451        RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4452      else
4453        llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4454    }
4455  }
4456
4457  RetOps[0] = Chain; // Update chain.
4458
4459  // Add the flag if we have it.
4460  if (Flag.getNode())
4461    RetOps.push_back(Flag);
4462
4463  return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4464}
4465
4466//===----------------------------------------------------------------------===//
4467//  Other Lowering Code
4468//===----------------------------------------------------------------------===//
4469
4470SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4471                                             SelectionDAG &DAG,
4472                                             unsigned Flag) const {
4473  return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4474                                    N->getOffset(), Flag);
4475}
4476
4477SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4478                                             SelectionDAG &DAG,
4479                                             unsigned Flag) const {
4480  return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4481}
4482
4483SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4484                                             SelectionDAG &DAG,
4485                                             unsigned Flag) const {
4486  return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4487                                   N->getOffset(), Flag);
4488}
4489
4490SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4491                                             SelectionDAG &DAG,
4492                                             unsigned Flag) const {
4493  return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4494}
4495
4496// (loadGOT sym)
4497template <class NodeTy>
4498SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4499                                      unsigned Flags) const {
4500  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4501  SDLoc DL(N);
4502  EVT Ty = getPointerTy(DAG.getDataLayout());
4503  SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4504  // FIXME: Once remat is capable of dealing with instructions with register
4505  // operands, expand this into two nodes instead of using a wrapper node.
4506  return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4507}
4508
4509// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4510template <class NodeTy>
4511SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4512                                            unsigned Flags) const {
4513  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4514  SDLoc DL(N);
4515  EVT Ty = getPointerTy(DAG.getDataLayout());
4516  const unsigned char MO_NC = AArch64II::MO_NC;
4517  return DAG.getNode(
4518      AArch64ISD::WrapperLarge, DL, Ty,
4519      getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4520      getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4521      getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4522      getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4523}
4524
4525// (addlow (adrp %hi(sym)) %lo(sym))
4526template <class NodeTy>
4527SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4528                                       unsigned Flags) const {
4529  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4530  SDLoc DL(N);
4531  EVT Ty = getPointerTy(DAG.getDataLayout());
4532  SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4533  SDValue Lo = getTargetNode(N, Ty, DAG,
4534                             AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4535  SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4536  return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4537}
4538
4539// (adr sym)
4540template <class NodeTy>
4541SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4542                                           unsigned Flags) const {
4543  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4544  SDLoc DL(N);
4545  EVT Ty = getPointerTy(DAG.getDataLayout());
4546  SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4547  return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4548}
4549
4550SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4551                                                  SelectionDAG &DAG) const {
4552  GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4553  const GlobalValue *GV = GN->getGlobal();
4554  unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4555
4556  if (OpFlags != AArch64II::MO_NO_FLAG)
4557    assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4558           "unexpected offset in global node");
4559
4560  // This also catches the large code model case for Darwin, and tiny code
4561  // model with got relocations.
4562  if ((OpFlags & AArch64II::MO_GOT) != 0) {
4563    return getGOT(GN, DAG, OpFlags);
4564  }
4565
4566  SDValue Result;
4567  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4568    Result = getAddrLarge(GN, DAG, OpFlags);
4569  } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4570    Result = getAddrTiny(GN, DAG, OpFlags);
4571  } else {
4572    Result = getAddr(GN, DAG, OpFlags);
4573  }
4574  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4575  SDLoc DL(GN);
4576  if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4577    Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4578                         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4579  return Result;
4580}
4581
4582/// Convert a TLS address reference into the correct sequence of loads
4583/// and calls to compute the variable's address (for Darwin, currently) and
4584/// return an SDValue containing the final node.
4585
4586/// Darwin only has one TLS scheme which must be capable of dealing with the
4587/// fully general situation, in the worst case. This means:
4588///     + "extern __thread" declaration.
4589///     + Defined in a possibly unknown dynamic library.
4590///
4591/// The general system is that each __thread variable has a [3 x i64] descriptor
4592/// which contains information used by the runtime to calculate the address. The
4593/// only part of this the compiler needs to know about is the first xword, which
4594/// contains a function pointer that must be called with the address of the
4595/// entire descriptor in "x0".
4596///
4597/// Since this descriptor may be in a different unit, in general even the
4598/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4599/// is:
4600///     adrp x0, _var@TLVPPAGE
4601///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4602///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4603///                                      ; the function pointer
4604///     blr x1                           ; Uses descriptor address in x0
4605///     ; Address of _var is now in x0.
4606///
4607/// If the address of _var's descriptor *is* known to the linker, then it can
4608/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4609/// a slight efficiency gain.
4610SDValue
4611AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4612                                                   SelectionDAG &DAG) const {
4613  assert(Subtarget->isTargetDarwin() &&
4614         "This function expects a Darwin target");
4615
4616  SDLoc DL(Op);
4617  MVT PtrVT = getPointerTy(DAG.getDataLayout());
4618  MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4619  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4620
4621  SDValue TLVPAddr =
4622      DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4623  SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4624
4625  // The first entry in the descriptor is a function pointer that we must call
4626  // to obtain the address of the variable.
4627  SDValue Chain = DAG.getEntryNode();
4628  SDValue FuncTLVGet = DAG.getLoad(
4629      PtrMemVT, DL, Chain, DescAddr,
4630      MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4631      /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4632      MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4633  Chain = FuncTLVGet.getValue(1);
4634
4635  // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4636  FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4637
4638  MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4639  MFI.setAdjustsStack(true);
4640
4641  // TLS calls preserve all registers except those that absolutely must be
4642  // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4643  // silly).
4644  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4645  const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4646  if (Subtarget->hasCustomCallingConv())
4647    TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4648
4649  // Finally, we can make the call. This is just a degenerate version of a
4650  // normal AArch64 call node: x0 takes the address of the descriptor, and
4651  // returns the address of the variable in this thread.
4652  Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4653  Chain =
4654      DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4655                  Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4656                  DAG.getRegisterMask(Mask), Chain.getValue(1));
4657  return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4658}
4659
4660/// Convert a thread-local variable reference into a sequence of instructions to
4661/// compute the variable's address for the local exec TLS model of ELF targets.
4662/// The sequence depends on the maximum TLS area size.
4663SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
4664                                                    SDValue ThreadBase,
4665                                                    const SDLoc &DL,
4666                                                    SelectionDAG &DAG) const {
4667  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4668  SDValue TPOff, Addr;
4669
4670  switch (DAG.getTarget().Options.TLSSize) {
4671  default:
4672    llvm_unreachable("Unexpected TLS size");
4673
4674  case 12: {
4675    // mrs   x0, TPIDR_EL0
4676    // add   x0, x0, :tprel_lo12:a
4677    SDValue Var = DAG.getTargetGlobalAddress(
4678        GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
4679    return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4680                                      Var,
4681                                      DAG.getTargetConstant(0, DL, MVT::i32)),
4682                   0);
4683  }
4684
4685  case 24: {
4686    // mrs   x0, TPIDR_EL0
4687    // add   x0, x0, :tprel_hi12:a
4688    // add   x0, x0, :tprel_lo12_nc:a
4689    SDValue HiVar = DAG.getTargetGlobalAddress(
4690        GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4691    SDValue LoVar = DAG.getTargetGlobalAddress(
4692        GV, DL, PtrVT, 0,
4693        AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4694    Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4695                                      HiVar,
4696                                      DAG.getTargetConstant(0, DL, MVT::i32)),
4697                   0);
4698    return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
4699                                      LoVar,
4700                                      DAG.getTargetConstant(0, DL, MVT::i32)),
4701                   0);
4702  }
4703
4704  case 32: {
4705    // mrs   x1, TPIDR_EL0
4706    // movz  x0, #:tprel_g1:a
4707    // movk  x0, #:tprel_g0_nc:a
4708    // add   x0, x1, x0
4709    SDValue HiVar = DAG.getTargetGlobalAddress(
4710        GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
4711    SDValue LoVar = DAG.getTargetGlobalAddress(
4712        GV, DL, PtrVT, 0,
4713        AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4714    TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4715                                       DAG.getTargetConstant(16, DL, MVT::i32)),
4716                    0);
4717    TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4718                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4719                    0);
4720    return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4721  }
4722
4723  case 48: {
4724    // mrs   x1, TPIDR_EL0
4725    // movz  x0, #:tprel_g2:a
4726    // movk  x0, #:tprel_g1_nc:a
4727    // movk  x0, #:tprel_g0_nc:a
4728    // add   x0, x1, x0
4729    SDValue HiVar = DAG.getTargetGlobalAddress(
4730        GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
4731    SDValue MiVar = DAG.getTargetGlobalAddress(
4732        GV, DL, PtrVT, 0,
4733        AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
4734    SDValue LoVar = DAG.getTargetGlobalAddress(
4735        GV, DL, PtrVT, 0,
4736        AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4737    TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4738                                       DAG.getTargetConstant(32, DL, MVT::i32)),
4739                    0);
4740    TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
4741                                       DAG.getTargetConstant(16, DL, MVT::i32)),
4742                    0);
4743    TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4744                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4745                    0);
4746    return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4747  }
4748  }
4749}
4750
4751/// When accessing thread-local variables under either the general-dynamic or
4752/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4753/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4754/// is a function pointer to carry out the resolution.
4755///
4756/// The sequence is:
4757///    adrp  x0, :tlsdesc:var
4758///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4759///    add   x0, x0, #:tlsdesc_lo12:var
4760///    .tlsdesccall var
4761///    blr   x1
4762///    (TPIDR_EL0 offset now in x0)
4763///
4764///  The above sequence must be produced unscheduled, to enable the linker to
4765///  optimize/relax this sequence.
4766///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4767///  above sequence, and expanded really late in the compilation flow, to ensure
4768///  the sequence is produced as per above.
4769SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4770                                                      const SDLoc &DL,
4771                                                      SelectionDAG &DAG) const {
4772  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4773
4774  SDValue Chain = DAG.getEntryNode();
4775  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4776
4777  Chain =
4778      DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4779  SDValue Glue = Chain.getValue(1);
4780
4781  return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4782}
4783
4784SDValue
4785AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4786                                                SelectionDAG &DAG) const {
4787  assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4788
4789  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4790
4791  TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4792
4793  if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4794    if (Model == TLSModel::LocalDynamic)
4795      Model = TLSModel::GeneralDynamic;
4796  }
4797
4798  if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4799      Model != TLSModel::LocalExec)
4800    report_fatal_error("ELF TLS only supported in small memory model or "
4801                       "in local exec TLS model");
4802  // Different choices can be made for the maximum size of the TLS area for a
4803  // module. For the small address model, the default TLS size is 16MiB and the
4804  // maximum TLS size is 4GiB.
4805  // FIXME: add tiny and large code model support for TLS access models other
4806  // than local exec. We currently generate the same code as small for tiny,
4807  // which may be larger than needed.
4808
4809  SDValue TPOff;
4810  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4811  SDLoc DL(Op);
4812  const GlobalValue *GV = GA->getGlobal();
4813
4814  SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4815
4816  if (Model == TLSModel::LocalExec) {
4817    return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
4818  } else if (Model == TLSModel::InitialExec) {
4819    TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4820    TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4821  } else if (Model == TLSModel::LocalDynamic) {
4822    // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4823    // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4824    // the beginning of the module's TLS region, followed by a DTPREL offset
4825    // calculation.
4826
4827    // These accesses will need deduplicating if there's more than one.
4828    AArch64FunctionInfo *MFI =
4829        DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4830    MFI->incNumLocalDynamicTLSAccesses();
4831
4832    // The call needs a relocation too for linker relaxation. It doesn't make
4833    // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4834    // the address.
4835    SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4836                                                  AArch64II::MO_TLS);
4837
4838    // Now we can calculate the offset from TPIDR_EL0 to this module's
4839    // thread-local area.
4840    TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4841
4842    // Now use :dtprel_whatever: operations to calculate this variable's offset
4843    // in its thread-storage area.
4844    SDValue HiVar = DAG.getTargetGlobalAddress(
4845        GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4846    SDValue LoVar = DAG.getTargetGlobalAddress(
4847        GV, DL, MVT::i64, 0,
4848        AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4849
4850    TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4851                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4852                    0);
4853    TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4854                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4855                    0);
4856  } else if (Model == TLSModel::GeneralDynamic) {
4857    // The call needs a relocation too for linker relaxation. It doesn't make
4858    // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4859    // the address.
4860    SDValue SymAddr =
4861        DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4862
4863    // Finally we can make a call to calculate the offset from tpidr_el0.
4864    TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4865  } else
4866    llvm_unreachable("Unsupported ELF TLS access model");
4867
4868  return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4869}
4870
4871SDValue
4872AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4873                                                    SelectionDAG &DAG) const {
4874  assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4875
4876  SDValue Chain = DAG.getEntryNode();
4877  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4878  SDLoc DL(Op);
4879
4880  SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4881
4882  // Load the ThreadLocalStoragePointer from the TEB
4883  // A pointer to the TLS array is located at offset 0x58 from the TEB.
4884  SDValue TLSArray =
4885      DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4886  TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4887  Chain = TLSArray.getValue(1);
4888
4889  // Load the TLS index from the C runtime;
4890  // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4891  // This also does the same as LOADgot, but using a generic i32 load,
4892  // while LOADgot only loads i64.
4893  SDValue TLSIndexHi =
4894      DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4895  SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4896      "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4897  SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4898  SDValue TLSIndex =
4899      DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4900  TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4901  Chain = TLSIndex.getValue(1);
4902
4903  // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4904  // offset into the TLSArray.
4905  TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4906  SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4907                             DAG.getConstant(3, DL, PtrVT));
4908  SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4909                            DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4910                            MachinePointerInfo());
4911  Chain = TLS.getValue(1);
4912
4913  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4914  const GlobalValue *GV = GA->getGlobal();
4915  SDValue TGAHi = DAG.getTargetGlobalAddress(
4916      GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4917  SDValue TGALo = DAG.getTargetGlobalAddress(
4918      GV, DL, PtrVT, 0,
4919      AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4920
4921  // Add the offset from the start of the .tls section (section base).
4922  SDValue Addr =
4923      SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4924                                 DAG.getTargetConstant(0, DL, MVT::i32)),
4925              0);
4926  Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4927  return Addr;
4928}
4929
4930SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4931                                                     SelectionDAG &DAG) const {
4932  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4933  if (DAG.getTarget().useEmulatedTLS())
4934    return LowerToTLSEmulatedModel(GA, DAG);
4935
4936  if (Subtarget->isTargetDarwin())
4937    return LowerDarwinGlobalTLSAddress(Op, DAG);
4938  if (Subtarget->isTargetELF())
4939    return LowerELFGlobalTLSAddress(Op, DAG);
4940  if (Subtarget->isTargetWindows())
4941    return LowerWindowsGlobalTLSAddress(Op, DAG);
4942
4943  llvm_unreachable("Unexpected platform trying to use TLS");
4944}
4945
4946SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4947  SDValue Chain = Op.getOperand(0);
4948  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4949  SDValue LHS = Op.getOperand(2);
4950  SDValue RHS = Op.getOperand(3);
4951  SDValue Dest = Op.getOperand(4);
4952  SDLoc dl(Op);
4953
4954  MachineFunction &MF = DAG.getMachineFunction();
4955  // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4956  // will not be produced, as they are conditional branch instructions that do
4957  // not set flags.
4958  bool ProduceNonFlagSettingCondBr =
4959      !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4960
4961  // Handle f128 first, since lowering it will result in comparing the return
4962  // value of a libcall against zero, which is just what the rest of LowerBR_CC
4963  // is expecting to deal with.
4964  if (LHS.getValueType() == MVT::f128) {
4965    softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4966
4967    // If softenSetCCOperands returned a scalar, we need to compare the result
4968    // against zero to select between true and false values.
4969    if (!RHS.getNode()) {
4970      RHS = DAG.getConstant(0, dl, LHS.getValueType());
4971      CC = ISD::SETNE;
4972    }
4973  }
4974
4975  // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4976  // instruction.
4977  if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4978      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4979    // Only lower legal XALUO ops.
4980    if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4981      return SDValue();
4982
4983    // The actual operation with overflow check.
4984    AArch64CC::CondCode OFCC;
4985    SDValue Value, Overflow;
4986    std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4987
4988    if (CC == ISD::SETNE)
4989      OFCC = getInvertedCondCode(OFCC);
4990    SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4991
4992    return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4993                       Overflow);
4994  }
4995
4996  if (LHS.getValueType().isInteger()) {
4997    assert((LHS.getValueType() == RHS.getValueType()) &&
4998           (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4999
5000    // If the RHS of the comparison is zero, we can potentially fold this
5001    // to a specialized branch.
5002    const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5003    if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5004      if (CC == ISD::SETEQ) {
5005        // See if we can use a TBZ to fold in an AND as well.
5006        // TBZ has a smaller branch displacement than CBZ.  If the offset is
5007        // out of bounds, a late MI-layer pass rewrites branches.
5008        // 403.gcc is an example that hits this case.
5009        if (LHS.getOpcode() == ISD::AND &&
5010            isa<ConstantSDNode>(LHS.getOperand(1)) &&
5011            isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5012          SDValue Test = LHS.getOperand(0);
5013          uint64_t Mask = LHS.getConstantOperandVal(1);
5014          return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5015                             DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5016                             Dest);
5017        }
5018
5019        return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5020      } else if (CC == ISD::SETNE) {
5021        // See if we can use a TBZ to fold in an AND as well.
5022        // TBZ has a smaller branch displacement than CBZ.  If the offset is
5023        // out of bounds, a late MI-layer pass rewrites branches.
5024        // 403.gcc is an example that hits this case.
5025        if (LHS.getOpcode() == ISD::AND &&
5026            isa<ConstantSDNode>(LHS.getOperand(1)) &&
5027            isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5028          SDValue Test = LHS.getOperand(0);
5029          uint64_t Mask = LHS.getConstantOperandVal(1);
5030          return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5031                             DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5032                             Dest);
5033        }
5034
5035        return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5036      } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5037        // Don't combine AND since emitComparison converts the AND to an ANDS
5038        // (a.k.a. TST) and the test in the test bit and branch instruction
5039        // becomes redundant.  This would also increase register pressure.
5040        uint64_t Mask = LHS.getValueSizeInBits() - 1;
5041        return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5042                           DAG.getConstant(Mask, dl, MVT::i64), Dest);
5043      }
5044    }
5045    if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5046        LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5047      // Don't combine AND since emitComparison converts the AND to an ANDS
5048      // (a.k.a. TST) and the test in the test bit and branch instruction
5049      // becomes redundant.  This would also increase register pressure.
5050      uint64_t Mask = LHS.getValueSizeInBits() - 1;
5051      return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5052                         DAG.getConstant(Mask, dl, MVT::i64), Dest);
5053    }
5054
5055    SDValue CCVal;
5056    SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5057    return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5058                       Cmp);
5059  }
5060
5061  assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5062         LHS.getValueType() == MVT::f64);
5063
5064  // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5065  // clean.  Some of them require two branches to implement.
5066  SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5067  AArch64CC::CondCode CC1, CC2;
5068  changeFPCCToAArch64CC(CC, CC1, CC2);
5069  SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5070  SDValue BR1 =
5071      DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5072  if (CC2 != AArch64CC::AL) {
5073    SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5074    return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5075                       Cmp);
5076  }
5077
5078  return BR1;
5079}
5080
5081SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5082                                              SelectionDAG &DAG) const {
5083  EVT VT = Op.getValueType();
5084  SDLoc DL(Op);
5085
5086  SDValue In1 = Op.getOperand(0);
5087  SDValue In2 = Op.getOperand(1);
5088  EVT SrcVT = In2.getValueType();
5089
5090  if (SrcVT.bitsLT(VT))
5091    In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5092  else if (SrcVT.bitsGT(VT))
5093    In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5094
5095  EVT VecVT;
5096  uint64_t EltMask;
5097  SDValue VecVal1, VecVal2;
5098
5099  auto setVecVal = [&] (int Idx) {
5100    if (!VT.isVector()) {
5101      VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5102                                          DAG.getUNDEF(VecVT), In1);
5103      VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5104                                          DAG.getUNDEF(VecVT), In2);
5105    } else {
5106      VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5107      VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5108    }
5109  };
5110
5111  if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5112    VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5113    EltMask = 0x80000000ULL;
5114    setVecVal(AArch64::ssub);
5115  } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5116    VecVT = MVT::v2i64;
5117
5118    // We want to materialize a mask with the high bit set, but the AdvSIMD
5119    // immediate moves cannot materialize that in a single instruction for
5120    // 64-bit elements. Instead, materialize zero and then negate it.
5121    EltMask = 0;
5122
5123    setVecVal(AArch64::dsub);
5124  } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5125    VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5126    EltMask = 0x8000ULL;
5127    setVecVal(AArch64::hsub);
5128  } else {
5129    llvm_unreachable("Invalid type for copysign!");
5130  }
5131
5132  SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5133
5134  // If we couldn't materialize the mask above, then the mask vector will be
5135  // the zero vector, and we need to negate it here.
5136  if (VT == MVT::f64 || VT == MVT::v2f64) {
5137    BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5138    BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5139    BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5140  }
5141
5142  SDValue Sel =
5143      DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5144
5145  if (VT == MVT::f16)
5146    return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5147  if (VT == MVT::f32)
5148    return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5149  else if (VT == MVT::f64)
5150    return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5151  else
5152    return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5153}
5154
5155SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5156  if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5157          Attribute::NoImplicitFloat))
5158    return SDValue();
5159
5160  if (!Subtarget->hasNEON())
5161    return SDValue();
5162
5163  // While there is no integer popcount instruction, it can
5164  // be more efficiently lowered to the following sequence that uses
5165  // AdvSIMD registers/instructions as long as the copies to/from
5166  // the AdvSIMD registers are cheap.
5167  //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5168  //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5169  //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5170  //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5171  SDValue Val = Op.getOperand(0);
5172  SDLoc DL(Op);
5173  EVT VT = Op.getValueType();
5174
5175  if (VT == MVT::i32 || VT == MVT::i64) {
5176    if (VT == MVT::i32)
5177      Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5178    Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5179
5180    SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5181    SDValue UaddLV = DAG.getNode(
5182        ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5183        DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5184
5185    if (VT == MVT::i64)
5186      UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5187    return UaddLV;
5188  }
5189
5190  assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5191          VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5192         "Unexpected type for custom ctpop lowering");
5193
5194  EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5195  Val = DAG.getBitcast(VT8Bit, Val);
5196  Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5197
5198  // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5199  unsigned EltSize = 8;
5200  unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5201  while (EltSize != VT.getScalarSizeInBits()) {
5202    EltSize *= 2;
5203    NumElts /= 2;
5204    MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5205    Val = DAG.getNode(
5206        ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5207        DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5208  }
5209
5210  return Val;
5211}
5212
5213SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5214
5215  if (Op.getValueType().isVector())
5216    return LowerVSETCC(Op, DAG);
5217
5218  bool IsStrict = Op->isStrictFPOpcode();
5219  bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5220  unsigned OpNo = IsStrict ? 1 : 0;
5221  SDValue Chain;
5222  if (IsStrict)
5223    Chain = Op.getOperand(0);
5224  SDValue LHS = Op.getOperand(OpNo + 0);
5225  SDValue RHS = Op.getOperand(OpNo + 1);
5226  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5227  SDLoc dl(Op);
5228
5229  // We chose ZeroOrOneBooleanContents, so use zero and one.
5230  EVT VT = Op.getValueType();
5231  SDValue TVal = DAG.getConstant(1, dl, VT);
5232  SDValue FVal = DAG.getConstant(0, dl, VT);
5233
5234  // Handle f128 first, since one possible outcome is a normal integer
5235  // comparison which gets picked up by the next if statement.
5236  if (LHS.getValueType() == MVT::f128) {
5237    softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5238                        IsSignaling);
5239
5240    // If softenSetCCOperands returned a scalar, use it.
5241    if (!RHS.getNode()) {
5242      assert(LHS.getValueType() == Op.getValueType() &&
5243             "Unexpected setcc expansion!");
5244      return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5245    }
5246  }
5247
5248  if (LHS.getValueType().isInteger()) {
5249    SDValue CCVal;
5250    SDValue Cmp = getAArch64Cmp(
5251        LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5252
5253    // Note that we inverted the condition above, so we reverse the order of
5254    // the true and false operands here.  This will allow the setcc to be
5255    // matched to a single CSINC instruction.
5256    SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5257    return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5258  }
5259
5260  // Now we know we're dealing with FP values.
5261  assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5262         LHS.getValueType() == MVT::f64);
5263
5264  // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5265  // and do the comparison.
5266  SDValue Cmp;
5267  if (IsStrict)
5268    Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5269  else
5270    Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5271
5272  AArch64CC::CondCode CC1, CC2;
5273  changeFPCCToAArch64CC(CC, CC1, CC2);
5274  SDValue Res;
5275  if (CC2 == AArch64CC::AL) {
5276    changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5277                          CC2);
5278    SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5279
5280    // Note that we inverted the condition above, so we reverse the order of
5281    // the true and false operands here.  This will allow the setcc to be
5282    // matched to a single CSINC instruction.
5283    Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5284  } else {
5285    // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5286    // totally clean.  Some of them require two CSELs to implement.  As is in
5287    // this case, we emit the first CSEL and then emit a second using the output
5288    // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5289
5290    // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5291    SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5292    SDValue CS1 =
5293        DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5294
5295    SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5296    Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5297  }
5298  return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5299}
5300
5301SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5302                                              SDValue RHS, SDValue TVal,
5303                                              SDValue FVal, const SDLoc &dl,
5304                                              SelectionDAG &DAG) const {
5305  // Handle f128 first, because it will result in a comparison of some RTLIB
5306  // call result against zero.
5307  if (LHS.getValueType() == MVT::f128) {
5308    softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5309
5310    // If softenSetCCOperands returned a scalar, we need to compare the result
5311    // against zero to select between true and false values.
5312    if (!RHS.getNode()) {
5313      RHS = DAG.getConstant(0, dl, LHS.getValueType());
5314      CC = ISD::SETNE;
5315    }
5316  }
5317
5318  // Also handle f16, for which we need to do a f32 comparison.
5319  if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5320    LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5321    RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5322  }
5323
5324  // Next, handle integers.
5325  if (LHS.getValueType().isInteger()) {
5326    assert((LHS.getValueType() == RHS.getValueType()) &&
5327           (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5328
5329    unsigned Opcode = AArch64ISD::CSEL;
5330
5331    // If both the TVal and the FVal are constants, see if we can swap them in
5332    // order to for a CSINV or CSINC out of them.
5333    ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5334    ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5335
5336    if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5337      std::swap(TVal, FVal);
5338      std::swap(CTVal, CFVal);
5339      CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5340    } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5341      std::swap(TVal, FVal);
5342      std::swap(CTVal, CFVal);
5343      CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5344    } else if (TVal.getOpcode() == ISD::XOR) {
5345      // If TVal is a NOT we want to swap TVal and FVal so that we can match
5346      // with a CSINV rather than a CSEL.
5347      if (isAllOnesConstant(TVal.getOperand(1))) {
5348        std::swap(TVal, FVal);
5349        std::swap(CTVal, CFVal);
5350        CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5351      }
5352    } else if (TVal.getOpcode() == ISD::SUB) {
5353      // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5354      // that we can match with a CSNEG rather than a CSEL.
5355      if (isNullConstant(TVal.getOperand(0))) {
5356        std::swap(TVal, FVal);
5357        std::swap(CTVal, CFVal);
5358        CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5359      }
5360    } else if (CTVal && CFVal) {
5361      const int64_t TrueVal = CTVal->getSExtValue();
5362      const int64_t FalseVal = CFVal->getSExtValue();
5363      bool Swap = false;
5364
5365      // If both TVal and FVal are constants, see if FVal is the
5366      // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5367      // instead of a CSEL in that case.
5368      if (TrueVal == ~FalseVal) {
5369        Opcode = AArch64ISD::CSINV;
5370      } else if (TrueVal == -FalseVal) {
5371        Opcode = AArch64ISD::CSNEG;
5372      } else if (TVal.getValueType() == MVT::i32) {
5373        // If our operands are only 32-bit wide, make sure we use 32-bit
5374        // arithmetic for the check whether we can use CSINC. This ensures that
5375        // the addition in the check will wrap around properly in case there is
5376        // an overflow (which would not be the case if we do the check with
5377        // 64-bit arithmetic).
5378        const uint32_t TrueVal32 = CTVal->getZExtValue();
5379        const uint32_t FalseVal32 = CFVal->getZExtValue();
5380
5381        if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5382          Opcode = AArch64ISD::CSINC;
5383
5384          if (TrueVal32 > FalseVal32) {
5385            Swap = true;
5386          }
5387        }
5388        // 64-bit check whether we can use CSINC.
5389      } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5390        Opcode = AArch64ISD::CSINC;
5391
5392        if (TrueVal > FalseVal) {
5393          Swap = true;
5394        }
5395      }
5396
5397      // Swap TVal and FVal if necessary.
5398      if (Swap) {
5399        std::swap(TVal, FVal);
5400        std::swap(CTVal, CFVal);
5401        CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5402      }
5403
5404      if (Opcode != AArch64ISD::CSEL) {
5405        // Drop FVal since we can get its value by simply inverting/negating
5406        // TVal.
5407        FVal = TVal;
5408      }
5409    }
5410
5411    // Avoid materializing a constant when possible by reusing a known value in
5412    // a register.  However, don't perform this optimization if the known value
5413    // is one, zero or negative one in the case of a CSEL.  We can always
5414    // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5415    // FVal, respectively.
5416    ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5417    if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5418        !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5419      AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5420      // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5421      // "a != C ? x : a" to avoid materializing C.
5422      if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5423        TVal = LHS;
5424      else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5425        FVal = LHS;
5426    } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5427      assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5428      // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5429      // avoid materializing C.
5430      AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5431      if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5432        Opcode = AArch64ISD::CSINV;
5433        TVal = LHS;
5434        FVal = DAG.getConstant(0, dl, FVal.getValueType());
5435      }
5436    }
5437
5438    SDValue CCVal;
5439    SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5440    EVT VT = TVal.getValueType();
5441    return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5442  }
5443
5444  // Now we know we're dealing with FP values.
5445  assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5446         LHS.getValueType() == MVT::f64);
5447  assert(LHS.getValueType() == RHS.getValueType());
5448  EVT VT = TVal.getValueType();
5449  SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5450
5451  // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5452  // clean.  Some of them require two CSELs to implement.
5453  AArch64CC::CondCode CC1, CC2;
5454  changeFPCCToAArch64CC(CC, CC1, CC2);
5455
5456  if (DAG.getTarget().Options.UnsafeFPMath) {
5457    // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5458    // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5459    ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5460    if (RHSVal && RHSVal->isZero()) {
5461      ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5462      ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5463
5464      if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5465          CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5466        TVal = LHS;
5467      else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5468               CFVal && CFVal->isZero() &&
5469               FVal.getValueType() == LHS.getValueType())
5470        FVal = LHS;
5471    }
5472  }
5473
5474  // Emit first, and possibly only, CSEL.
5475  SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5476  SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5477
5478  // If we need a second CSEL, emit it, using the output of the first as the
5479  // RHS.  We're effectively OR'ing the two CC's together.
5480  if (CC2 != AArch64CC::AL) {
5481    SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5482    return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5483  }
5484
5485  // Otherwise, return the output of the first CSEL.
5486  return CS1;
5487}
5488
5489SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5490                                              SelectionDAG &DAG) const {
5491  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5492  SDValue LHS = Op.getOperand(0);
5493  SDValue RHS = Op.getOperand(1);
5494  SDValue TVal = Op.getOperand(2);
5495  SDValue FVal = Op.getOperand(3);
5496  SDLoc DL(Op);
5497  return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5498}
5499
5500SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5501                                           SelectionDAG &DAG) const {
5502  SDValue CCVal = Op->getOperand(0);
5503  SDValue TVal = Op->getOperand(1);
5504  SDValue FVal = Op->getOperand(2);
5505  SDLoc DL(Op);
5506
5507  // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5508  // instruction.
5509  if (isOverflowIntrOpRes(CCVal)) {
5510    // Only lower legal XALUO ops.
5511    if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5512      return SDValue();
5513
5514    AArch64CC::CondCode OFCC;
5515    SDValue Value, Overflow;
5516    std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5517    SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5518
5519    return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5520                       CCVal, Overflow);
5521  }
5522
5523  // Lower it the same way as we would lower a SELECT_CC node.
5524  ISD::CondCode CC;
5525  SDValue LHS, RHS;
5526  if (CCVal.getOpcode() == ISD::SETCC) {
5527    LHS = CCVal.getOperand(0);
5528    RHS = CCVal.getOperand(1);
5529    CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5530  } else {
5531    LHS = CCVal;
5532    RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5533    CC = ISD::SETNE;
5534  }
5535  return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5536}
5537
5538SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5539                                              SelectionDAG &DAG) const {
5540  // Jump table entries as PC relative offsets. No additional tweaking
5541  // is necessary here. Just get the address of the jump table.
5542  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5543
5544  if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5545      !Subtarget->isTargetMachO()) {
5546    return getAddrLarge(JT, DAG);
5547  } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5548    return getAddrTiny(JT, DAG);
5549  }
5550  return getAddr(JT, DAG);
5551}
5552
5553SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5554                                          SelectionDAG &DAG) const {
5555  // Jump table entries as PC relative offsets. No additional tweaking
5556  // is necessary here. Just get the address of the jump table.
5557  SDLoc DL(Op);
5558  SDValue JT = Op.getOperand(1);
5559  SDValue Entry = Op.getOperand(2);
5560  int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5561
5562  SDNode *Dest =
5563      DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5564                         Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5565  return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5566                     SDValue(Dest, 0));
5567}
5568
5569SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5570                                                 SelectionDAG &DAG) const {
5571  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5572
5573  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5574    // Use the GOT for the large code model on iOS.
5575    if (Subtarget->isTargetMachO()) {
5576      return getGOT(CP, DAG);
5577    }
5578    return getAddrLarge(CP, DAG);
5579  } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5580    return getAddrTiny(CP, DAG);
5581  } else {
5582    return getAddr(CP, DAG);
5583  }
5584}
5585
5586SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5587                                               SelectionDAG &DAG) const {
5588  BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5589  if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5590      !Subtarget->isTargetMachO()) {
5591    return getAddrLarge(BA, DAG);
5592  } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5593    return getAddrTiny(BA, DAG);
5594  }
5595  return getAddr(BA, DAG);
5596}
5597
5598SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5599                                                 SelectionDAG &DAG) const {
5600  AArch64FunctionInfo *FuncInfo =
5601      DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5602
5603  SDLoc DL(Op);
5604  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5605                                 getPointerTy(DAG.getDataLayout()));
5606  FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5607  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5608  return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5609                      MachinePointerInfo(SV));
5610}
5611
5612SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5613                                                  SelectionDAG &DAG) const {
5614  AArch64FunctionInfo *FuncInfo =
5615      DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5616
5617  SDLoc DL(Op);
5618  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5619                                     ? FuncInfo->getVarArgsGPRIndex()
5620                                     : FuncInfo->getVarArgsStackIndex(),
5621                                 getPointerTy(DAG.getDataLayout()));
5622  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5623  return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5624                      MachinePointerInfo(SV));
5625}
5626
5627SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5628                                                SelectionDAG &DAG) const {
5629  // The layout of the va_list struct is specified in the AArch64 Procedure Call
5630  // Standard, section B.3.
5631  MachineFunction &MF = DAG.getMachineFunction();
5632  AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5633  auto PtrVT = getPointerTy(DAG.getDataLayout());
5634  SDLoc DL(Op);
5635
5636  SDValue Chain = Op.getOperand(0);
5637  SDValue VAList = Op.getOperand(1);
5638  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5639  SmallVector<SDValue, 4> MemOps;
5640
5641  // void *__stack at offset 0
5642  SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5643  MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5644                                MachinePointerInfo(SV), /* Alignment = */ 8));
5645
5646  // void *__gr_top at offset 8
5647  int GPRSize = FuncInfo->getVarArgsGPRSize();
5648  if (GPRSize > 0) {
5649    SDValue GRTop, GRTopAddr;
5650
5651    GRTopAddr =
5652        DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5653
5654    GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5655    GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5656                        DAG.getConstant(GPRSize, DL, PtrVT));
5657
5658    MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5659                                  MachinePointerInfo(SV, 8),
5660                                  /* Alignment = */ 8));
5661  }
5662
5663  // void *__vr_top at offset 16
5664  int FPRSize = FuncInfo->getVarArgsFPRSize();
5665  if (FPRSize > 0) {
5666    SDValue VRTop, VRTopAddr;
5667    VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5668                            DAG.getConstant(16, DL, PtrVT));
5669
5670    VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5671    VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5672                        DAG.getConstant(FPRSize, DL, PtrVT));
5673
5674    MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5675                                  MachinePointerInfo(SV, 16),
5676                                  /* Alignment = */ 8));
5677  }
5678
5679  // int __gr_offs at offset 24
5680  SDValue GROffsAddr =
5681      DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5682  MemOps.push_back(DAG.getStore(
5683      Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5684      MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5685
5686  // int __vr_offs at offset 28
5687  SDValue VROffsAddr =
5688      DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5689  MemOps.push_back(DAG.getStore(
5690      Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5691      MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5692
5693  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5694}
5695
5696SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5697                                            SelectionDAG &DAG) const {
5698  MachineFunction &MF = DAG.getMachineFunction();
5699
5700  if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5701    return LowerWin64_VASTART(Op, DAG);
5702  else if (Subtarget->isTargetDarwin())
5703    return LowerDarwin_VASTART(Op, DAG);
5704  else
5705    return LowerAAPCS_VASTART(Op, DAG);
5706}
5707
5708SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5709                                           SelectionDAG &DAG) const {
5710  // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5711  // pointer.
5712  SDLoc DL(Op);
5713  unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5714  unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5715                         Subtarget->isTargetWindows()) ? PtrSize : 32;
5716  const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5717  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5718
5719  return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5720                       DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize,
5721                       false, false, false, MachinePointerInfo(DestSV),
5722                       MachinePointerInfo(SrcSV));
5723}
5724
5725SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5726  assert(Subtarget->isTargetDarwin() &&
5727         "automatic va_arg instruction only works on Darwin");
5728
5729  const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5730  EVT VT = Op.getValueType();
5731  SDLoc DL(Op);
5732  SDValue Chain = Op.getOperand(0);
5733  SDValue Addr = Op.getOperand(1);
5734  unsigned Align = Op.getConstantOperandVal(3);
5735  unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5736  auto PtrVT = getPointerTy(DAG.getDataLayout());
5737  auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5738  SDValue VAList =
5739      DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5740  Chain = VAList.getValue(1);
5741  VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5742
5743  if (Align > MinSlotSize) {
5744    assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5745    VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5746                         DAG.getConstant(Align - 1, DL, PtrVT));
5747    VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5748                         DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5749  }
5750
5751  Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5752  unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5753
5754  // Scalar integer and FP values smaller than 64 bits are implicitly extended
5755  // up to 64 bits.  At the very least, we have to increase the striding of the
5756  // vaargs list to match this, and for FP values we need to introduce
5757  // FP_ROUND nodes as well.
5758  if (VT.isInteger() && !VT.isVector())
5759    ArgSize = std::max(ArgSize, MinSlotSize);
5760  bool NeedFPTrunc = false;
5761  if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5762    ArgSize = 8;
5763    NeedFPTrunc = true;
5764  }
5765
5766  // Increment the pointer, VAList, to the next vaarg
5767  SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5768                               DAG.getConstant(ArgSize, DL, PtrVT));
5769  VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5770
5771  // Store the incremented VAList to the legalized pointer
5772  SDValue APStore =
5773      DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5774
5775  // Load the actual argument out of the pointer VAList
5776  if (NeedFPTrunc) {
5777    // Load the value as an f64.
5778    SDValue WideFP =
5779        DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5780    // Round the value down to an f32.
5781    SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5782                                   DAG.getIntPtrConstant(1, DL));
5783    SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5784    // Merge the rounded value with the chain output of the load.
5785    return DAG.getMergeValues(Ops, DL);
5786  }
5787
5788  return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5789}
5790
5791SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5792                                              SelectionDAG &DAG) const {
5793  MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5794  MFI.setFrameAddressIsTaken(true);
5795
5796  EVT VT = Op.getValueType();
5797  SDLoc DL(Op);
5798  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5799  SDValue FrameAddr =
5800      DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5801  while (Depth--)
5802    FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5803                            MachinePointerInfo());
5804
5805  if (Subtarget->isTargetILP32())
5806    FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5807                            DAG.getValueType(VT));
5808
5809  return FrameAddr;
5810}
5811
5812SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5813                                              SelectionDAG &DAG) const {
5814  MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5815
5816  EVT VT = getPointerTy(DAG.getDataLayout());
5817  SDLoc DL(Op);
5818  int FI = MFI.CreateFixedObject(4, 0, false);
5819  return DAG.getFrameIndex(FI, VT);
5820}
5821
5822#define GET_REGISTER_MATCHER
5823#include "AArch64GenAsmMatcher.inc"
5824
5825// FIXME? Maybe this could be a TableGen attribute on some registers and
5826// this table could be generated automatically from RegInfo.
5827Register AArch64TargetLowering::
5828getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
5829  Register Reg = MatchRegisterName(RegName);
5830  if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5831    const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5832    unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5833    if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5834      Reg = 0;
5835  }
5836  if (Reg)
5837    return Reg;
5838  report_fatal_error(Twine("Invalid register name \""
5839                              + StringRef(RegName)  + "\"."));
5840}
5841
5842SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5843                                                     SelectionDAG &DAG) const {
5844  DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5845
5846  EVT VT = Op.getValueType();
5847  SDLoc DL(Op);
5848
5849  SDValue FrameAddr =
5850      DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5851  SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5852
5853  return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5854}
5855
5856SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5857                                               SelectionDAG &DAG) const {
5858  MachineFunction &MF = DAG.getMachineFunction();
5859  MachineFrameInfo &MFI = MF.getFrameInfo();
5860  MFI.setReturnAddressIsTaken(true);
5861
5862  EVT VT = Op.getValueType();
5863  SDLoc DL(Op);
5864  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5865  if (Depth) {
5866    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5867    SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5868    return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5869                       DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5870                       MachinePointerInfo());
5871  }
5872
5873  // Return LR, which contains the return address. Mark it an implicit live-in.
5874  unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5875  return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5876}
5877
5878/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5879/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5880SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5881                                                    SelectionDAG &DAG) const {
5882  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5883  EVT VT = Op.getValueType();
5884  unsigned VTBits = VT.getSizeInBits();
5885  SDLoc dl(Op);
5886  SDValue ShOpLo = Op.getOperand(0);
5887  SDValue ShOpHi = Op.getOperand(1);
5888  SDValue ShAmt = Op.getOperand(2);
5889  unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5890
5891  assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5892
5893  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5894                                 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5895  SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5896
5897  // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5898  // is "undef". We wanted 0, so CSEL it directly.
5899  SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5900                               ISD::SETEQ, dl, DAG);
5901  SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5902  HiBitsForLo =
5903      DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5904                  HiBitsForLo, CCVal, Cmp);
5905
5906  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5907                                   DAG.getConstant(VTBits, dl, MVT::i64));
5908
5909  SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5910  SDValue LoForNormalShift =
5911      DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5912
5913  Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5914                       dl, DAG);
5915  CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5916  SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5917  SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5918                           LoForNormalShift, CCVal, Cmp);
5919
5920  // AArch64 shifts larger than the register width are wrapped rather than
5921  // clamped, so we can't just emit "hi >> x".
5922  SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5923  SDValue HiForBigShift =
5924      Opc == ISD::SRA
5925          ? DAG.getNode(Opc, dl, VT, ShOpHi,
5926                        DAG.getConstant(VTBits - 1, dl, MVT::i64))
5927          : DAG.getConstant(0, dl, VT);
5928  SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5929                           HiForNormalShift, CCVal, Cmp);
5930
5931  SDValue Ops[2] = { Lo, Hi };
5932  return DAG.getMergeValues(Ops, dl);
5933}
5934
5935/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5936/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5937SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5938                                                   SelectionDAG &DAG) const {
5939  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5940  EVT VT = Op.getValueType();
5941  unsigned VTBits = VT.getSizeInBits();
5942  SDLoc dl(Op);
5943  SDValue ShOpLo = Op.getOperand(0);
5944  SDValue ShOpHi = Op.getOperand(1);
5945  SDValue ShAmt = Op.getOperand(2);
5946
5947  assert(Op.getOpcode() == ISD::SHL_PARTS);
5948  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5949                                 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5950  SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5951
5952  // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5953  // is "undef". We wanted 0, so CSEL it directly.
5954  SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5955                               ISD::SETEQ, dl, DAG);
5956  SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5957  LoBitsForHi =
5958      DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5959                  LoBitsForHi, CCVal, Cmp);
5960
5961  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5962                                   DAG.getConstant(VTBits, dl, MVT::i64));
5963  SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5964  SDValue HiForNormalShift =
5965      DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5966
5967  SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5968
5969  Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5970                       dl, DAG);
5971  CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5972  SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5973                           HiForNormalShift, CCVal, Cmp);
5974
5975  // AArch64 shifts of larger than register sizes are wrapped rather than
5976  // clamped, so we can't just emit "lo << a" if a is too big.
5977  SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5978  SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5979  SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5980                           LoForNormalShift, CCVal, Cmp);
5981
5982  SDValue Ops[2] = { Lo, Hi };
5983  return DAG.getMergeValues(Ops, dl);
5984}
5985
5986bool AArch64TargetLowering::isOffsetFoldingLegal(
5987    const GlobalAddressSDNode *GA) const {
5988  // Offsets are folded in the DAG combine rather than here so that we can
5989  // intelligently choose an offset based on the uses.
5990  return false;
5991}
5992
5993bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5994                                         bool OptForSize) const {
5995  bool IsLegal = false;
5996  // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5997  // 16-bit case when target has full fp16 support.
5998  // FIXME: We should be able to handle f128 as well with a clever lowering.
5999  const APInt ImmInt = Imm.bitcastToAPInt();
6000  if (VT == MVT::f64)
6001    IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6002  else if (VT == MVT::f32)
6003    IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6004  else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6005    IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6006  // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6007  //       generate that fmov.
6008
6009  // If we can not materialize in immediate field for fmov, check if the
6010  // value can be encoded as the immediate operand of a logical instruction.
6011  // The immediate value will be created with either MOVZ, MOVN, or ORR.
6012  if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6013    // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6014    // however the mov+fmov sequence is always better because of the reduced
6015    // cache pressure. The timings are still the same if you consider
6016    // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6017    // movw+movk is fused). So we limit up to 2 instrdduction at most.
6018    SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6019    AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6020			      Insn);
6021    unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6022    IsLegal = Insn.size() <= Limit;
6023  }
6024
6025  LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6026                    << " imm value: "; Imm.dump(););
6027  return IsLegal;
6028}
6029
6030//===----------------------------------------------------------------------===//
6031//                          AArch64 Optimization Hooks
6032//===----------------------------------------------------------------------===//
6033
6034static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6035                           SDValue Operand, SelectionDAG &DAG,
6036                           int &ExtraSteps) {
6037  EVT VT = Operand.getValueType();
6038  if (ST->hasNEON() &&
6039      (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6040       VT == MVT::f32 || VT == MVT::v1f32 ||
6041       VT == MVT::v2f32 || VT == MVT::v4f32)) {
6042    if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6043      // For the reciprocal estimates, convergence is quadratic, so the number
6044      // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6045      // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6046      // the result for float (23 mantissa bits) is 2 and for double (52
6047      // mantissa bits) is 3.
6048      ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6049
6050    return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6051  }
6052
6053  return SDValue();
6054}
6055
6056SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6057                                               SelectionDAG &DAG, int Enabled,
6058                                               int &ExtraSteps,
6059                                               bool &UseOneConst,
6060                                               bool Reciprocal) const {
6061  if (Enabled == ReciprocalEstimate::Enabled ||
6062      (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6063    if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6064                                       DAG, ExtraSteps)) {
6065      SDLoc DL(Operand);
6066      EVT VT = Operand.getValueType();
6067
6068      SDNodeFlags Flags;
6069      Flags.setAllowReassociation(true);
6070
6071      // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6072      // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6073      for (int i = ExtraSteps; i > 0; --i) {
6074        SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6075                                   Flags);
6076        Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6077        Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6078      }
6079      if (!Reciprocal) {
6080        EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6081                                      VT);
6082        SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6083        SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6084
6085        Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6086        // Correct the result if the operand is 0.0.
6087        Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6088                               VT, Eq, Operand, Estimate);
6089      }
6090
6091      ExtraSteps = 0;
6092      return Estimate;
6093    }
6094
6095  return SDValue();
6096}
6097
6098SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6099                                                SelectionDAG &DAG, int Enabled,
6100                                                int &ExtraSteps) const {
6101  if (Enabled == ReciprocalEstimate::Enabled)
6102    if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6103                                       DAG, ExtraSteps)) {
6104      SDLoc DL(Operand);
6105      EVT VT = Operand.getValueType();
6106
6107      SDNodeFlags Flags;
6108      Flags.setAllowReassociation(true);
6109
6110      // Newton reciprocal iteration: E * (2 - X * E)
6111      // AArch64 reciprocal iteration instruction: (2 - M * N)
6112      for (int i = ExtraSteps; i > 0; --i) {
6113        SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6114                                   Estimate, Flags);
6115        Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6116      }
6117
6118      ExtraSteps = 0;
6119      return Estimate;
6120    }
6121
6122  return SDValue();
6123}
6124
6125//===----------------------------------------------------------------------===//
6126//                          AArch64 Inline Assembly Support
6127//===----------------------------------------------------------------------===//
6128
6129// Table of Constraints
6130// TODO: This is the current set of constraints supported by ARM for the
6131// compiler, not all of them may make sense.
6132//
6133// r - A general register
6134// w - An FP/SIMD register of some size in the range v0-v31
6135// x - An FP/SIMD register of some size in the range v0-v15
6136// I - Constant that can be used with an ADD instruction
6137// J - Constant that can be used with a SUB instruction
6138// K - Constant that can be used with a 32-bit logical instruction
6139// L - Constant that can be used with a 64-bit logical instruction
6140// M - Constant that can be used as a 32-bit MOV immediate
6141// N - Constant that can be used as a 64-bit MOV immediate
6142// Q - A memory reference with base register and no offset
6143// S - A symbolic address
6144// Y - Floating point constant zero
6145// Z - Integer constant zero
6146//
6147//   Note that general register operands will be output using their 64-bit x
6148// register name, whatever the size of the variable, unless the asm operand
6149// is prefixed by the %w modifier. Floating-point and SIMD register operands
6150// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6151// %q modifier.
6152const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6153  // At this point, we have to lower this constraint to something else, so we
6154  // lower it to an "r" or "w". However, by doing this we will force the result
6155  // to be in register, while the X constraint is much more permissive.
6156  //
6157  // Although we are correct (we are free to emit anything, without
6158  // constraints), we might break use cases that would expect us to be more
6159  // efficient and emit something else.
6160  if (!Subtarget->hasFPARMv8())
6161    return "r";
6162
6163  if (ConstraintVT.isFloatingPoint())
6164    return "w";
6165
6166  if (ConstraintVT.isVector() &&
6167     (ConstraintVT.getSizeInBits() == 64 ||
6168      ConstraintVT.getSizeInBits() == 128))
6169    return "w";
6170
6171  return "r";
6172}
6173
6174enum PredicateConstraint {
6175  Upl,
6176  Upa,
6177  Invalid
6178};
6179
6180static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6181  PredicateConstraint P = PredicateConstraint::Invalid;
6182  if (Constraint == "Upa")
6183    P = PredicateConstraint::Upa;
6184  if (Constraint == "Upl")
6185    P = PredicateConstraint::Upl;
6186  return P;
6187}
6188
6189/// getConstraintType - Given a constraint letter, return the type of
6190/// constraint it is for this target.
6191AArch64TargetLowering::ConstraintType
6192AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6193  if (Constraint.size() == 1) {
6194    switch (Constraint[0]) {
6195    default:
6196      break;
6197    case 'x':
6198    case 'w':
6199    case 'y':
6200      return C_RegisterClass;
6201    // An address with a single base register. Due to the way we
6202    // currently handle addresses it is the same as 'r'.
6203    case 'Q':
6204      return C_Memory;
6205    case 'I':
6206    case 'J':
6207    case 'K':
6208    case 'L':
6209    case 'M':
6210    case 'N':
6211    case 'Y':
6212    case 'Z':
6213      return C_Immediate;
6214    case 'z':
6215    case 'S': // A symbolic address
6216      return C_Other;
6217    }
6218  } else if (parsePredicateConstraint(Constraint) !=
6219             PredicateConstraint::Invalid)
6220      return C_RegisterClass;
6221  return TargetLowering::getConstraintType(Constraint);
6222}
6223
6224/// Examine constraint type and operand type and determine a weight value.
6225/// This object must already have been set up with the operand type
6226/// and the current alternative constraint selected.
6227TargetLowering::ConstraintWeight
6228AArch64TargetLowering::getSingleConstraintMatchWeight(
6229    AsmOperandInfo &info, const char *constraint) const {
6230  ConstraintWeight weight = CW_Invalid;
6231  Value *CallOperandVal = info.CallOperandVal;
6232  // If we don't have a value, we can't do a match,
6233  // but allow it at the lowest weight.
6234  if (!CallOperandVal)
6235    return CW_Default;
6236  Type *type = CallOperandVal->getType();
6237  // Look at the constraint type.
6238  switch (*constraint) {
6239  default:
6240    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6241    break;
6242  case 'x':
6243  case 'w':
6244  case 'y':
6245    if (type->isFloatingPointTy() || type->isVectorTy())
6246      weight = CW_Register;
6247    break;
6248  case 'z':
6249    weight = CW_Constant;
6250    break;
6251  case 'U':
6252    if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6253      weight = CW_Register;
6254    break;
6255  }
6256  return weight;
6257}
6258
6259std::pair<unsigned, const TargetRegisterClass *>
6260AArch64TargetLowering::getRegForInlineAsmConstraint(
6261    const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6262  if (Constraint.size() == 1) {
6263    switch (Constraint[0]) {
6264    case 'r':
6265      if (VT.getSizeInBits() == 64)
6266        return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6267      return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6268    case 'w':
6269      if (!Subtarget->hasFPARMv8())
6270        break;
6271      if (VT.isScalableVector())
6272        return std::make_pair(0U, &AArch64::ZPRRegClass);
6273      if (VT.getSizeInBits() == 16)
6274        return std::make_pair(0U, &AArch64::FPR16RegClass);
6275      if (VT.getSizeInBits() == 32)
6276        return std::make_pair(0U, &AArch64::FPR32RegClass);
6277      if (VT.getSizeInBits() == 64)
6278        return std::make_pair(0U, &AArch64::FPR64RegClass);
6279      if (VT.getSizeInBits() == 128)
6280        return std::make_pair(0U, &AArch64::FPR128RegClass);
6281      break;
6282    // The instructions that this constraint is designed for can
6283    // only take 128-bit registers so just use that regclass.
6284    case 'x':
6285      if (!Subtarget->hasFPARMv8())
6286        break;
6287      if (VT.isScalableVector())
6288        return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6289      if (VT.getSizeInBits() == 128)
6290        return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6291      break;
6292    case 'y':
6293      if (!Subtarget->hasFPARMv8())
6294        break;
6295      if (VT.isScalableVector())
6296        return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6297      break;
6298    }
6299  } else {
6300    PredicateConstraint PC = parsePredicateConstraint(Constraint);
6301    if (PC != PredicateConstraint::Invalid) {
6302      assert(VT.isScalableVector());
6303      bool restricted = (PC == PredicateConstraint::Upl);
6304      return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6305                          : std::make_pair(0U, &AArch64::PPRRegClass);
6306    }
6307  }
6308  if (StringRef("{cc}").equals_lower(Constraint))
6309    return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6310
6311  // Use the default implementation in TargetLowering to convert the register
6312  // constraint into a member of a register class.
6313  std::pair<unsigned, const TargetRegisterClass *> Res;
6314  Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6315
6316  // Not found as a standard register?
6317  if (!Res.second) {
6318    unsigned Size = Constraint.size();
6319    if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6320        tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6321      int RegNo;
6322      bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6323      if (!Failed && RegNo >= 0 && RegNo <= 31) {
6324        // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6325        // By default we'll emit v0-v31 for this unless there's a modifier where
6326        // we'll emit the correct register as well.
6327        if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6328          Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6329          Res.second = &AArch64::FPR64RegClass;
6330        } else {
6331          Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6332          Res.second = &AArch64::FPR128RegClass;
6333        }
6334      }
6335    }
6336  }
6337
6338  if (Res.second && !Subtarget->hasFPARMv8() &&
6339      !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6340      !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6341    return std::make_pair(0U, nullptr);
6342
6343  return Res;
6344}
6345
6346/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6347/// vector.  If it is invalid, don't add anything to Ops.
6348void AArch64TargetLowering::LowerAsmOperandForConstraint(
6349    SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6350    SelectionDAG &DAG) const {
6351  SDValue Result;
6352
6353  // Currently only support length 1 constraints.
6354  if (Constraint.length() != 1)
6355    return;
6356
6357  char ConstraintLetter = Constraint[0];
6358  switch (ConstraintLetter) {
6359  default:
6360    break;
6361
6362  // This set of constraints deal with valid constants for various instructions.
6363  // Validate and return a target constant for them if we can.
6364  case 'z': {
6365    // 'z' maps to xzr or wzr so it needs an input of 0.
6366    if (!isNullConstant(Op))
6367      return;
6368
6369    if (Op.getValueType() == MVT::i64)
6370      Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6371    else
6372      Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6373    break;
6374  }
6375  case 'S': {
6376    // An absolute symbolic address or label reference.
6377    if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6378      Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6379                                          GA->getValueType(0));
6380    } else if (const BlockAddressSDNode *BA =
6381                   dyn_cast<BlockAddressSDNode>(Op)) {
6382      Result =
6383          DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6384    } else if (const ExternalSymbolSDNode *ES =
6385                   dyn_cast<ExternalSymbolSDNode>(Op)) {
6386      Result =
6387          DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6388    } else
6389      return;
6390    break;
6391  }
6392
6393  case 'I':
6394  case 'J':
6395  case 'K':
6396  case 'L':
6397  case 'M':
6398  case 'N':
6399    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6400    if (!C)
6401      return;
6402
6403    // Grab the value and do some validation.
6404    uint64_t CVal = C->getZExtValue();
6405    switch (ConstraintLetter) {
6406    // The I constraint applies only to simple ADD or SUB immediate operands:
6407    // i.e. 0 to 4095 with optional shift by 12
6408    // The J constraint applies only to ADD or SUB immediates that would be
6409    // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6410    // instruction [or vice versa], in other words -1 to -4095 with optional
6411    // left shift by 12.
6412    case 'I':
6413      if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6414        break;
6415      return;
6416    case 'J': {
6417      uint64_t NVal = -C->getSExtValue();
6418      if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6419        CVal = C->getSExtValue();
6420        break;
6421      }
6422      return;
6423    }
6424    // The K and L constraints apply *only* to logical immediates, including
6425    // what used to be the MOVI alias for ORR (though the MOVI alias has now
6426    // been removed and MOV should be used). So these constraints have to
6427    // distinguish between bit patterns that are valid 32-bit or 64-bit
6428    // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6429    // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6430    // versa.
6431    case 'K':
6432      if (AArch64_AM::isLogicalImmediate(CVal, 32))
6433        break;
6434      return;
6435    case 'L':
6436      if (AArch64_AM::isLogicalImmediate(CVal, 64))
6437        break;
6438      return;
6439    // The M and N constraints are a superset of K and L respectively, for use
6440    // with the MOV (immediate) alias. As well as the logical immediates they
6441    // also match 32 or 64-bit immediates that can be loaded either using a
6442    // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6443    // (M) or 64-bit 0x1234000000000000 (N) etc.
6444    // As a note some of this code is liberally stolen from the asm parser.
6445    case 'M': {
6446      if (!isUInt<32>(CVal))
6447        return;
6448      if (AArch64_AM::isLogicalImmediate(CVal, 32))
6449        break;
6450      if ((CVal & 0xFFFF) == CVal)
6451        break;
6452      if ((CVal & 0xFFFF0000ULL) == CVal)
6453        break;
6454      uint64_t NCVal = ~(uint32_t)CVal;
6455      if ((NCVal & 0xFFFFULL) == NCVal)
6456        break;
6457      if ((NCVal & 0xFFFF0000ULL) == NCVal)
6458        break;
6459      return;
6460    }
6461    case 'N': {
6462      if (AArch64_AM::isLogicalImmediate(CVal, 64))
6463        break;
6464      if ((CVal & 0xFFFFULL) == CVal)
6465        break;
6466      if ((CVal & 0xFFFF0000ULL) == CVal)
6467        break;
6468      if ((CVal & 0xFFFF00000000ULL) == CVal)
6469        break;
6470      if ((CVal & 0xFFFF000000000000ULL) == CVal)
6471        break;
6472      uint64_t NCVal = ~CVal;
6473      if ((NCVal & 0xFFFFULL) == NCVal)
6474        break;
6475      if ((NCVal & 0xFFFF0000ULL) == NCVal)
6476        break;
6477      if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6478        break;
6479      if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6480        break;
6481      return;
6482    }
6483    default:
6484      return;
6485    }
6486
6487    // All assembler immediates are 64-bit integers.
6488    Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6489    break;
6490  }
6491
6492  if (Result.getNode()) {
6493    Ops.push_back(Result);
6494    return;
6495  }
6496
6497  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6498}
6499
6500//===----------------------------------------------------------------------===//
6501//                     AArch64 Advanced SIMD Support
6502//===----------------------------------------------------------------------===//
6503
6504/// WidenVector - Given a value in the V64 register class, produce the
6505/// equivalent value in the V128 register class.
6506static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6507  EVT VT = V64Reg.getValueType();
6508  unsigned NarrowSize = VT.getVectorNumElements();
6509  MVT EltTy = VT.getVectorElementType().getSimpleVT();
6510  MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6511  SDLoc DL(V64Reg);
6512
6513  return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6514                     V64Reg, DAG.getConstant(0, DL, MVT::i32));
6515}
6516
6517/// getExtFactor - Determine the adjustment factor for the position when
6518/// generating an "extract from vector registers" instruction.
6519static unsigned getExtFactor(SDValue &V) {
6520  EVT EltType = V.getValueType().getVectorElementType();
6521  return EltType.getSizeInBits() / 8;
6522}
6523
6524/// NarrowVector - Given a value in the V128 register class, produce the
6525/// equivalent value in the V64 register class.
6526static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6527  EVT VT = V128Reg.getValueType();
6528  unsigned WideSize = VT.getVectorNumElements();
6529  MVT EltTy = VT.getVectorElementType().getSimpleVT();
6530  MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6531  SDLoc DL(V128Reg);
6532
6533  return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6534}
6535
6536// Gather data to see if the operation can be modelled as a
6537// shuffle in combination with VEXTs.
6538SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6539                                                  SelectionDAG &DAG) const {
6540  assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6541  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6542  SDLoc dl(Op);
6543  EVT VT = Op.getValueType();
6544  unsigned NumElts = VT.getVectorNumElements();
6545
6546  struct ShuffleSourceInfo {
6547    SDValue Vec;
6548    unsigned MinElt;
6549    unsigned MaxElt;
6550
6551    // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6552    // be compatible with the shuffle we intend to construct. As a result
6553    // ShuffleVec will be some sliding window into the original Vec.
6554    SDValue ShuffleVec;
6555
6556    // Code should guarantee that element i in Vec starts at element "WindowBase
6557    // + i * WindowScale in ShuffleVec".
6558    int WindowBase;
6559    int WindowScale;
6560
6561    ShuffleSourceInfo(SDValue Vec)
6562      : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6563          ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6564
6565    bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6566  };
6567
6568  // First gather all vectors used as an immediate source for this BUILD_VECTOR
6569  // node.
6570  SmallVector<ShuffleSourceInfo, 2> Sources;
6571  for (unsigned i = 0; i < NumElts; ++i) {
6572    SDValue V = Op.getOperand(i);
6573    if (V.isUndef())
6574      continue;
6575    else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6576             !isa<ConstantSDNode>(V.getOperand(1))) {
6577      LLVM_DEBUG(
6578          dbgs() << "Reshuffle failed: "
6579                    "a shuffle can only come from building a vector from "
6580                    "various elements of other vectors, provided their "
6581                    "indices are constant\n");
6582      return SDValue();
6583    }
6584
6585    // Add this element source to the list if it's not already there.
6586    SDValue SourceVec = V.getOperand(0);
6587    auto Source = find(Sources, SourceVec);
6588    if (Source == Sources.end())
6589      Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6590
6591    // Update the minimum and maximum lane number seen.
6592    unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6593    Source->MinElt = std::min(Source->MinElt, EltNo);
6594    Source->MaxElt = std::max(Source->MaxElt, EltNo);
6595  }
6596
6597  if (Sources.size() > 2) {
6598    LLVM_DEBUG(
6599        dbgs() << "Reshuffle failed: currently only do something sane when at "
6600                  "most two source vectors are involved\n");
6601    return SDValue();
6602  }
6603
6604  // Find out the smallest element size among result and two sources, and use
6605  // it as element size to build the shuffle_vector.
6606  EVT SmallestEltTy = VT.getVectorElementType();
6607  for (auto &Source : Sources) {
6608    EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6609    if (SrcEltTy.bitsLT(SmallestEltTy)) {
6610      SmallestEltTy = SrcEltTy;
6611    }
6612  }
6613  unsigned ResMultiplier =
6614      VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6615  NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6616  EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6617
6618  // If the source vector is too wide or too narrow, we may nevertheless be able
6619  // to construct a compatible shuffle either by concatenating it with UNDEF or
6620  // extracting a suitable range of elements.
6621  for (auto &Src : Sources) {
6622    EVT SrcVT = Src.ShuffleVec.getValueType();
6623
6624    if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6625      continue;
6626
6627    // This stage of the search produces a source with the same element type as
6628    // the original, but with a total width matching the BUILD_VECTOR output.
6629    EVT EltVT = SrcVT.getVectorElementType();
6630    unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6631    EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6632
6633    if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6634      assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6635      // We can pad out the smaller vector for free, so if it's part of a
6636      // shuffle...
6637      Src.ShuffleVec =
6638          DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6639                      DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6640      continue;
6641    }
6642
6643    assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6644
6645    if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6646      LLVM_DEBUG(
6647          dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6648      return SDValue();
6649    }
6650
6651    if (Src.MinElt >= NumSrcElts) {
6652      // The extraction can just take the second half
6653      Src.ShuffleVec =
6654          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6655                      DAG.getConstant(NumSrcElts, dl, MVT::i64));
6656      Src.WindowBase = -NumSrcElts;
6657    } else if (Src.MaxElt < NumSrcElts) {
6658      // The extraction can just take the first half
6659      Src.ShuffleVec =
6660          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6661                      DAG.getConstant(0, dl, MVT::i64));
6662    } else {
6663      // An actual VEXT is needed
6664      SDValue VEXTSrc1 =
6665          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6666                      DAG.getConstant(0, dl, MVT::i64));
6667      SDValue VEXTSrc2 =
6668          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6669                      DAG.getConstant(NumSrcElts, dl, MVT::i64));
6670      unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6671
6672      Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6673                                   VEXTSrc2,
6674                                   DAG.getConstant(Imm, dl, MVT::i32));
6675      Src.WindowBase = -Src.MinElt;
6676    }
6677  }
6678
6679  // Another possible incompatibility occurs from the vector element types. We
6680  // can fix this by bitcasting the source vectors to the same type we intend
6681  // for the shuffle.
6682  for (auto &Src : Sources) {
6683    EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6684    if (SrcEltTy == SmallestEltTy)
6685      continue;
6686    assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6687    Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6688    Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6689    Src.WindowBase *= Src.WindowScale;
6690  }
6691
6692  // Final sanity check before we try to actually produce a shuffle.
6693  LLVM_DEBUG(for (auto Src
6694                  : Sources)
6695                 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6696
6697  // The stars all align, our next step is to produce the mask for the shuffle.
6698  SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6699  int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6700  for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6701    SDValue Entry = Op.getOperand(i);
6702    if (Entry.isUndef())
6703      continue;
6704
6705    auto Src = find(Sources, Entry.getOperand(0));
6706    int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6707
6708    // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6709    // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6710    // segment.
6711    EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6712    int BitsDefined =
6713        std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6714    int LanesDefined = BitsDefined / BitsPerShuffleLane;
6715
6716    // This source is expected to fill ResMultiplier lanes of the final shuffle,
6717    // starting at the appropriate offset.
6718    int *LaneMask = &Mask[i * ResMultiplier];
6719
6720    int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6721    ExtractBase += NumElts * (Src - Sources.begin());
6722    for (int j = 0; j < LanesDefined; ++j)
6723      LaneMask[j] = ExtractBase + j;
6724  }
6725
6726  // Final check before we try to produce nonsense...
6727  if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6728    LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6729    return SDValue();
6730  }
6731
6732  SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6733  for (unsigned i = 0; i < Sources.size(); ++i)
6734    ShuffleOps[i] = Sources[i].ShuffleVec;
6735
6736  SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6737                                         ShuffleOps[1], Mask);
6738  SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6739
6740  LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6741             dbgs() << "Reshuffle, creating node: "; V.dump(););
6742
6743  return V;
6744}
6745
6746// check if an EXT instruction can handle the shuffle mask when the
6747// vector sources of the shuffle are the same.
6748static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6749  unsigned NumElts = VT.getVectorNumElements();
6750
6751  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6752  if (M[0] < 0)
6753    return false;
6754
6755  Imm = M[0];
6756
6757  // If this is a VEXT shuffle, the immediate value is the index of the first
6758  // element.  The other shuffle indices must be the successive elements after
6759  // the first one.
6760  unsigned ExpectedElt = Imm;
6761  for (unsigned i = 1; i < NumElts; ++i) {
6762    // Increment the expected index.  If it wraps around, just follow it
6763    // back to index zero and keep going.
6764    ++ExpectedElt;
6765    if (ExpectedElt == NumElts)
6766      ExpectedElt = 0;
6767
6768    if (M[i] < 0)
6769      continue; // ignore UNDEF indices
6770    if (ExpectedElt != static_cast<unsigned>(M[i]))
6771      return false;
6772  }
6773
6774  return true;
6775}
6776
6777// check if an EXT instruction can handle the shuffle mask when the
6778// vector sources of the shuffle are different.
6779static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6780                      unsigned &Imm) {
6781  // Look for the first non-undef element.
6782  const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6783
6784  // Benefit form APInt to handle overflow when calculating expected element.
6785  unsigned NumElts = VT.getVectorNumElements();
6786  unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6787  APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6788  // The following shuffle indices must be the successive elements after the
6789  // first real element.
6790  const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6791      [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6792  if (FirstWrongElt != M.end())
6793    return false;
6794
6795  // The index of an EXT is the first element if it is not UNDEF.
6796  // Watch out for the beginning UNDEFs. The EXT index should be the expected
6797  // value of the first element.  E.g.
6798  // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6799  // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6800  // ExpectedElt is the last mask index plus 1.
6801  Imm = ExpectedElt.getZExtValue();
6802
6803  // There are two difference cases requiring to reverse input vectors.
6804  // For example, for vector <4 x i32> we have the following cases,
6805  // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6806  // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6807  // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6808  // to reverse two input vectors.
6809  if (Imm < NumElts)
6810    ReverseEXT = true;
6811  else
6812    Imm -= NumElts;
6813
6814  return true;
6815}
6816
6817/// isREVMask - Check if a vector shuffle corresponds to a REV
6818/// instruction with the specified blocksize.  (The order of the elements
6819/// within each block of the vector is reversed.)
6820static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6821  assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6822         "Only possible block sizes for REV are: 16, 32, 64");
6823
6824  unsigned EltSz = VT.getScalarSizeInBits();
6825  if (EltSz == 64)
6826    return false;
6827
6828  unsigned NumElts = VT.getVectorNumElements();
6829  unsigned BlockElts = M[0] + 1;
6830  // If the first shuffle index is UNDEF, be optimistic.
6831  if (M[0] < 0)
6832    BlockElts = BlockSize / EltSz;
6833
6834  if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6835    return false;
6836
6837  for (unsigned i = 0; i < NumElts; ++i) {
6838    if (M[i] < 0)
6839      continue; // ignore UNDEF indices
6840    if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6841      return false;
6842  }
6843
6844  return true;
6845}
6846
6847static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6848  unsigned NumElts = VT.getVectorNumElements();
6849  if (NumElts % 2 != 0)
6850    return false;
6851  WhichResult = (M[0] == 0 ? 0 : 1);
6852  unsigned Idx = WhichResult * NumElts / 2;
6853  for (unsigned i = 0; i != NumElts; i += 2) {
6854    if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6855        (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6856      return false;
6857    Idx += 1;
6858  }
6859
6860  return true;
6861}
6862
6863static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6864  unsigned NumElts = VT.getVectorNumElements();
6865  WhichResult = (M[0] == 0 ? 0 : 1);
6866  for (unsigned i = 0; i != NumElts; ++i) {
6867    if (M[i] < 0)
6868      continue; // ignore UNDEF indices
6869    if ((unsigned)M[i] != 2 * i + WhichResult)
6870      return false;
6871  }
6872
6873  return true;
6874}
6875
6876static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6877  unsigned NumElts = VT.getVectorNumElements();
6878  if (NumElts % 2 != 0)
6879    return false;
6880  WhichResult = (M[0] == 0 ? 0 : 1);
6881  for (unsigned i = 0; i < NumElts; i += 2) {
6882    if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6883        (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6884      return false;
6885  }
6886  return true;
6887}
6888
6889/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6890/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6891/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6892static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6893  unsigned NumElts = VT.getVectorNumElements();
6894  if (NumElts % 2 != 0)
6895    return false;
6896  WhichResult = (M[0] == 0 ? 0 : 1);
6897  unsigned Idx = WhichResult * NumElts / 2;
6898  for (unsigned i = 0; i != NumElts; i += 2) {
6899    if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6900        (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6901      return false;
6902    Idx += 1;
6903  }
6904
6905  return true;
6906}
6907
6908/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6909/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6910/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6911static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6912  unsigned Half = VT.getVectorNumElements() / 2;
6913  WhichResult = (M[0] == 0 ? 0 : 1);
6914  for (unsigned j = 0; j != 2; ++j) {
6915    unsigned Idx = WhichResult;
6916    for (unsigned i = 0; i != Half; ++i) {
6917      int MIdx = M[i + j * Half];
6918      if (MIdx >= 0 && (unsigned)MIdx != Idx)
6919        return false;
6920      Idx += 2;
6921    }
6922  }
6923
6924  return true;
6925}
6926
6927/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6928/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6929/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6930static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6931  unsigned NumElts = VT.getVectorNumElements();
6932  if (NumElts % 2 != 0)
6933    return false;
6934  WhichResult = (M[0] == 0 ? 0 : 1);
6935  for (unsigned i = 0; i < NumElts; i += 2) {
6936    if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6937        (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6938      return false;
6939  }
6940  return true;
6941}
6942
6943static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6944                      bool &DstIsLeft, int &Anomaly) {
6945  if (M.size() != static_cast<size_t>(NumInputElements))
6946    return false;
6947
6948  int NumLHSMatch = 0, NumRHSMatch = 0;
6949  int LastLHSMismatch = -1, LastRHSMismatch = -1;
6950
6951  for (int i = 0; i < NumInputElements; ++i) {
6952    if (M[i] == -1) {
6953      ++NumLHSMatch;
6954      ++NumRHSMatch;
6955      continue;
6956    }
6957
6958    if (M[i] == i)
6959      ++NumLHSMatch;
6960    else
6961      LastLHSMismatch = i;
6962
6963    if (M[i] == i + NumInputElements)
6964      ++NumRHSMatch;
6965    else
6966      LastRHSMismatch = i;
6967  }
6968
6969  if (NumLHSMatch == NumInputElements - 1) {
6970    DstIsLeft = true;
6971    Anomaly = LastLHSMismatch;
6972    return true;
6973  } else if (NumRHSMatch == NumInputElements - 1) {
6974    DstIsLeft = false;
6975    Anomaly = LastRHSMismatch;
6976    return true;
6977  }
6978
6979  return false;
6980}
6981
6982static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6983  if (VT.getSizeInBits() != 128)
6984    return false;
6985
6986  unsigned NumElts = VT.getVectorNumElements();
6987
6988  for (int I = 0, E = NumElts / 2; I != E; I++) {
6989    if (Mask[I] != I)
6990      return false;
6991  }
6992
6993  int Offset = NumElts / 2;
6994  for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6995    if (Mask[I] != I + SplitLHS * Offset)
6996      return false;
6997  }
6998
6999  return true;
7000}
7001
7002static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7003  SDLoc DL(Op);
7004  EVT VT = Op.getValueType();
7005  SDValue V0 = Op.getOperand(0);
7006  SDValue V1 = Op.getOperand(1);
7007  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7008
7009  if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7010      VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7011    return SDValue();
7012
7013  bool SplitV0 = V0.getValueSizeInBits() == 128;
7014
7015  if (!isConcatMask(Mask, VT, SplitV0))
7016    return SDValue();
7017
7018  EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7019  if (SplitV0) {
7020    V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7021                     DAG.getConstant(0, DL, MVT::i64));
7022  }
7023  if (V1.getValueSizeInBits() == 128) {
7024    V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7025                     DAG.getConstant(0, DL, MVT::i64));
7026  }
7027  return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7028}
7029
7030/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7031/// the specified operations to build the shuffle.
7032static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7033                                      SDValue RHS, SelectionDAG &DAG,
7034                                      const SDLoc &dl) {
7035  unsigned OpNum = (PFEntry >> 26) & 0x0F;
7036  unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7037  unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7038
7039  enum {
7040    OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7041    OP_VREV,
7042    OP_VDUP0,
7043    OP_VDUP1,
7044    OP_VDUP2,
7045    OP_VDUP3,
7046    OP_VEXT1,
7047    OP_VEXT2,
7048    OP_VEXT3,
7049    OP_VUZPL, // VUZP, left result
7050    OP_VUZPR, // VUZP, right result
7051    OP_VZIPL, // VZIP, left result
7052    OP_VZIPR, // VZIP, right result
7053    OP_VTRNL, // VTRN, left result
7054    OP_VTRNR  // VTRN, right result
7055  };
7056
7057  if (OpNum == OP_COPY) {
7058    if (LHSID == (1 * 9 + 2) * 9 + 3)
7059      return LHS;
7060    assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7061    return RHS;
7062  }
7063
7064  SDValue OpLHS, OpRHS;
7065  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7066  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7067  EVT VT = OpLHS.getValueType();
7068
7069  switch (OpNum) {
7070  default:
7071    llvm_unreachable("Unknown shuffle opcode!");
7072  case OP_VREV:
7073    // VREV divides the vector in half and swaps within the half.
7074    if (VT.getVectorElementType() == MVT::i32 ||
7075        VT.getVectorElementType() == MVT::f32)
7076      return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7077    // vrev <4 x i16> -> REV32
7078    if (VT.getVectorElementType() == MVT::i16 ||
7079        VT.getVectorElementType() == MVT::f16)
7080      return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7081    // vrev <4 x i8> -> REV16
7082    assert(VT.getVectorElementType() == MVT::i8);
7083    return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7084  case OP_VDUP0:
7085  case OP_VDUP1:
7086  case OP_VDUP2:
7087  case OP_VDUP3: {
7088    EVT EltTy = VT.getVectorElementType();
7089    unsigned Opcode;
7090    if (EltTy == MVT::i8)
7091      Opcode = AArch64ISD::DUPLANE8;
7092    else if (EltTy == MVT::i16 || EltTy == MVT::f16)
7093      Opcode = AArch64ISD::DUPLANE16;
7094    else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7095      Opcode = AArch64ISD::DUPLANE32;
7096    else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7097      Opcode = AArch64ISD::DUPLANE64;
7098    else
7099      llvm_unreachable("Invalid vector element type?");
7100
7101    if (VT.getSizeInBits() == 64)
7102      OpLHS = WidenVector(OpLHS, DAG);
7103    SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7104    return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7105  }
7106  case OP_VEXT1:
7107  case OP_VEXT2:
7108  case OP_VEXT3: {
7109    unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7110    return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7111                       DAG.getConstant(Imm, dl, MVT::i32));
7112  }
7113  case OP_VUZPL:
7114    return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7115                       OpRHS);
7116  case OP_VUZPR:
7117    return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7118                       OpRHS);
7119  case OP_VZIPL:
7120    return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7121                       OpRHS);
7122  case OP_VZIPR:
7123    return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7124                       OpRHS);
7125  case OP_VTRNL:
7126    return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7127                       OpRHS);
7128  case OP_VTRNR:
7129    return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7130                       OpRHS);
7131  }
7132}
7133
7134static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7135                           SelectionDAG &DAG) {
7136  // Check to see if we can use the TBL instruction.
7137  SDValue V1 = Op.getOperand(0);
7138  SDValue V2 = Op.getOperand(1);
7139  SDLoc DL(Op);
7140
7141  EVT EltVT = Op.getValueType().getVectorElementType();
7142  unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7143
7144  SmallVector<SDValue, 8> TBLMask;
7145  for (int Val : ShuffleMask) {
7146    for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7147      unsigned Offset = Byte + Val * BytesPerElt;
7148      TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7149    }
7150  }
7151
7152  MVT IndexVT = MVT::v8i8;
7153  unsigned IndexLen = 8;
7154  if (Op.getValueSizeInBits() == 128) {
7155    IndexVT = MVT::v16i8;
7156    IndexLen = 16;
7157  }
7158
7159  SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7160  SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7161
7162  SDValue Shuffle;
7163  if (V2.getNode()->isUndef()) {
7164    if (IndexLen == 8)
7165      V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7166    Shuffle = DAG.getNode(
7167        ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7168        DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7169        DAG.getBuildVector(IndexVT, DL,
7170                           makeArrayRef(TBLMask.data(), IndexLen)));
7171  } else {
7172    if (IndexLen == 8) {
7173      V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7174      Shuffle = DAG.getNode(
7175          ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7176          DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7177          DAG.getBuildVector(IndexVT, DL,
7178                             makeArrayRef(TBLMask.data(), IndexLen)));
7179    } else {
7180      // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7181      // cannot currently represent the register constraints on the input
7182      // table registers.
7183      //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7184      //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7185      //                   IndexLen));
7186      Shuffle = DAG.getNode(
7187          ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7188          DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7189          V2Cst, DAG.getBuildVector(IndexVT, DL,
7190                                    makeArrayRef(TBLMask.data(), IndexLen)));
7191    }
7192  }
7193  return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7194}
7195
7196static unsigned getDUPLANEOp(EVT EltType) {
7197  if (EltType == MVT::i8)
7198    return AArch64ISD::DUPLANE8;
7199  if (EltType == MVT::i16 || EltType == MVT::f16)
7200    return AArch64ISD::DUPLANE16;
7201  if (EltType == MVT::i32 || EltType == MVT::f32)
7202    return AArch64ISD::DUPLANE32;
7203  if (EltType == MVT::i64 || EltType == MVT::f64)
7204    return AArch64ISD::DUPLANE64;
7205
7206  llvm_unreachable("Invalid vector element type?");
7207}
7208
7209SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7210                                                   SelectionDAG &DAG) const {
7211  SDLoc dl(Op);
7212  EVT VT = Op.getValueType();
7213
7214  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7215
7216  // Convert shuffles that are directly supported on NEON to target-specific
7217  // DAG nodes, instead of keeping them as shuffles and matching them again
7218  // during code selection.  This is more efficient and avoids the possibility
7219  // of inconsistencies between legalization and selection.
7220  ArrayRef<int> ShuffleMask = SVN->getMask();
7221
7222  SDValue V1 = Op.getOperand(0);
7223  SDValue V2 = Op.getOperand(1);
7224
7225  if (SVN->isSplat()) {
7226    int Lane = SVN->getSplatIndex();
7227    // If this is undef splat, generate it via "just" vdup, if possible.
7228    if (Lane == -1)
7229      Lane = 0;
7230
7231    if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7232      return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7233                         V1.getOperand(0));
7234    // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7235    // constant. If so, we can just reference the lane's definition directly.
7236    if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7237        !isa<ConstantSDNode>(V1.getOperand(Lane)))
7238      return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7239
7240    // Otherwise, duplicate from the lane of the input vector.
7241    unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7242
7243    // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7244    auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7245      // Match: dup (bitcast (extract_subv X, C)), LaneC
7246      if (BitCast.getOpcode() != ISD::BITCAST ||
7247          BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7248        return false;
7249
7250      // The extract index must align in the destination type. That may not
7251      // happen if the bitcast is from narrow to wide type.
7252      SDValue Extract = BitCast.getOperand(0);
7253      unsigned ExtIdx = Extract.getConstantOperandVal(1);
7254      unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7255      unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7256      unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7257      if (ExtIdxInBits % CastedEltBitWidth != 0)
7258        return false;
7259
7260      // Update the lane value by offsetting with the scaled extract index.
7261      LaneC += ExtIdxInBits / CastedEltBitWidth;
7262
7263      // Determine the casted vector type of the wide vector input.
7264      // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7265      // Examples:
7266      // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7267      // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7268      unsigned SrcVecNumElts =
7269          Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7270      CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7271                                SrcVecNumElts);
7272      return true;
7273    };
7274    MVT CastVT;
7275    if (getScaledOffsetDup(V1, Lane, CastVT)) {
7276      V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7277    } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7278      // The lane is incremented by the index of the extract.
7279      // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7280      Lane += V1.getConstantOperandVal(1);
7281      V1 = V1.getOperand(0);
7282    } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7283      // The lane is decremented if we are splatting from the 2nd operand.
7284      // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7285      unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7286      Lane -= Idx * VT.getVectorNumElements() / 2;
7287      V1 = WidenVector(V1.getOperand(Idx), DAG);
7288    } else if (VT.getSizeInBits() == 64) {
7289      // Widen the operand to 128-bit register with undef.
7290      V1 = WidenVector(V1, DAG);
7291    }
7292    return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7293  }
7294
7295  if (isREVMask(ShuffleMask, VT, 64))
7296    return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7297  if (isREVMask(ShuffleMask, VT, 32))
7298    return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7299  if (isREVMask(ShuffleMask, VT, 16))
7300    return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7301
7302  bool ReverseEXT = false;
7303  unsigned Imm;
7304  if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7305    if (ReverseEXT)
7306      std::swap(V1, V2);
7307    Imm *= getExtFactor(V1);
7308    return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7309                       DAG.getConstant(Imm, dl, MVT::i32));
7310  } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7311    Imm *= getExtFactor(V1);
7312    return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7313                       DAG.getConstant(Imm, dl, MVT::i32));
7314  }
7315
7316  unsigned WhichResult;
7317  if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7318    unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7319    return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7320  }
7321  if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7322    unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7323    return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7324  }
7325  if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7326    unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7327    return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7328  }
7329
7330  if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7331    unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7332    return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7333  }
7334  if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7335    unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7336    return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7337  }
7338  if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7339    unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7340    return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7341  }
7342
7343  if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7344    return Concat;
7345
7346  bool DstIsLeft;
7347  int Anomaly;
7348  int NumInputElements = V1.getValueType().getVectorNumElements();
7349  if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7350    SDValue DstVec = DstIsLeft ? V1 : V2;
7351    SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7352
7353    SDValue SrcVec = V1;
7354    int SrcLane = ShuffleMask[Anomaly];
7355    if (SrcLane >= NumInputElements) {
7356      SrcVec = V2;
7357      SrcLane -= VT.getVectorNumElements();
7358    }
7359    SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7360
7361    EVT ScalarVT = VT.getVectorElementType();
7362
7363    if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7364      ScalarVT = MVT::i32;
7365
7366    return DAG.getNode(
7367        ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7368        DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7369        DstLaneV);
7370  }
7371
7372  // If the shuffle is not directly supported and it has 4 elements, use
7373  // the PerfectShuffle-generated table to synthesize it from other shuffles.
7374  unsigned NumElts = VT.getVectorNumElements();
7375  if (NumElts == 4) {
7376    unsigned PFIndexes[4];
7377    for (unsigned i = 0; i != 4; ++i) {
7378      if (ShuffleMask[i] < 0)
7379        PFIndexes[i] = 8;
7380      else
7381        PFIndexes[i] = ShuffleMask[i];
7382    }
7383
7384    // Compute the index in the perfect shuffle table.
7385    unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7386                            PFIndexes[2] * 9 + PFIndexes[3];
7387    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7388    unsigned Cost = (PFEntry >> 30);
7389
7390    if (Cost <= 4)
7391      return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7392  }
7393
7394  return GenerateTBL(Op, ShuffleMask, DAG);
7395}
7396
7397SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7398                                                 SelectionDAG &DAG) const {
7399  SDLoc dl(Op);
7400  EVT VT = Op.getValueType();
7401  EVT ElemVT = VT.getScalarType();
7402
7403  SDValue SplatVal = Op.getOperand(0);
7404
7405  // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7406  // FPRs don't have this restriction.
7407  switch (ElemVT.getSimpleVT().SimpleTy) {
7408  case MVT::i8:
7409  case MVT::i16:
7410  case MVT::i32:
7411    SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7412    return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7413  case MVT::i64:
7414    SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7415    return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7416  case MVT::i1: {
7417    // The general case of i1.  There isn't any natural way to do this,
7418    // so we use some trickery with whilelo.
7419    // TODO: Add special cases for splat of constant true/false.
7420    SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7421    SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7422                           DAG.getValueType(MVT::i1));
7423    SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7424                                       MVT::i64);
7425    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7426                       DAG.getConstant(0, dl, MVT::i64), SplatVal);
7427  }
7428  // TODO: we can support float types, but haven't added patterns yet.
7429  case MVT::f16:
7430  case MVT::f32:
7431  case MVT::f64:
7432  default:
7433    report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7434  }
7435}
7436
7437static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7438                               APInt &UndefBits) {
7439  EVT VT = BVN->getValueType(0);
7440  APInt SplatBits, SplatUndef;
7441  unsigned SplatBitSize;
7442  bool HasAnyUndefs;
7443  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7444    unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7445
7446    for (unsigned i = 0; i < NumSplats; ++i) {
7447      CnstBits <<= SplatBitSize;
7448      UndefBits <<= SplatBitSize;
7449      CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7450      UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7451    }
7452
7453    return true;
7454  }
7455
7456  return false;
7457}
7458
7459// Try 64-bit splatted SIMD immediate.
7460static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7461                                 const APInt &Bits) {
7462  if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7463    uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7464    EVT VT = Op.getValueType();
7465    MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7466
7467    if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7468      Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7469
7470      SDLoc dl(Op);
7471      SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7472                                DAG.getConstant(Value, dl, MVT::i32));
7473      return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7474    }
7475  }
7476
7477  return SDValue();
7478}
7479
7480// Try 32-bit splatted SIMD immediate.
7481static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7482                                  const APInt &Bits,
7483                                  const SDValue *LHS = nullptr) {
7484  if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7485    uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7486    EVT VT = Op.getValueType();
7487    MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7488    bool isAdvSIMDModImm = false;
7489    uint64_t Shift;
7490
7491    if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7492      Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7493      Shift = 0;
7494    }
7495    else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7496      Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7497      Shift = 8;
7498    }
7499    else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7500      Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7501      Shift = 16;
7502    }
7503    else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7504      Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7505      Shift = 24;
7506    }
7507
7508    if (isAdvSIMDModImm) {
7509      SDLoc dl(Op);
7510      SDValue Mov;
7511
7512      if (LHS)
7513        Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7514                          DAG.getConstant(Value, dl, MVT::i32),
7515                          DAG.getConstant(Shift, dl, MVT::i32));
7516      else
7517        Mov = DAG.getNode(NewOp, dl, MovTy,
7518                          DAG.getConstant(Value, dl, MVT::i32),
7519                          DAG.getConstant(Shift, dl, MVT::i32));
7520
7521      return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7522    }
7523  }
7524
7525  return SDValue();
7526}
7527
7528// Try 16-bit splatted SIMD immediate.
7529static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7530                                  const APInt &Bits,
7531                                  const SDValue *LHS = nullptr) {
7532  if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7533    uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7534    EVT VT = Op.getValueType();
7535    MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7536    bool isAdvSIMDModImm = false;
7537    uint64_t Shift;
7538
7539    if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7540      Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7541      Shift = 0;
7542    }
7543    else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7544      Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7545      Shift = 8;
7546    }
7547
7548    if (isAdvSIMDModImm) {
7549      SDLoc dl(Op);
7550      SDValue Mov;
7551
7552      if (LHS)
7553        Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7554                          DAG.getConstant(Value, dl, MVT::i32),
7555                          DAG.getConstant(Shift, dl, MVT::i32));
7556      else
7557        Mov = DAG.getNode(NewOp, dl, MovTy,
7558                          DAG.getConstant(Value, dl, MVT::i32),
7559                          DAG.getConstant(Shift, dl, MVT::i32));
7560
7561      return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7562    }
7563  }
7564
7565  return SDValue();
7566}
7567
7568// Try 32-bit splatted SIMD immediate with shifted ones.
7569static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7570                                    SelectionDAG &DAG, const APInt &Bits) {
7571  if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7572    uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7573    EVT VT = Op.getValueType();
7574    MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7575    bool isAdvSIMDModImm = false;
7576    uint64_t Shift;
7577
7578    if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7579      Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7580      Shift = 264;
7581    }
7582    else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7583      Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7584      Shift = 272;
7585    }
7586
7587    if (isAdvSIMDModImm) {
7588      SDLoc dl(Op);
7589      SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7590                                DAG.getConstant(Value, dl, MVT::i32),
7591                                DAG.getConstant(Shift, dl, MVT::i32));
7592      return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7593    }
7594  }
7595
7596  return SDValue();
7597}
7598
7599// Try 8-bit splatted SIMD immediate.
7600static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7601                                 const APInt &Bits) {
7602  if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7603    uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7604    EVT VT = Op.getValueType();
7605    MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7606
7607    if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7608      Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7609
7610      SDLoc dl(Op);
7611      SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7612                                DAG.getConstant(Value, dl, MVT::i32));
7613      return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7614    }
7615  }
7616
7617  return SDValue();
7618}
7619
7620// Try FP splatted SIMD immediate.
7621static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7622                                  const APInt &Bits) {
7623  if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7624    uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7625    EVT VT = Op.getValueType();
7626    bool isWide = (VT.getSizeInBits() == 128);
7627    MVT MovTy;
7628    bool isAdvSIMDModImm = false;
7629
7630    if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7631      Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7632      MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7633    }
7634    else if (isWide &&
7635             (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7636      Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7637      MovTy = MVT::v2f64;
7638    }
7639
7640    if (isAdvSIMDModImm) {
7641      SDLoc dl(Op);
7642      SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7643                                DAG.getConstant(Value, dl, MVT::i32));
7644      return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7645    }
7646  }
7647
7648  return SDValue();
7649}
7650
7651// Specialized code to quickly find if PotentialBVec is a BuildVector that
7652// consists of only the same constant int value, returned in reference arg
7653// ConstVal
7654static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7655                                     uint64_t &ConstVal) {
7656  BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7657  if (!Bvec)
7658    return false;
7659  ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7660  if (!FirstElt)
7661    return false;
7662  EVT VT = Bvec->getValueType(0);
7663  unsigned NumElts = VT.getVectorNumElements();
7664  for (unsigned i = 1; i < NumElts; ++i)
7665    if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7666      return false;
7667  ConstVal = FirstElt->getZExtValue();
7668  return true;
7669}
7670
7671static unsigned getIntrinsicID(const SDNode *N) {
7672  unsigned Opcode = N->getOpcode();
7673  switch (Opcode) {
7674  default:
7675    return Intrinsic::not_intrinsic;
7676  case ISD::INTRINSIC_WO_CHAIN: {
7677    unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7678    if (IID < Intrinsic::num_intrinsics)
7679      return IID;
7680    return Intrinsic::not_intrinsic;
7681  }
7682  }
7683}
7684
7685// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7686// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7687// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7688// Also, logical shift right -> sri, with the same structure.
7689static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7690  EVT VT = N->getValueType(0);
7691
7692  if (!VT.isVector())
7693    return SDValue();
7694
7695  SDLoc DL(N);
7696
7697  // Is the first op an AND?
7698  const SDValue And = N->getOperand(0);
7699  if (And.getOpcode() != ISD::AND)
7700    return SDValue();
7701
7702  // Is the second op an shl or lshr?
7703  SDValue Shift = N->getOperand(1);
7704  // This will have been turned into: AArch64ISD::VSHL vector, #shift
7705  // or AArch64ISD::VLSHR vector, #shift
7706  unsigned ShiftOpc = Shift.getOpcode();
7707  if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7708    return SDValue();
7709  bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7710
7711  // Is the shift amount constant?
7712  ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7713  if (!C2node)
7714    return SDValue();
7715
7716  // Is the and mask vector all constant?
7717  uint64_t C1;
7718  if (!isAllConstantBuildVector(And.getOperand(1), C1))
7719    return SDValue();
7720
7721  // Is C1 == ~C2, taking into account how much one can shift elements of a
7722  // particular size?
7723  uint64_t C2 = C2node->getZExtValue();
7724  unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7725  if (C2 > ElemSizeInBits)
7726    return SDValue();
7727  unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7728  if ((C1 & ElemMask) != (~C2 & ElemMask))
7729    return SDValue();
7730
7731  SDValue X = And.getOperand(0);
7732  SDValue Y = Shift.getOperand(0);
7733
7734  unsigned Intrin =
7735      IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7736  SDValue ResultSLI =
7737      DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7738                  DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7739                  Shift.getOperand(1));
7740
7741  LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7742  LLVM_DEBUG(N->dump(&DAG));
7743  LLVM_DEBUG(dbgs() << "into: \n");
7744  LLVM_DEBUG(ResultSLI->dump(&DAG));
7745
7746  ++NumShiftInserts;
7747  return ResultSLI;
7748}
7749
7750SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7751                                             SelectionDAG &DAG) const {
7752  // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7753  if (EnableAArch64SlrGeneration) {
7754    if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7755      return Res;
7756  }
7757
7758  EVT VT = Op.getValueType();
7759
7760  SDValue LHS = Op.getOperand(0);
7761  BuildVectorSDNode *BVN =
7762      dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7763  if (!BVN) {
7764    // OR commutes, so try swapping the operands.
7765    LHS = Op.getOperand(1);
7766    BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7767  }
7768  if (!BVN)
7769    return Op;
7770
7771  APInt DefBits(VT.getSizeInBits(), 0);
7772  APInt UndefBits(VT.getSizeInBits(), 0);
7773  if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7774    SDValue NewOp;
7775
7776    if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7777                                    DefBits, &LHS)) ||
7778        (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7779                                    DefBits, &LHS)))
7780      return NewOp;
7781
7782    if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7783                                    UndefBits, &LHS)) ||
7784        (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7785                                    UndefBits, &LHS)))
7786      return NewOp;
7787  }
7788
7789  // We can always fall back to a non-immediate OR.
7790  return Op;
7791}
7792
7793// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7794// be truncated to fit element width.
7795static SDValue NormalizeBuildVector(SDValue Op,
7796                                    SelectionDAG &DAG) {
7797  assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7798  SDLoc dl(Op);
7799  EVT VT = Op.getValueType();
7800  EVT EltTy= VT.getVectorElementType();
7801
7802  if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7803    return Op;
7804
7805  SmallVector<SDValue, 16> Ops;
7806  for (SDValue Lane : Op->ops()) {
7807    // For integer vectors, type legalization would have promoted the
7808    // operands already. Otherwise, if Op is a floating-point splat
7809    // (with operands cast to integers), then the only possibilities
7810    // are constants and UNDEFs.
7811    if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7812      APInt LowBits(EltTy.getSizeInBits(),
7813                    CstLane->getZExtValue());
7814      Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7815    } else if (Lane.getNode()->isUndef()) {
7816      Lane = DAG.getUNDEF(MVT::i32);
7817    } else {
7818      assert(Lane.getValueType() == MVT::i32 &&
7819             "Unexpected BUILD_VECTOR operand type");
7820    }
7821    Ops.push_back(Lane);
7822  }
7823  return DAG.getBuildVector(VT, dl, Ops);
7824}
7825
7826static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7827  EVT VT = Op.getValueType();
7828
7829  APInt DefBits(VT.getSizeInBits(), 0);
7830  APInt UndefBits(VT.getSizeInBits(), 0);
7831  BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7832  if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7833    SDValue NewOp;
7834    if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7835        (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7836        (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7837        (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7838        (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7839        (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7840      return NewOp;
7841
7842    DefBits = ~DefBits;
7843    if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7844        (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7845        (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7846      return NewOp;
7847
7848    DefBits = UndefBits;
7849    if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7850        (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7851        (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7852        (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7853        (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7854        (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7855      return NewOp;
7856
7857    DefBits = ~UndefBits;
7858    if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7859        (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7860        (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7861      return NewOp;
7862  }
7863
7864  return SDValue();
7865}
7866
7867SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7868                                                 SelectionDAG &DAG) const {
7869  EVT VT = Op.getValueType();
7870
7871  // Try to build a simple constant vector.
7872  Op = NormalizeBuildVector(Op, DAG);
7873  if (VT.isInteger()) {
7874    // Certain vector constants, used to express things like logical NOT and
7875    // arithmetic NEG, are passed through unmodified.  This allows special
7876    // patterns for these operations to match, which will lower these constants
7877    // to whatever is proven necessary.
7878    BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7879    if (BVN->isConstant())
7880      if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7881        unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7882        APInt Val(BitSize,
7883                  Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7884        if (Val.isNullValue() || Val.isAllOnesValue())
7885          return Op;
7886      }
7887  }
7888
7889  if (SDValue V = ConstantBuildVector(Op, DAG))
7890    return V;
7891
7892  // Scan through the operands to find some interesting properties we can
7893  // exploit:
7894  //   1) If only one value is used, we can use a DUP, or
7895  //   2) if only the low element is not undef, we can just insert that, or
7896  //   3) if only one constant value is used (w/ some non-constant lanes),
7897  //      we can splat the constant value into the whole vector then fill
7898  //      in the non-constant lanes.
7899  //   4) FIXME: If different constant values are used, but we can intelligently
7900  //             select the values we'll be overwriting for the non-constant
7901  //             lanes such that we can directly materialize the vector
7902  //             some other way (MOVI, e.g.), we can be sneaky.
7903  //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7904  SDLoc dl(Op);
7905  unsigned NumElts = VT.getVectorNumElements();
7906  bool isOnlyLowElement = true;
7907  bool usesOnlyOneValue = true;
7908  bool usesOnlyOneConstantValue = true;
7909  bool isConstant = true;
7910  bool AllLanesExtractElt = true;
7911  unsigned NumConstantLanes = 0;
7912  SDValue Value;
7913  SDValue ConstantValue;
7914  for (unsigned i = 0; i < NumElts; ++i) {
7915    SDValue V = Op.getOperand(i);
7916    if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7917      AllLanesExtractElt = false;
7918    if (V.isUndef())
7919      continue;
7920    if (i > 0)
7921      isOnlyLowElement = false;
7922    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7923      isConstant = false;
7924
7925    if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7926      ++NumConstantLanes;
7927      if (!ConstantValue.getNode())
7928        ConstantValue = V;
7929      else if (ConstantValue != V)
7930        usesOnlyOneConstantValue = false;
7931    }
7932
7933    if (!Value.getNode())
7934      Value = V;
7935    else if (V != Value)
7936      usesOnlyOneValue = false;
7937  }
7938
7939  if (!Value.getNode()) {
7940    LLVM_DEBUG(
7941        dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7942    return DAG.getUNDEF(VT);
7943  }
7944
7945  // Convert BUILD_VECTOR where all elements but the lowest are undef into
7946  // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7947  // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7948  if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7949    LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7950                         "SCALAR_TO_VECTOR node\n");
7951    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7952  }
7953
7954  if (AllLanesExtractElt) {
7955    SDNode *Vector = nullptr;
7956    bool Even = false;
7957    bool Odd = false;
7958    // Check whether the extract elements match the Even pattern <0,2,4,...> or
7959    // the Odd pattern <1,3,5,...>.
7960    for (unsigned i = 0; i < NumElts; ++i) {
7961      SDValue V = Op.getOperand(i);
7962      const SDNode *N = V.getNode();
7963      if (!isa<ConstantSDNode>(N->getOperand(1)))
7964        break;
7965      SDValue N0 = N->getOperand(0);
7966
7967      // All elements are extracted from the same vector.
7968      if (!Vector) {
7969        Vector = N0.getNode();
7970        // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7971        // BUILD_VECTOR.
7972        if (VT.getVectorElementType() !=
7973            N0.getValueType().getVectorElementType())
7974          break;
7975      } else if (Vector != N0.getNode()) {
7976        Odd = false;
7977        Even = false;
7978        break;
7979      }
7980
7981      // Extracted values are either at Even indices <0,2,4,...> or at Odd
7982      // indices <1,3,5,...>.
7983      uint64_t Val = N->getConstantOperandVal(1);
7984      if (Val == 2 * i) {
7985        Even = true;
7986        continue;
7987      }
7988      if (Val - 1 == 2 * i) {
7989        Odd = true;
7990        continue;
7991      }
7992
7993      // Something does not match: abort.
7994      Odd = false;
7995      Even = false;
7996      break;
7997    }
7998    if (Even || Odd) {
7999      SDValue LHS =
8000          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8001                      DAG.getConstant(0, dl, MVT::i64));
8002      SDValue RHS =
8003          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8004                      DAG.getConstant(NumElts, dl, MVT::i64));
8005
8006      if (Even && !Odd)
8007        return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8008                           RHS);
8009      if (Odd && !Even)
8010        return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8011                           RHS);
8012    }
8013  }
8014
8015  // Use DUP for non-constant splats. For f32 constant splats, reduce to
8016  // i32 and try again.
8017  if (usesOnlyOneValue) {
8018    if (!isConstant) {
8019      if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8020          Value.getValueType() != VT) {
8021        LLVM_DEBUG(
8022            dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8023        return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8024      }
8025
8026      // This is actually a DUPLANExx operation, which keeps everything vectory.
8027
8028      SDValue Lane = Value.getOperand(1);
8029      Value = Value.getOperand(0);
8030      if (Value.getValueSizeInBits() == 64) {
8031        LLVM_DEBUG(
8032            dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8033                      "widening it\n");
8034        Value = WidenVector(Value, DAG);
8035      }
8036
8037      unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8038      return DAG.getNode(Opcode, dl, VT, Value, Lane);
8039    }
8040
8041    if (VT.getVectorElementType().isFloatingPoint()) {
8042      SmallVector<SDValue, 8> Ops;
8043      EVT EltTy = VT.getVectorElementType();
8044      assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
8045              "Unsupported floating-point vector type");
8046      LLVM_DEBUG(
8047          dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8048                    "BITCASTS, and try again\n");
8049      MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8050      for (unsigned i = 0; i < NumElts; ++i)
8051        Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8052      EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8053      SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8054      LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8055                 Val.dump(););
8056      Val = LowerBUILD_VECTOR(Val, DAG);
8057      if (Val.getNode())
8058        return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8059    }
8060  }
8061
8062  // If there was only one constant value used and for more than one lane,
8063  // start by splatting that value, then replace the non-constant lanes. This
8064  // is better than the default, which will perform a separate initialization
8065  // for each lane.
8066  if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8067    // Firstly, try to materialize the splat constant.
8068    SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8069            Val = ConstantBuildVector(Vec, DAG);
8070    if (!Val) {
8071      // Otherwise, materialize the constant and splat it.
8072      Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8073      DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8074    }
8075
8076    // Now insert the non-constant lanes.
8077    for (unsigned i = 0; i < NumElts; ++i) {
8078      SDValue V = Op.getOperand(i);
8079      SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8080      if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8081        // Note that type legalization likely mucked about with the VT of the
8082        // source operand, so we may have to convert it here before inserting.
8083        Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8084    }
8085    return Val;
8086  }
8087
8088  // This will generate a load from the constant pool.
8089  if (isConstant) {
8090    LLVM_DEBUG(
8091        dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8092                  "expansion\n");
8093    return SDValue();
8094  }
8095
8096  // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8097  if (NumElts >= 4) {
8098    if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8099      return shuffle;
8100  }
8101
8102  // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8103  // know the default expansion would otherwise fall back on something even
8104  // worse. For a vector with one or two non-undef values, that's
8105  // scalar_to_vector for the elements followed by a shuffle (provided the
8106  // shuffle is valid for the target) and materialization element by element
8107  // on the stack followed by a load for everything else.
8108  if (!isConstant && !usesOnlyOneValue) {
8109    LLVM_DEBUG(
8110        dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8111                  "of INSERT_VECTOR_ELT\n");
8112
8113    SDValue Vec = DAG.getUNDEF(VT);
8114    SDValue Op0 = Op.getOperand(0);
8115    unsigned i = 0;
8116
8117    // Use SCALAR_TO_VECTOR for lane zero to
8118    // a) Avoid a RMW dependency on the full vector register, and
8119    // b) Allow the register coalescer to fold away the copy if the
8120    //    value is already in an S or D register, and we're forced to emit an
8121    //    INSERT_SUBREG that we can't fold anywhere.
8122    //
8123    // We also allow types like i8 and i16 which are illegal scalar but legal
8124    // vector element types. After type-legalization the inserted value is
8125    // extended (i32) and it is safe to cast them to the vector type by ignoring
8126    // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8127    if (!Op0.isUndef()) {
8128      LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8129      Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8130      ++i;
8131    }
8132    LLVM_DEBUG(if (i < NumElts) dbgs()
8133                   << "Creating nodes for the other vector elements:\n";);
8134    for (; i < NumElts; ++i) {
8135      SDValue V = Op.getOperand(i);
8136      if (V.isUndef())
8137        continue;
8138      SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8139      Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8140    }
8141    return Vec;
8142  }
8143
8144  LLVM_DEBUG(
8145      dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8146                "better alternative\n");
8147  return SDValue();
8148}
8149
8150SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8151                                                      SelectionDAG &DAG) const {
8152  assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8153
8154  // Check for non-constant or out of range lane.
8155  EVT VT = Op.getOperand(0).getValueType();
8156  ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8157  if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8158    return SDValue();
8159
8160
8161  // Insertion/extraction are legal for V128 types.
8162  if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8163      VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8164      VT == MVT::v8f16)
8165    return Op;
8166
8167  if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8168      VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8169    return SDValue();
8170
8171  // For V64 types, we perform insertion by expanding the value
8172  // to a V128 type and perform the insertion on that.
8173  SDLoc DL(Op);
8174  SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8175  EVT WideTy = WideVec.getValueType();
8176
8177  SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8178                             Op.getOperand(1), Op.getOperand(2));
8179  // Re-narrow the resultant vector.
8180  return NarrowVector(Node, DAG);
8181}
8182
8183SDValue
8184AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8185                                               SelectionDAG &DAG) const {
8186  assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8187
8188  // Check for non-constant or out of range lane.
8189  EVT VT = Op.getOperand(0).getValueType();
8190  ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8191  if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8192    return SDValue();
8193
8194
8195  // Insertion/extraction are legal for V128 types.
8196  if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8197      VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8198      VT == MVT::v8f16)
8199    return Op;
8200
8201  if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8202      VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8203    return SDValue();
8204
8205  // For V64 types, we perform extraction by expanding the value
8206  // to a V128 type and perform the extraction on that.
8207  SDLoc DL(Op);
8208  SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8209  EVT WideTy = WideVec.getValueType();
8210
8211  EVT ExtrTy = WideTy.getVectorElementType();
8212  if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8213    ExtrTy = MVT::i32;
8214
8215  // For extractions, we just return the result directly.
8216  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8217                     Op.getOperand(1));
8218}
8219
8220SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8221                                                      SelectionDAG &DAG) const {
8222  EVT VT = Op.getOperand(0).getValueType();
8223  SDLoc dl(Op);
8224  // Just in case...
8225  if (!VT.isVector())
8226    return SDValue();
8227
8228  ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8229  if (!Cst)
8230    return SDValue();
8231  unsigned Val = Cst->getZExtValue();
8232
8233  unsigned Size = Op.getValueSizeInBits();
8234
8235  // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8236  if (Val == 0)
8237    return Op;
8238
8239  // If this is extracting the upper 64-bits of a 128-bit vector, we match
8240  // that directly.
8241  if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
8242    return Op;
8243
8244  return SDValue();
8245}
8246
8247bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8248  if (VT.getVectorNumElements() == 4 &&
8249      (VT.is128BitVector() || VT.is64BitVector())) {
8250    unsigned PFIndexes[4];
8251    for (unsigned i = 0; i != 4; ++i) {
8252      if (M[i] < 0)
8253        PFIndexes[i] = 8;
8254      else
8255        PFIndexes[i] = M[i];
8256    }
8257
8258    // Compute the index in the perfect shuffle table.
8259    unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8260                            PFIndexes[2] * 9 + PFIndexes[3];
8261    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8262    unsigned Cost = (PFEntry >> 30);
8263
8264    if (Cost <= 4)
8265      return true;
8266  }
8267
8268  bool DummyBool;
8269  int DummyInt;
8270  unsigned DummyUnsigned;
8271
8272  return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8273          isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8274          isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8275          // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8276          isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8277          isZIPMask(M, VT, DummyUnsigned) ||
8278          isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8279          isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8280          isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8281          isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8282          isConcatMask(M, VT, VT.getSizeInBits() == 128));
8283}
8284
8285/// getVShiftImm - Check if this is a valid build_vector for the immediate
8286/// operand of a vector shift operation, where all the elements of the
8287/// build_vector must have the same constant integer value.
8288static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8289  // Ignore bit_converts.
8290  while (Op.getOpcode() == ISD::BITCAST)
8291    Op = Op.getOperand(0);
8292  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8293  APInt SplatBits, SplatUndef;
8294  unsigned SplatBitSize;
8295  bool HasAnyUndefs;
8296  if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8297                                    HasAnyUndefs, ElementBits) ||
8298      SplatBitSize > ElementBits)
8299    return false;
8300  Cnt = SplatBits.getSExtValue();
8301  return true;
8302}
8303
8304/// isVShiftLImm - Check if this is a valid build_vector for the immediate
8305/// operand of a vector shift left operation.  That value must be in the range:
8306///   0 <= Value < ElementBits for a left shift; or
8307///   0 <= Value <= ElementBits for a long left shift.
8308static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8309  assert(VT.isVector() && "vector shift count is not a vector type");
8310  int64_t ElementBits = VT.getScalarSizeInBits();
8311  if (!getVShiftImm(Op, ElementBits, Cnt))
8312    return false;
8313  return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8314}
8315
8316/// isVShiftRImm - Check if this is a valid build_vector for the immediate
8317/// operand of a vector shift right operation. The value must be in the range:
8318///   1 <= Value <= ElementBits for a right shift; or
8319static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8320  assert(VT.isVector() && "vector shift count is not a vector type");
8321  int64_t ElementBits = VT.getScalarSizeInBits();
8322  if (!getVShiftImm(Op, ElementBits, Cnt))
8323    return false;
8324  return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8325}
8326
8327SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8328                                                      SelectionDAG &DAG) const {
8329  EVT VT = Op.getValueType();
8330  SDLoc DL(Op);
8331  int64_t Cnt;
8332
8333  if (!Op.getOperand(1).getValueType().isVector())
8334    return Op;
8335  unsigned EltSize = VT.getScalarSizeInBits();
8336
8337  switch (Op.getOpcode()) {
8338  default:
8339    llvm_unreachable("unexpected shift opcode");
8340
8341  case ISD::SHL:
8342    if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8343      return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8344                         DAG.getConstant(Cnt, DL, MVT::i32));
8345    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8346                       DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8347                                       MVT::i32),
8348                       Op.getOperand(0), Op.getOperand(1));
8349  case ISD::SRA:
8350  case ISD::SRL:
8351    // Right shift immediate
8352    if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8353      unsigned Opc =
8354          (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8355      return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8356                         DAG.getConstant(Cnt, DL, MVT::i32));
8357    }
8358
8359    // Right shift register.  Note, there is not a shift right register
8360    // instruction, but the shift left register instruction takes a signed
8361    // value, where negative numbers specify a right shift.
8362    unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8363                                                : Intrinsic::aarch64_neon_ushl;
8364    // negate the shift amount
8365    SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8366    SDValue NegShiftLeft =
8367        DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8368                    DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8369                    NegShift);
8370    return NegShiftLeft;
8371  }
8372
8373  return SDValue();
8374}
8375
8376static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8377                                    AArch64CC::CondCode CC, bool NoNans, EVT VT,
8378                                    const SDLoc &dl, SelectionDAG &DAG) {
8379  EVT SrcVT = LHS.getValueType();
8380  assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8381         "function only supposed to emit natural comparisons");
8382
8383  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8384  APInt CnstBits(VT.getSizeInBits(), 0);
8385  APInt UndefBits(VT.getSizeInBits(), 0);
8386  bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8387  bool IsZero = IsCnst && (CnstBits == 0);
8388
8389  if (SrcVT.getVectorElementType().isFloatingPoint()) {
8390    switch (CC) {
8391    default:
8392      return SDValue();
8393    case AArch64CC::NE: {
8394      SDValue Fcmeq;
8395      if (IsZero)
8396        Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8397      else
8398        Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8399      return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8400    }
8401    case AArch64CC::EQ:
8402      if (IsZero)
8403        return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8404      return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8405    case AArch64CC::GE:
8406      if (IsZero)
8407        return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8408      return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8409    case AArch64CC::GT:
8410      if (IsZero)
8411        return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8412      return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8413    case AArch64CC::LS:
8414      if (IsZero)
8415        return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8416      return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8417    case AArch64CC::LT:
8418      if (!NoNans)
8419        return SDValue();
8420      // If we ignore NaNs then we can use to the MI implementation.
8421      LLVM_FALLTHROUGH;
8422    case AArch64CC::MI:
8423      if (IsZero)
8424        return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8425      return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8426    }
8427  }
8428
8429  switch (CC) {
8430  default:
8431    return SDValue();
8432  case AArch64CC::NE: {
8433    SDValue Cmeq;
8434    if (IsZero)
8435      Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8436    else
8437      Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8438    return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8439  }
8440  case AArch64CC::EQ:
8441    if (IsZero)
8442      return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8443    return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8444  case AArch64CC::GE:
8445    if (IsZero)
8446      return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8447    return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8448  case AArch64CC::GT:
8449    if (IsZero)
8450      return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8451    return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8452  case AArch64CC::LE:
8453    if (IsZero)
8454      return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8455    return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8456  case AArch64CC::LS:
8457    return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8458  case AArch64CC::LO:
8459    return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8460  case AArch64CC::LT:
8461    if (IsZero)
8462      return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8463    return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8464  case AArch64CC::HI:
8465    return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8466  case AArch64CC::HS:
8467    return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8468  }
8469}
8470
8471SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8472                                           SelectionDAG &DAG) const {
8473  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8474  SDValue LHS = Op.getOperand(0);
8475  SDValue RHS = Op.getOperand(1);
8476  EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8477  SDLoc dl(Op);
8478
8479  if (LHS.getValueType().getVectorElementType().isInteger()) {
8480    assert(LHS.getValueType() == RHS.getValueType());
8481    AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8482    SDValue Cmp =
8483        EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8484    return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8485  }
8486
8487  const bool FullFP16 =
8488    static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8489
8490  // Make v4f16 (only) fcmp operations utilise vector instructions
8491  // v8f16 support will be a litle more complicated
8492  if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8493    if (LHS.getValueType().getVectorNumElements() == 4) {
8494      LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8495      RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8496      SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8497      DAG.ReplaceAllUsesWith(Op, NewSetcc);
8498      CmpVT = MVT::v4i32;
8499    } else
8500      return SDValue();
8501  }
8502
8503  assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8504          LHS.getValueType().getVectorElementType() != MVT::f128);
8505
8506  // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8507  // clean.  Some of them require two branches to implement.
8508  AArch64CC::CondCode CC1, CC2;
8509  bool ShouldInvert;
8510  changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8511
8512  bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8513  SDValue Cmp =
8514      EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8515  if (!Cmp.getNode())
8516    return SDValue();
8517
8518  if (CC2 != AArch64CC::AL) {
8519    SDValue Cmp2 =
8520        EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8521    if (!Cmp2.getNode())
8522      return SDValue();
8523
8524    Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8525  }
8526
8527  Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8528
8529  if (ShouldInvert)
8530    Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8531
8532  return Cmp;
8533}
8534
8535static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8536                                  SelectionDAG &DAG) {
8537  SDValue VecOp = ScalarOp.getOperand(0);
8538  auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8539  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8540                     DAG.getConstant(0, DL, MVT::i64));
8541}
8542
8543SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8544                                              SelectionDAG &DAG) const {
8545  SDLoc dl(Op);
8546  switch (Op.getOpcode()) {
8547  case ISD::VECREDUCE_ADD:
8548    return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8549  case ISD::VECREDUCE_SMAX:
8550    return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8551  case ISD::VECREDUCE_SMIN:
8552    return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8553  case ISD::VECREDUCE_UMAX:
8554    return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8555  case ISD::VECREDUCE_UMIN:
8556    return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8557  case ISD::VECREDUCE_FMAX: {
8558    assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8559    return DAG.getNode(
8560        ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8561        DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8562        Op.getOperand(0));
8563  }
8564  case ISD::VECREDUCE_FMIN: {
8565    assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8566    return DAG.getNode(
8567        ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8568        DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8569        Op.getOperand(0));
8570  }
8571  default:
8572    llvm_unreachable("Unhandled reduction");
8573  }
8574}
8575
8576SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8577                                                    SelectionDAG &DAG) const {
8578  auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8579  if (!Subtarget.hasLSE())
8580    return SDValue();
8581
8582  // LSE has an atomic load-add instruction, but not a load-sub.
8583  SDLoc dl(Op);
8584  MVT VT = Op.getSimpleValueType();
8585  SDValue RHS = Op.getOperand(2);
8586  AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8587  RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8588  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8589                       Op.getOperand(0), Op.getOperand(1), RHS,
8590                       AN->getMemOperand());
8591}
8592
8593SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8594                                                    SelectionDAG &DAG) const {
8595  auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8596  if (!Subtarget.hasLSE())
8597    return SDValue();
8598
8599  // LSE has an atomic load-clear instruction, but not a load-and.
8600  SDLoc dl(Op);
8601  MVT VT = Op.getSimpleValueType();
8602  SDValue RHS = Op.getOperand(2);
8603  AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8604  RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8605  return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8606                       Op.getOperand(0), Op.getOperand(1), RHS,
8607                       AN->getMemOperand());
8608}
8609
8610SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8611    SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8612  SDLoc dl(Op);
8613  EVT PtrVT = getPointerTy(DAG.getDataLayout());
8614  SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8615
8616  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8617  const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8618  if (Subtarget->hasCustomCallingConv())
8619    TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8620
8621  Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8622                     DAG.getConstant(4, dl, MVT::i64));
8623  Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8624  Chain =
8625      DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8626                  Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8627                  DAG.getRegisterMask(Mask), Chain.getValue(1));
8628  // To match the actual intent better, we should read the output from X15 here
8629  // again (instead of potentially spilling it to the stack), but rereading Size
8630  // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8631  // here.
8632
8633  Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8634                     DAG.getConstant(4, dl, MVT::i64));
8635  return Chain;
8636}
8637
8638SDValue
8639AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8640                                               SelectionDAG &DAG) const {
8641  assert(Subtarget->isTargetWindows() &&
8642         "Only Windows alloca probing supported");
8643  SDLoc dl(Op);
8644  // Get the inputs.
8645  SDNode *Node = Op.getNode();
8646  SDValue Chain = Op.getOperand(0);
8647  SDValue Size = Op.getOperand(1);
8648  unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8649  EVT VT = Node->getValueType(0);
8650
8651  if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8652          "no-stack-arg-probe")) {
8653    SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8654    Chain = SP.getValue(1);
8655    SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8656    if (Align)
8657      SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8658                       DAG.getConstant(-(uint64_t)Align, dl, VT));
8659    Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8660    SDValue Ops[2] = {SP, Chain};
8661    return DAG.getMergeValues(Ops, dl);
8662  }
8663
8664  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8665
8666  Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8667
8668  SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8669  Chain = SP.getValue(1);
8670  SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8671  if (Align)
8672    SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8673                     DAG.getConstant(-(uint64_t)Align, dl, VT));
8674  Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8675
8676  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8677                             DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8678
8679  SDValue Ops[2] = {SP, Chain};
8680  return DAG.getMergeValues(Ops, dl);
8681}
8682
8683/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8684/// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8685/// specified in the intrinsic calls.
8686bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8687                                               const CallInst &I,
8688                                               MachineFunction &MF,
8689                                               unsigned Intrinsic) const {
8690  auto &DL = I.getModule()->getDataLayout();
8691  switch (Intrinsic) {
8692  case Intrinsic::aarch64_neon_ld2:
8693  case Intrinsic::aarch64_neon_ld3:
8694  case Intrinsic::aarch64_neon_ld4:
8695  case Intrinsic::aarch64_neon_ld1x2:
8696  case Intrinsic::aarch64_neon_ld1x3:
8697  case Intrinsic::aarch64_neon_ld1x4:
8698  case Intrinsic::aarch64_neon_ld2lane:
8699  case Intrinsic::aarch64_neon_ld3lane:
8700  case Intrinsic::aarch64_neon_ld4lane:
8701  case Intrinsic::aarch64_neon_ld2r:
8702  case Intrinsic::aarch64_neon_ld3r:
8703  case Intrinsic::aarch64_neon_ld4r: {
8704    Info.opc = ISD::INTRINSIC_W_CHAIN;
8705    // Conservatively set memVT to the entire set of vectors loaded.
8706    uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8707    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8708    Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8709    Info.offset = 0;
8710    Info.align.reset();
8711    // volatile loads with NEON intrinsics not supported
8712    Info.flags = MachineMemOperand::MOLoad;
8713    return true;
8714  }
8715  case Intrinsic::aarch64_neon_st2:
8716  case Intrinsic::aarch64_neon_st3:
8717  case Intrinsic::aarch64_neon_st4:
8718  case Intrinsic::aarch64_neon_st1x2:
8719  case Intrinsic::aarch64_neon_st1x3:
8720  case Intrinsic::aarch64_neon_st1x4:
8721  case Intrinsic::aarch64_neon_st2lane:
8722  case Intrinsic::aarch64_neon_st3lane:
8723  case Intrinsic::aarch64_neon_st4lane: {
8724    Info.opc = ISD::INTRINSIC_VOID;
8725    // Conservatively set memVT to the entire set of vectors stored.
8726    unsigned NumElts = 0;
8727    for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8728      Type *ArgTy = I.getArgOperand(ArgI)->getType();
8729      if (!ArgTy->isVectorTy())
8730        break;
8731      NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8732    }
8733    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8734    Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8735    Info.offset = 0;
8736    Info.align.reset();
8737    // volatile stores with NEON intrinsics not supported
8738    Info.flags = MachineMemOperand::MOStore;
8739    return true;
8740  }
8741  case Intrinsic::aarch64_ldaxr:
8742  case Intrinsic::aarch64_ldxr: {
8743    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8744    Info.opc = ISD::INTRINSIC_W_CHAIN;
8745    Info.memVT = MVT::getVT(PtrTy->getElementType());
8746    Info.ptrVal = I.getArgOperand(0);
8747    Info.offset = 0;
8748    Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8749    Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8750    return true;
8751  }
8752  case Intrinsic::aarch64_stlxr:
8753  case Intrinsic::aarch64_stxr: {
8754    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8755    Info.opc = ISD::INTRINSIC_W_CHAIN;
8756    Info.memVT = MVT::getVT(PtrTy->getElementType());
8757    Info.ptrVal = I.getArgOperand(1);
8758    Info.offset = 0;
8759    Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8760    Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8761    return true;
8762  }
8763  case Intrinsic::aarch64_ldaxp:
8764  case Intrinsic::aarch64_ldxp:
8765    Info.opc = ISD::INTRINSIC_W_CHAIN;
8766    Info.memVT = MVT::i128;
8767    Info.ptrVal = I.getArgOperand(0);
8768    Info.offset = 0;
8769    Info.align = Align(16);
8770    Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8771    return true;
8772  case Intrinsic::aarch64_stlxp:
8773  case Intrinsic::aarch64_stxp:
8774    Info.opc = ISD::INTRINSIC_W_CHAIN;
8775    Info.memVT = MVT::i128;
8776    Info.ptrVal = I.getArgOperand(2);
8777    Info.offset = 0;
8778    Info.align = Align(16);
8779    Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8780    return true;
8781  case Intrinsic::aarch64_sve_ldnt1: {
8782    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8783    Info.opc = ISD::INTRINSIC_W_CHAIN;
8784    Info.memVT = MVT::getVT(PtrTy->getElementType());
8785    Info.ptrVal = I.getArgOperand(1);
8786    Info.offset = 0;
8787    Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8788    Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
8789    return true;
8790  }
8791  case Intrinsic::aarch64_sve_stnt1: {
8792    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
8793    Info.opc = ISD::INTRINSIC_W_CHAIN;
8794    Info.memVT = MVT::getVT(PtrTy->getElementType());
8795    Info.ptrVal = I.getArgOperand(2);
8796    Info.offset = 0;
8797    Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8798    Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
8799    return true;
8800  }
8801  default:
8802    break;
8803  }
8804
8805  return false;
8806}
8807
8808bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8809                                                  ISD::LoadExtType ExtTy,
8810                                                  EVT NewVT) const {
8811  // TODO: This may be worth removing. Check regression tests for diffs.
8812  if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8813    return false;
8814
8815  // If we're reducing the load width in order to avoid having to use an extra
8816  // instruction to do extension then it's probably a good idea.
8817  if (ExtTy != ISD::NON_EXTLOAD)
8818    return true;
8819  // Don't reduce load width if it would prevent us from combining a shift into
8820  // the offset.
8821  MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8822  assert(Mem);
8823  const SDValue &Base = Mem->getBasePtr();
8824  if (Base.getOpcode() == ISD::ADD &&
8825      Base.getOperand(1).getOpcode() == ISD::SHL &&
8826      Base.getOperand(1).hasOneUse() &&
8827      Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8828    // The shift can be combined if it matches the size of the value being
8829    // loaded (and so reducing the width would make it not match).
8830    uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8831    uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8832    if (ShiftAmount == Log2_32(LoadBytes))
8833      return false;
8834  }
8835  // We have no reason to disallow reducing the load width, so allow it.
8836  return true;
8837}
8838
8839// Truncations from 64-bit GPR to 32-bit GPR is free.
8840bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8841  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8842    return false;
8843  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8844  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8845  return NumBits1 > NumBits2;
8846}
8847bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8848  if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8849    return false;
8850  unsigned NumBits1 = VT1.getSizeInBits();
8851  unsigned NumBits2 = VT2.getSizeInBits();
8852  return NumBits1 > NumBits2;
8853}
8854
8855/// Check if it is profitable to hoist instruction in then/else to if.
8856/// Not profitable if I and it's user can form a FMA instruction
8857/// because we prefer FMSUB/FMADD.
8858bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8859  if (I->getOpcode() != Instruction::FMul)
8860    return true;
8861
8862  if (!I->hasOneUse())
8863    return true;
8864
8865  Instruction *User = I->user_back();
8866
8867  if (User &&
8868      !(User->getOpcode() == Instruction::FSub ||
8869        User->getOpcode() == Instruction::FAdd))
8870    return true;
8871
8872  const TargetOptions &Options = getTargetMachine().Options;
8873  const Function *F = I->getFunction();
8874  const DataLayout &DL = F->getParent()->getDataLayout();
8875  Type *Ty = User->getOperand(0)->getType();
8876
8877  return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
8878           isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
8879           (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8880            Options.UnsafeFPMath));
8881}
8882
8883// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8884// 64-bit GPR.
8885bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8886  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8887    return false;
8888  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8889  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8890  return NumBits1 == 32 && NumBits2 == 64;
8891}
8892bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8893  if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8894    return false;
8895  unsigned NumBits1 = VT1.getSizeInBits();
8896  unsigned NumBits2 = VT2.getSizeInBits();
8897  return NumBits1 == 32 && NumBits2 == 64;
8898}
8899
8900bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8901  EVT VT1 = Val.getValueType();
8902  if (isZExtFree(VT1, VT2)) {
8903    return true;
8904  }
8905
8906  if (Val.getOpcode() != ISD::LOAD)
8907    return false;
8908
8909  // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8910  return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8911          VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8912          VT1.getSizeInBits() <= 32);
8913}
8914
8915bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8916  if (isa<FPExtInst>(Ext))
8917    return false;
8918
8919  // Vector types are not free.
8920  if (Ext->getType()->isVectorTy())
8921    return false;
8922
8923  for (const Use &U : Ext->uses()) {
8924    // The extension is free if we can fold it with a left shift in an
8925    // addressing mode or an arithmetic operation: add, sub, and cmp.
8926
8927    // Is there a shift?
8928    const Instruction *Instr = cast<Instruction>(U.getUser());
8929
8930    // Is this a constant shift?
8931    switch (Instr->getOpcode()) {
8932    case Instruction::Shl:
8933      if (!isa<ConstantInt>(Instr->getOperand(1)))
8934        return false;
8935      break;
8936    case Instruction::GetElementPtr: {
8937      gep_type_iterator GTI = gep_type_begin(Instr);
8938      auto &DL = Ext->getModule()->getDataLayout();
8939      std::advance(GTI, U.getOperandNo()-1);
8940      Type *IdxTy = GTI.getIndexedType();
8941      // This extension will end up with a shift because of the scaling factor.
8942      // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8943      // Get the shift amount based on the scaling factor:
8944      // log2(sizeof(IdxTy)) - log2(8).
8945      uint64_t ShiftAmt =
8946        countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
8947      // Is the constant foldable in the shift of the addressing mode?
8948      // I.e., shift amount is between 1 and 4 inclusive.
8949      if (ShiftAmt == 0 || ShiftAmt > 4)
8950        return false;
8951      break;
8952    }
8953    case Instruction::Trunc:
8954      // Check if this is a noop.
8955      // trunc(sext ty1 to ty2) to ty1.
8956      if (Instr->getType() == Ext->getOperand(0)->getType())
8957        continue;
8958      LLVM_FALLTHROUGH;
8959    default:
8960      return false;
8961    }
8962
8963    // At this point we can use the bfm family, so this extension is free
8964    // for that use.
8965  }
8966  return true;
8967}
8968
8969/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8970/// or upper half of the vector elements.
8971static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8972  auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8973    auto *FullVT = cast<VectorType>(FullV->getType());
8974    auto *HalfVT = cast<VectorType>(HalfV->getType());
8975    return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8976  };
8977
8978  auto extractHalf = [](Value *FullV, Value *HalfV) {
8979    auto *FullVT = cast<VectorType>(FullV->getType());
8980    auto *HalfVT = cast<VectorType>(HalfV->getType());
8981    return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8982  };
8983
8984  Constant *M1, *M2;
8985  Value *S1Op1, *S2Op1;
8986  if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8987      !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8988    return false;
8989
8990  // Check that the operands are half as wide as the result and we extract
8991  // half of the elements of the input vectors.
8992  if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8993      !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8994    return false;
8995
8996  // Check the mask extracts either the lower or upper half of vector
8997  // elements.
8998  int M1Start = -1;
8999  int M2Start = -1;
9000  int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
9001  if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9002      !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9003      M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9004    return false;
9005
9006  return true;
9007}
9008
9009/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9010/// of the vector elements.
9011static bool areExtractExts(Value *Ext1, Value *Ext2) {
9012  auto areExtDoubled = [](Instruction *Ext) {
9013    return Ext->getType()->getScalarSizeInBits() ==
9014           2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9015  };
9016
9017  if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9018      !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9019      !areExtDoubled(cast<Instruction>(Ext1)) ||
9020      !areExtDoubled(cast<Instruction>(Ext2)))
9021    return false;
9022
9023  return true;
9024}
9025
9026/// Check if sinking \p I's operands to I's basic block is profitable, because
9027/// the operands can be folded into a target instruction, e.g.
9028/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9029bool AArch64TargetLowering::shouldSinkOperands(
9030    Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9031  if (!I->getType()->isVectorTy())
9032    return false;
9033
9034  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9035    switch (II->getIntrinsicID()) {
9036    case Intrinsic::aarch64_neon_umull:
9037      if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9038        return false;
9039      Ops.push_back(&II->getOperandUse(0));
9040      Ops.push_back(&II->getOperandUse(1));
9041      return true;
9042    default:
9043      return false;
9044    }
9045  }
9046
9047  switch (I->getOpcode()) {
9048  case Instruction::Sub:
9049  case Instruction::Add: {
9050    if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9051      return false;
9052
9053    // If the exts' operands extract either the lower or upper elements, we
9054    // can sink them too.
9055    auto Ext1 = cast<Instruction>(I->getOperand(0));
9056    auto Ext2 = cast<Instruction>(I->getOperand(1));
9057    if (areExtractShuffleVectors(Ext1, Ext2)) {
9058      Ops.push_back(&Ext1->getOperandUse(0));
9059      Ops.push_back(&Ext2->getOperandUse(0));
9060    }
9061
9062    Ops.push_back(&I->getOperandUse(0));
9063    Ops.push_back(&I->getOperandUse(1));
9064
9065    return true;
9066  }
9067  default:
9068    return false;
9069  }
9070  return false;
9071}
9072
9073bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9074                                          unsigned &RequiredAligment) const {
9075  if (!LoadedType.isSimple() ||
9076      (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9077    return false;
9078  // Cyclone supports unaligned accesses.
9079  RequiredAligment = 0;
9080  unsigned NumBits = LoadedType.getSizeInBits();
9081  return NumBits == 32 || NumBits == 64;
9082}
9083
9084/// A helper function for determining the number of interleaved accesses we
9085/// will generate when lowering accesses of the given type.
9086unsigned
9087AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9088                                                 const DataLayout &DL) const {
9089  return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9090}
9091
9092MachineMemOperand::Flags
9093AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
9094  if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9095      I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9096    return MOStridedAccess;
9097  return MachineMemOperand::MONone;
9098}
9099
9100bool AArch64TargetLowering::isLegalInterleavedAccessType(
9101    VectorType *VecTy, const DataLayout &DL) const {
9102
9103  unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9104  unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9105
9106  // Ensure the number of vector elements is greater than 1.
9107  if (VecTy->getNumElements() < 2)
9108    return false;
9109
9110  // Ensure the element type is legal.
9111  if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9112    return false;
9113
9114  // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9115  // 128 will be split into multiple interleaved accesses.
9116  return VecSize == 64 || VecSize % 128 == 0;
9117}
9118
9119/// Lower an interleaved load into a ldN intrinsic.
9120///
9121/// E.g. Lower an interleaved load (Factor = 2):
9122///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9123///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9124///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9125///
9126///      Into:
9127///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9128///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9129///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9130bool AArch64TargetLowering::lowerInterleavedLoad(
9131    LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9132    ArrayRef<unsigned> Indices, unsigned Factor) const {
9133  assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9134         "Invalid interleave factor");
9135  assert(!Shuffles.empty() && "Empty shufflevector input");
9136  assert(Shuffles.size() == Indices.size() &&
9137         "Unmatched number of shufflevectors and indices");
9138
9139  const DataLayout &DL = LI->getModule()->getDataLayout();
9140
9141  VectorType *VecTy = Shuffles[0]->getType();
9142
9143  // Skip if we do not have NEON and skip illegal vector types. We can
9144  // "legalize" wide vector types into multiple interleaved accesses as long as
9145  // the vector types are divisible by 128.
9146  if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
9147    return false;
9148
9149  unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
9150
9151  // A pointer vector can not be the return type of the ldN intrinsics. Need to
9152  // load integer vectors first and then convert to pointer vectors.
9153  Type *EltTy = VecTy->getVectorElementType();
9154  if (EltTy->isPointerTy())
9155    VecTy =
9156        VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
9157
9158  IRBuilder<> Builder(LI);
9159
9160  // The base address of the load.
9161  Value *BaseAddr = LI->getPointerOperand();
9162
9163  if (NumLoads > 1) {
9164    // If we're going to generate more than one load, reset the sub-vector type
9165    // to something legal.
9166    VecTy = VectorType::get(VecTy->getVectorElementType(),
9167                            VecTy->getVectorNumElements() / NumLoads);
9168
9169    // We will compute the pointer operand of each load from the original base
9170    // address using GEPs. Cast the base address to a pointer to the scalar
9171    // element type.
9172    BaseAddr = Builder.CreateBitCast(
9173        BaseAddr, VecTy->getVectorElementType()->getPointerTo(
9174                      LI->getPointerAddressSpace()));
9175  }
9176
9177  Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
9178  Type *Tys[2] = {VecTy, PtrTy};
9179  static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9180                                            Intrinsic::aarch64_neon_ld3,
9181                                            Intrinsic::aarch64_neon_ld4};
9182  Function *LdNFunc =
9183      Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9184
9185  // Holds sub-vectors extracted from the load intrinsic return values. The
9186  // sub-vectors are associated with the shufflevector instructions they will
9187  // replace.
9188  DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9189
9190  for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9191
9192    // If we're generating more than one load, compute the base address of
9193    // subsequent loads as an offset from the previous.
9194    if (LoadCount > 0)
9195      BaseAddr =
9196          Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
9197                                     VecTy->getVectorNumElements() * Factor);
9198
9199    CallInst *LdN = Builder.CreateCall(
9200        LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9201
9202    // Extract and store the sub-vectors returned by the load intrinsic.
9203    for (unsigned i = 0; i < Shuffles.size(); i++) {
9204      ShuffleVectorInst *SVI = Shuffles[i];
9205      unsigned Index = Indices[i];
9206
9207      Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9208
9209      // Convert the integer vector to pointer vector if the element is pointer.
9210      if (EltTy->isPointerTy())
9211        SubVec = Builder.CreateIntToPtr(
9212            SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
9213                                    VecTy->getVectorNumElements()));
9214      SubVecs[SVI].push_back(SubVec);
9215    }
9216  }
9217
9218  // Replace uses of the shufflevector instructions with the sub-vectors
9219  // returned by the load intrinsic. If a shufflevector instruction is
9220  // associated with more than one sub-vector, those sub-vectors will be
9221  // concatenated into a single wide vector.
9222  for (ShuffleVectorInst *SVI : Shuffles) {
9223    auto &SubVec = SubVecs[SVI];
9224    auto *WideVec =
9225        SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9226    SVI->replaceAllUsesWith(WideVec);
9227  }
9228
9229  return true;
9230}
9231
9232/// Lower an interleaved store into a stN intrinsic.
9233///
9234/// E.g. Lower an interleaved store (Factor = 3):
9235///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9236///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9237///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9238///
9239///      Into:
9240///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9241///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9242///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9243///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9244///
9245/// Note that the new shufflevectors will be removed and we'll only generate one
9246/// st3 instruction in CodeGen.
9247///
9248/// Example for a more general valid mask (Factor 3). Lower:
9249///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9250///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9251///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9252///
9253///      Into:
9254///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9255///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9256///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9257///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9258bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9259                                                  ShuffleVectorInst *SVI,
9260                                                  unsigned Factor) const {
9261  assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9262         "Invalid interleave factor");
9263
9264  VectorType *VecTy = SVI->getType();
9265  assert(VecTy->getVectorNumElements() % Factor == 0 &&
9266         "Invalid interleaved store");
9267
9268  unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
9269  Type *EltTy = VecTy->getVectorElementType();
9270  VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
9271
9272  const DataLayout &DL = SI->getModule()->getDataLayout();
9273
9274  // Skip if we do not have NEON and skip illegal vector types. We can
9275  // "legalize" wide vector types into multiple interleaved accesses as long as
9276  // the vector types are divisible by 128.
9277  if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9278    return false;
9279
9280  unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9281
9282  Value *Op0 = SVI->getOperand(0);
9283  Value *Op1 = SVI->getOperand(1);
9284  IRBuilder<> Builder(SI);
9285
9286  // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9287  // vectors to integer vectors.
9288  if (EltTy->isPointerTy()) {
9289    Type *IntTy = DL.getIntPtrType(EltTy);
9290    unsigned NumOpElts = Op0->getType()->getVectorNumElements();
9291
9292    // Convert to the corresponding integer vector.
9293    Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
9294    Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9295    Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9296
9297    SubVecTy = VectorType::get(IntTy, LaneLen);
9298  }
9299
9300  // The base address of the store.
9301  Value *BaseAddr = SI->getPointerOperand();
9302
9303  if (NumStores > 1) {
9304    // If we're going to generate more than one store, reset the lane length
9305    // and sub-vector type to something legal.
9306    LaneLen /= NumStores;
9307    SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
9308
9309    // We will compute the pointer operand of each store from the original base
9310    // address using GEPs. Cast the base address to a pointer to the scalar
9311    // element type.
9312    BaseAddr = Builder.CreateBitCast(
9313        BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
9314                      SI->getPointerAddressSpace()));
9315  }
9316
9317  auto Mask = SVI->getShuffleMask();
9318
9319  Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
9320  Type *Tys[2] = {SubVecTy, PtrTy};
9321  static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
9322                                             Intrinsic::aarch64_neon_st3,
9323                                             Intrinsic::aarch64_neon_st4};
9324  Function *StNFunc =
9325      Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
9326
9327  for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9328
9329    SmallVector<Value *, 5> Ops;
9330
9331    // Split the shufflevector operands into sub vectors for the new stN call.
9332    for (unsigned i = 0; i < Factor; i++) {
9333      unsigned IdxI = StoreCount * LaneLen * Factor + i;
9334      if (Mask[IdxI] >= 0) {
9335        Ops.push_back(Builder.CreateShuffleVector(
9336            Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9337      } else {
9338        unsigned StartMask = 0;
9339        for (unsigned j = 1; j < LaneLen; j++) {
9340          unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9341          if (Mask[IdxJ * Factor + IdxI] >= 0) {
9342            StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9343            break;
9344          }
9345        }
9346        // Note: Filling undef gaps with random elements is ok, since
9347        // those elements were being written anyway (with undefs).
9348        // In the case of all undefs we're defaulting to using elems from 0
9349        // Note: StartMask cannot be negative, it's checked in
9350        // isReInterleaveMask
9351        Ops.push_back(Builder.CreateShuffleVector(
9352            Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9353      }
9354    }
9355
9356    // If we generating more than one store, we compute the base address of
9357    // subsequent stores as an offset from the previous.
9358    if (StoreCount > 0)
9359      BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
9360                                            BaseAddr, LaneLen * Factor);
9361
9362    Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9363    Builder.CreateCall(StNFunc, Ops);
9364  }
9365  return true;
9366}
9367
9368static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9369                       unsigned AlignCheck) {
9370  return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9371          (DstAlign == 0 || DstAlign % AlignCheck == 0));
9372}
9373
9374EVT AArch64TargetLowering::getOptimalMemOpType(
9375    uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9376    bool ZeroMemset, bool MemcpyStrSrc,
9377    const AttributeList &FuncAttributes) const {
9378  bool CanImplicitFloat =
9379      !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9380  bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9381  bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9382  // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9383  // taken one instruction to materialize the v2i64 zero and one store (with
9384  // restrictive addressing mode). Just do i64 stores.
9385  bool IsSmallMemset = IsMemset && Size < 32;
9386  auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9387    if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9388      return true;
9389    bool Fast;
9390    return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9391                                          &Fast) &&
9392           Fast;
9393  };
9394
9395  if (CanUseNEON && IsMemset && !IsSmallMemset &&
9396      AlignmentIsAcceptable(MVT::v2i64, 16))
9397    return MVT::v2i64;
9398  if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9399    return MVT::f128;
9400  if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9401    return MVT::i64;
9402  if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9403    return MVT::i32;
9404  return MVT::Other;
9405}
9406
9407LLT AArch64TargetLowering::getOptimalMemOpLLT(
9408    uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9409    bool ZeroMemset, bool MemcpyStrSrc,
9410    const AttributeList &FuncAttributes) const {
9411  bool CanImplicitFloat =
9412      !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9413  bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9414  bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9415  // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9416  // taken one instruction to materialize the v2i64 zero and one store (with
9417  // restrictive addressing mode). Just do i64 stores.
9418  bool IsSmallMemset = IsMemset && Size < 32;
9419  auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9420    if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9421      return true;
9422    bool Fast;
9423    return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9424                                          &Fast) &&
9425           Fast;
9426  };
9427
9428  if (CanUseNEON && IsMemset && !IsSmallMemset &&
9429      AlignmentIsAcceptable(MVT::v2i64, 16))
9430    return LLT::vector(2, 64);
9431  if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9432    return LLT::scalar(128);
9433  if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9434    return LLT::scalar(64);
9435  if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9436    return LLT::scalar(32);
9437  return LLT();
9438}
9439
9440// 12-bit optionally shifted immediates are legal for adds.
9441bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9442  if (Immed == std::numeric_limits<int64_t>::min()) {
9443    LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9444                      << ": avoid UB for INT64_MIN\n");
9445    return false;
9446  }
9447  // Same encoding for add/sub, just flip the sign.
9448  Immed = std::abs(Immed);
9449  bool IsLegal = ((Immed >> 12) == 0 ||
9450                  ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9451  LLVM_DEBUG(dbgs() << "Is " << Immed
9452                    << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9453  return IsLegal;
9454}
9455
9456// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9457// immediates is the same as for an add or a sub.
9458bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9459  return isLegalAddImmediate(Immed);
9460}
9461
9462/// isLegalAddressingMode - Return true if the addressing mode represented
9463/// by AM is legal for this target, for a load/store of the specified type.
9464bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9465                                                  const AddrMode &AM, Type *Ty,
9466                                                  unsigned AS, Instruction *I) const {
9467  // AArch64 has five basic addressing modes:
9468  //  reg
9469  //  reg + 9-bit signed offset
9470  //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
9471  //  reg1 + reg2
9472  //  reg + SIZE_IN_BYTES * reg
9473
9474  // No global is ever allowed as a base.
9475  if (AM.BaseGV)
9476    return false;
9477
9478  // No reg+reg+imm addressing.
9479  if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9480    return false;
9481
9482  // check reg + imm case:
9483  // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9484  uint64_t NumBytes = 0;
9485  if (Ty->isSized()) {
9486    uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9487    NumBytes = NumBits / 8;
9488    if (!isPowerOf2_64(NumBits))
9489      NumBytes = 0;
9490  }
9491
9492  if (!AM.Scale) {
9493    int64_t Offset = AM.BaseOffs;
9494
9495    // 9-bit signed offset
9496    if (isInt<9>(Offset))
9497      return true;
9498
9499    // 12-bit unsigned offset
9500    unsigned shift = Log2_64(NumBytes);
9501    if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9502        // Must be a multiple of NumBytes (NumBytes is a power of 2)
9503        (Offset >> shift) << shift == Offset)
9504      return true;
9505    return false;
9506  }
9507
9508  // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9509
9510  return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9511}
9512
9513bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9514  // Consider splitting large offset of struct or array.
9515  return true;
9516}
9517
9518int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9519                                                const AddrMode &AM, Type *Ty,
9520                                                unsigned AS) const {
9521  // Scaling factors are not free at all.
9522  // Operands                     | Rt Latency
9523  // -------------------------------------------
9524  // Rt, [Xn, Xm]                 | 4
9525  // -------------------------------------------
9526  // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
9527  // Rt, [Xn, Wm, <extend> #imm]  |
9528  if (isLegalAddressingMode(DL, AM, Ty, AS))
9529    // Scale represents reg2 * scale, thus account for 1 if
9530    // it is not equal to 0 or 1.
9531    return AM.Scale != 0 && AM.Scale != 1;
9532  return -1;
9533}
9534
9535bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
9536    const MachineFunction &MF, EVT VT) const {
9537  VT = VT.getScalarType();
9538
9539  if (!VT.isSimple())
9540    return false;
9541
9542  switch (VT.getSimpleVT().SimpleTy) {
9543  case MVT::f32:
9544  case MVT::f64:
9545    return true;
9546  default:
9547    break;
9548  }
9549
9550  return false;
9551}
9552
9553bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
9554                                                       Type *Ty) const {
9555  switch (Ty->getScalarType()->getTypeID()) {
9556  case Type::FloatTyID:
9557  case Type::DoubleTyID:
9558    return true;
9559  default:
9560    return false;
9561  }
9562}
9563
9564const MCPhysReg *
9565AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9566  // LR is a callee-save register, but we must treat it as clobbered by any call
9567  // site. Hence we include LR in the scratch registers, which are in turn added
9568  // as implicit-defs for stackmaps and patchpoints.
9569  static const MCPhysReg ScratchRegs[] = {
9570    AArch64::X16, AArch64::X17, AArch64::LR, 0
9571  };
9572  return ScratchRegs;
9573}
9574
9575bool
9576AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9577                                                     CombineLevel Level) const {
9578  N = N->getOperand(0).getNode();
9579  EVT VT = N->getValueType(0);
9580    // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9581    // it with shift to let it be lowered to UBFX.
9582  if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9583      isa<ConstantSDNode>(N->getOperand(1))) {
9584    uint64_t TruncMask = N->getConstantOperandVal(1);
9585    if (isMask_64(TruncMask) &&
9586      N->getOperand(0).getOpcode() == ISD::SRL &&
9587      isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9588      return false;
9589  }
9590  return true;
9591}
9592
9593bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9594                                                              Type *Ty) const {
9595  assert(Ty->isIntegerTy());
9596
9597  unsigned BitSize = Ty->getPrimitiveSizeInBits();
9598  if (BitSize == 0)
9599    return false;
9600
9601  int64_t Val = Imm.getSExtValue();
9602  if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9603    return true;
9604
9605  if ((int64_t)Val < 0)
9606    Val = ~Val;
9607  if (BitSize == 32)
9608    Val &= (1LL << 32) - 1;
9609
9610  unsigned LZ = countLeadingZeros((uint64_t)Val);
9611  unsigned Shift = (63 - LZ) / 16;
9612  // MOVZ is free so return true for one or fewer MOVK.
9613  return Shift < 3;
9614}
9615
9616bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9617                                                    unsigned Index) const {
9618  if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9619    return false;
9620
9621  return (Index == 0 || Index == ResVT.getVectorNumElements());
9622}
9623
9624/// Turn vector tests of the signbit in the form of:
9625///   xor (sra X, elt_size(X)-1), -1
9626/// into:
9627///   cmge X, X, #0
9628static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9629                                         const AArch64Subtarget *Subtarget) {
9630  EVT VT = N->getValueType(0);
9631  if (!Subtarget->hasNEON() || !VT.isVector())
9632    return SDValue();
9633
9634  // There must be a shift right algebraic before the xor, and the xor must be a
9635  // 'not' operation.
9636  SDValue Shift = N->getOperand(0);
9637  SDValue Ones = N->getOperand(1);
9638  if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9639      !ISD::isBuildVectorAllOnes(Ones.getNode()))
9640    return SDValue();
9641
9642  // The shift should be smearing the sign bit across each vector element.
9643  auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9644  EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9645  if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9646    return SDValue();
9647
9648  return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9649}
9650
9651// Generate SUBS and CSEL for integer abs.
9652static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9653  EVT VT = N->getValueType(0);
9654
9655  SDValue N0 = N->getOperand(0);
9656  SDValue N1 = N->getOperand(1);
9657  SDLoc DL(N);
9658
9659  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9660  // and change it to SUB and CSEL.
9661  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9662      N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9663      N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9664    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9665      if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9666        SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9667                                  N0.getOperand(0));
9668        // Generate SUBS & CSEL.
9669        SDValue Cmp =
9670            DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9671                        N0.getOperand(0), DAG.getConstant(0, DL, VT));
9672        return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9673                           DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9674                           SDValue(Cmp.getNode(), 1));
9675      }
9676  return SDValue();
9677}
9678
9679static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9680                                 TargetLowering::DAGCombinerInfo &DCI,
9681                                 const AArch64Subtarget *Subtarget) {
9682  if (DCI.isBeforeLegalizeOps())
9683    return SDValue();
9684
9685  if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9686    return Cmp;
9687
9688  return performIntegerAbsCombine(N, DAG);
9689}
9690
9691SDValue
9692AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9693                                     SelectionDAG &DAG,
9694                                     SmallVectorImpl<SDNode *> &Created) const {
9695  AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9696  if (isIntDivCheap(N->getValueType(0), Attr))
9697    return SDValue(N,0); // Lower SDIV as SDIV
9698
9699  // fold (sdiv X, pow2)
9700  EVT VT = N->getValueType(0);
9701  if ((VT != MVT::i32 && VT != MVT::i64) ||
9702      !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9703    return SDValue();
9704
9705  SDLoc DL(N);
9706  SDValue N0 = N->getOperand(0);
9707  unsigned Lg2 = Divisor.countTrailingZeros();
9708  SDValue Zero = DAG.getConstant(0, DL, VT);
9709  SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9710
9711  // Add (N0 < 0) ? Pow2 - 1 : 0;
9712  SDValue CCVal;
9713  SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9714  SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9715  SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9716
9717  Created.push_back(Cmp.getNode());
9718  Created.push_back(Add.getNode());
9719  Created.push_back(CSel.getNode());
9720
9721  // Divide by pow2.
9722  SDValue SRA =
9723      DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9724
9725  // If we're dividing by a positive value, we're done.  Otherwise, we must
9726  // negate the result.
9727  if (Divisor.isNonNegative())
9728    return SRA;
9729
9730  Created.push_back(SRA.getNode());
9731  return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9732}
9733
9734static bool IsSVECntIntrinsic(SDValue S) {
9735  switch(getIntrinsicID(S.getNode())) {
9736  default:
9737    break;
9738  case Intrinsic::aarch64_sve_cntb:
9739  case Intrinsic::aarch64_sve_cnth:
9740  case Intrinsic::aarch64_sve_cntw:
9741  case Intrinsic::aarch64_sve_cntd:
9742    return true;
9743  }
9744  return false;
9745}
9746
9747static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9748                                 TargetLowering::DAGCombinerInfo &DCI,
9749                                 const AArch64Subtarget *Subtarget) {
9750  if (DCI.isBeforeLegalizeOps())
9751    return SDValue();
9752
9753  // The below optimizations require a constant RHS.
9754  if (!isa<ConstantSDNode>(N->getOperand(1)))
9755    return SDValue();
9756
9757  SDValue N0 = N->getOperand(0);
9758  ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9759  const APInt &ConstValue = C->getAPIntValue();
9760
9761  // Allow the scaling to be folded into the `cnt` instruction by preventing
9762  // the scaling to be obscured here. This makes it easier to pattern match.
9763  if (IsSVECntIntrinsic(N0) ||
9764     (N0->getOpcode() == ISD::TRUNCATE &&
9765      (IsSVECntIntrinsic(N0->getOperand(0)))))
9766       if (ConstValue.sge(1) && ConstValue.sle(16))
9767         return SDValue();
9768
9769  // Multiplication of a power of two plus/minus one can be done more
9770  // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9771  // future CPUs have a cheaper MADD instruction, this may need to be
9772  // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9773  // 64-bit is 5 cycles, so this is always a win.
9774  // More aggressively, some multiplications N0 * C can be lowered to
9775  // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9776  // e.g. 6=3*2=(2+1)*2.
9777  // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9778  // which equals to (1+2)*16-(1+2).
9779  // TrailingZeroes is used to test if the mul can be lowered to
9780  // shift+add+shift.
9781  unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9782  if (TrailingZeroes) {
9783    // Conservatively do not lower to shift+add+shift if the mul might be
9784    // folded into smul or umul.
9785    if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9786                            isZeroExtended(N0.getNode(), DAG)))
9787      return SDValue();
9788    // Conservatively do not lower to shift+add+shift if the mul might be
9789    // folded into madd or msub.
9790    if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9791                           N->use_begin()->getOpcode() == ISD::SUB))
9792      return SDValue();
9793  }
9794  // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9795  // and shift+add+shift.
9796  APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9797
9798  unsigned ShiftAmt, AddSubOpc;
9799  // Is the shifted value the LHS operand of the add/sub?
9800  bool ShiftValUseIsN0 = true;
9801  // Do we need to negate the result?
9802  bool NegateResult = false;
9803
9804  if (ConstValue.isNonNegative()) {
9805    // (mul x, 2^N + 1) => (add (shl x, N), x)
9806    // (mul x, 2^N - 1) => (sub (shl x, N), x)
9807    // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9808    APInt SCVMinus1 = ShiftedConstValue - 1;
9809    APInt CVPlus1 = ConstValue + 1;
9810    if (SCVMinus1.isPowerOf2()) {
9811      ShiftAmt = SCVMinus1.logBase2();
9812      AddSubOpc = ISD::ADD;
9813    } else if (CVPlus1.isPowerOf2()) {
9814      ShiftAmt = CVPlus1.logBase2();
9815      AddSubOpc = ISD::SUB;
9816    } else
9817      return SDValue();
9818  } else {
9819    // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9820    // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9821    APInt CVNegPlus1 = -ConstValue + 1;
9822    APInt CVNegMinus1 = -ConstValue - 1;
9823    if (CVNegPlus1.isPowerOf2()) {
9824      ShiftAmt = CVNegPlus1.logBase2();
9825      AddSubOpc = ISD::SUB;
9826      ShiftValUseIsN0 = false;
9827    } else if (CVNegMinus1.isPowerOf2()) {
9828      ShiftAmt = CVNegMinus1.logBase2();
9829      AddSubOpc = ISD::ADD;
9830      NegateResult = true;
9831    } else
9832      return SDValue();
9833  }
9834
9835  SDLoc DL(N);
9836  EVT VT = N->getValueType(0);
9837  SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9838                                   DAG.getConstant(ShiftAmt, DL, MVT::i64));
9839
9840  SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9841  SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9842  SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9843  assert(!(NegateResult && TrailingZeroes) &&
9844         "NegateResult and TrailingZeroes cannot both be true for now.");
9845  // Negate the result.
9846  if (NegateResult)
9847    return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9848  // Shift the result.
9849  if (TrailingZeroes)
9850    return DAG.getNode(ISD::SHL, DL, VT, Res,
9851                       DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9852  return Res;
9853}
9854
9855static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9856                                                         SelectionDAG &DAG) {
9857  // Take advantage of vector comparisons producing 0 or -1 in each lane to
9858  // optimize away operation when it's from a constant.
9859  //
9860  // The general transformation is:
9861  //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9862  //       AND(VECTOR_CMP(x,y), constant2)
9863  //    constant2 = UNARYOP(constant)
9864
9865  // Early exit if this isn't a vector operation, the operand of the
9866  // unary operation isn't a bitwise AND, or if the sizes of the operations
9867  // aren't the same.
9868  EVT VT = N->getValueType(0);
9869  if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9870      N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9871      VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9872    return SDValue();
9873
9874  // Now check that the other operand of the AND is a constant. We could
9875  // make the transformation for non-constant splats as well, but it's unclear
9876  // that would be a benefit as it would not eliminate any operations, just
9877  // perform one more step in scalar code before moving to the vector unit.
9878  if (BuildVectorSDNode *BV =
9879          dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9880    // Bail out if the vector isn't a constant.
9881    if (!BV->isConstant())
9882      return SDValue();
9883
9884    // Everything checks out. Build up the new and improved node.
9885    SDLoc DL(N);
9886    EVT IntVT = BV->getValueType(0);
9887    // Create a new constant of the appropriate type for the transformed
9888    // DAG.
9889    SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9890    // The AND node needs bitcasts to/from an integer vector type around it.
9891    SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9892    SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9893                                 N->getOperand(0)->getOperand(0), MaskConst);
9894    SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9895    return Res;
9896  }
9897
9898  return SDValue();
9899}
9900
9901static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9902                                     const AArch64Subtarget *Subtarget) {
9903  // First try to optimize away the conversion when it's conditionally from
9904  // a constant. Vectors only.
9905  if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9906    return Res;
9907
9908  EVT VT = N->getValueType(0);
9909  if (VT != MVT::f32 && VT != MVT::f64)
9910    return SDValue();
9911
9912  // Only optimize when the source and destination types have the same width.
9913  if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9914    return SDValue();
9915
9916  // If the result of an integer load is only used by an integer-to-float
9917  // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9918  // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9919  SDValue N0 = N->getOperand(0);
9920  if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9921      // Do not change the width of a volatile load.
9922      !cast<LoadSDNode>(N0)->isVolatile()) {
9923    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9924    SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9925                               LN0->getPointerInfo(), LN0->getAlignment(),
9926                               LN0->getMemOperand()->getFlags());
9927
9928    // Make sure successors of the original load stay after it by updating them
9929    // to use the new Chain.
9930    DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9931
9932    unsigned Opcode =
9933        (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9934    return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9935  }
9936
9937  return SDValue();
9938}
9939
9940/// Fold a floating-point multiply by power of two into floating-point to
9941/// fixed-point conversion.
9942static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9943                                     TargetLowering::DAGCombinerInfo &DCI,
9944                                     const AArch64Subtarget *Subtarget) {
9945  if (!Subtarget->hasNEON())
9946    return SDValue();
9947
9948  if (!N->getValueType(0).isSimple())
9949    return SDValue();
9950
9951  SDValue Op = N->getOperand(0);
9952  if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9953      Op.getOpcode() != ISD::FMUL)
9954    return SDValue();
9955
9956  SDValue ConstVec = Op->getOperand(1);
9957  if (!isa<BuildVectorSDNode>(ConstVec))
9958    return SDValue();
9959
9960  MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9961  uint32_t FloatBits = FloatTy.getSizeInBits();
9962  if (FloatBits != 32 && FloatBits != 64)
9963    return SDValue();
9964
9965  MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9966  uint32_t IntBits = IntTy.getSizeInBits();
9967  if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9968    return SDValue();
9969
9970  // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9971  if (IntBits > FloatBits)
9972    return SDValue();
9973
9974  BitVector UndefElements;
9975  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9976  int32_t Bits = IntBits == 64 ? 64 : 32;
9977  int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9978  if (C == -1 || C == 0 || C > Bits)
9979    return SDValue();
9980
9981  MVT ResTy;
9982  unsigned NumLanes = Op.getValueType().getVectorNumElements();
9983  switch (NumLanes) {
9984  default:
9985    return SDValue();
9986  case 2:
9987    ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9988    break;
9989  case 4:
9990    ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9991    break;
9992  }
9993
9994  if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9995    return SDValue();
9996
9997  assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9998         "Illegal vector type after legalization");
9999
10000  SDLoc DL(N);
10001  bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10002  unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10003                                      : Intrinsic::aarch64_neon_vcvtfp2fxu;
10004  SDValue FixConv =
10005      DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10006                  DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10007                  Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10008  // We can handle smaller integers by generating an extra trunc.
10009  if (IntBits < FloatBits)
10010    FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10011
10012  return FixConv;
10013}
10014
10015/// Fold a floating-point divide by power of two into fixed-point to
10016/// floating-point conversion.
10017static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10018                                  TargetLowering::DAGCombinerInfo &DCI,
10019                                  const AArch64Subtarget *Subtarget) {
10020  if (!Subtarget->hasNEON())
10021    return SDValue();
10022
10023  SDValue Op = N->getOperand(0);
10024  unsigned Opc = Op->getOpcode();
10025  if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10026      !Op.getOperand(0).getValueType().isSimple() ||
10027      (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10028    return SDValue();
10029
10030  SDValue ConstVec = N->getOperand(1);
10031  if (!isa<BuildVectorSDNode>(ConstVec))
10032    return SDValue();
10033
10034  MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10035  int32_t IntBits = IntTy.getSizeInBits();
10036  if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10037    return SDValue();
10038
10039  MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10040  int32_t FloatBits = FloatTy.getSizeInBits();
10041  if (FloatBits != 32 && FloatBits != 64)
10042    return SDValue();
10043
10044  // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10045  if (IntBits > FloatBits)
10046    return SDValue();
10047
10048  BitVector UndefElements;
10049  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10050  int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10051  if (C == -1 || C == 0 || C > FloatBits)
10052    return SDValue();
10053
10054  MVT ResTy;
10055  unsigned NumLanes = Op.getValueType().getVectorNumElements();
10056  switch (NumLanes) {
10057  default:
10058    return SDValue();
10059  case 2:
10060    ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10061    break;
10062  case 4:
10063    ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10064    break;
10065  }
10066
10067  if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10068    return SDValue();
10069
10070  SDLoc DL(N);
10071  SDValue ConvInput = Op.getOperand(0);
10072  bool IsSigned = Opc == ISD::SINT_TO_FP;
10073  if (IntBits < FloatBits)
10074    ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10075                            ResTy, ConvInput);
10076
10077  unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10078                                      : Intrinsic::aarch64_neon_vcvtfxu2fp;
10079  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10080                     DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10081                     DAG.getConstant(C, DL, MVT::i32));
10082}
10083
10084/// An EXTR instruction is made up of two shifts, ORed together. This helper
10085/// searches for and classifies those shifts.
10086static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10087                         bool &FromHi) {
10088  if (N.getOpcode() == ISD::SHL)
10089    FromHi = false;
10090  else if (N.getOpcode() == ISD::SRL)
10091    FromHi = true;
10092  else
10093    return false;
10094
10095  if (!isa<ConstantSDNode>(N.getOperand(1)))
10096    return false;
10097
10098  ShiftAmount = N->getConstantOperandVal(1);
10099  Src = N->getOperand(0);
10100  return true;
10101}
10102
10103/// EXTR instruction extracts a contiguous chunk of bits from two existing
10104/// registers viewed as a high/low pair. This function looks for the pattern:
10105/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10106/// with an EXTR. Can't quite be done in TableGen because the two immediates
10107/// aren't independent.
10108static SDValue tryCombineToEXTR(SDNode *N,
10109                                TargetLowering::DAGCombinerInfo &DCI) {
10110  SelectionDAG &DAG = DCI.DAG;
10111  SDLoc DL(N);
10112  EVT VT = N->getValueType(0);
10113
10114  assert(N->getOpcode() == ISD::OR && "Unexpected root");
10115
10116  if (VT != MVT::i32 && VT != MVT::i64)
10117    return SDValue();
10118
10119  SDValue LHS;
10120  uint32_t ShiftLHS = 0;
10121  bool LHSFromHi = false;
10122  if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10123    return SDValue();
10124
10125  SDValue RHS;
10126  uint32_t ShiftRHS = 0;
10127  bool RHSFromHi = false;
10128  if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10129    return SDValue();
10130
10131  // If they're both trying to come from the high part of the register, they're
10132  // not really an EXTR.
10133  if (LHSFromHi == RHSFromHi)
10134    return SDValue();
10135
10136  if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10137    return SDValue();
10138
10139  if (LHSFromHi) {
10140    std::swap(LHS, RHS);
10141    std::swap(ShiftLHS, ShiftRHS);
10142  }
10143
10144  return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10145                     DAG.getConstant(ShiftRHS, DL, MVT::i64));
10146}
10147
10148static SDValue tryCombineToBSL(SDNode *N,
10149                                TargetLowering::DAGCombinerInfo &DCI) {
10150  EVT VT = N->getValueType(0);
10151  SelectionDAG &DAG = DCI.DAG;
10152  SDLoc DL(N);
10153
10154  if (!VT.isVector())
10155    return SDValue();
10156
10157  SDValue N0 = N->getOperand(0);
10158  if (N0.getOpcode() != ISD::AND)
10159    return SDValue();
10160
10161  SDValue N1 = N->getOperand(1);
10162  if (N1.getOpcode() != ISD::AND)
10163    return SDValue();
10164
10165  // We only have to look for constant vectors here since the general, variable
10166  // case can be handled in TableGen.
10167  unsigned Bits = VT.getScalarSizeInBits();
10168  uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10169  for (int i = 1; i >= 0; --i)
10170    for (int j = 1; j >= 0; --j) {
10171      BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10172      BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10173      if (!BVN0 || !BVN1)
10174        continue;
10175
10176      bool FoundMatch = true;
10177      for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10178        ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10179        ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10180        if (!CN0 || !CN1 ||
10181            CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10182          FoundMatch = false;
10183          break;
10184        }
10185      }
10186
10187      if (FoundMatch)
10188        return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
10189                           N0->getOperand(1 - i), N1->getOperand(1 - j));
10190    }
10191
10192  return SDValue();
10193}
10194
10195static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10196                                const AArch64Subtarget *Subtarget) {
10197  // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10198  SelectionDAG &DAG = DCI.DAG;
10199  EVT VT = N->getValueType(0);
10200
10201  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10202    return SDValue();
10203
10204  if (SDValue Res = tryCombineToEXTR(N, DCI))
10205    return Res;
10206
10207  if (SDValue Res = tryCombineToBSL(N, DCI))
10208    return Res;
10209
10210  return SDValue();
10211}
10212
10213static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10214  if (!MemVT.getVectorElementType().isSimple())
10215    return false;
10216
10217  uint64_t MaskForTy = 0ull;
10218  switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10219  case MVT::i8:
10220    MaskForTy = 0xffull;
10221    break;
10222  case MVT::i16:
10223    MaskForTy = 0xffffull;
10224    break;
10225  case MVT::i32:
10226    MaskForTy = 0xffffffffull;
10227    break;
10228  default:
10229    return false;
10230    break;
10231  }
10232
10233  if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10234    if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10235      return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10236
10237  return false;
10238}
10239
10240static SDValue performSVEAndCombine(SDNode *N,
10241                                    TargetLowering::DAGCombinerInfo &DCI) {
10242  if (DCI.isBeforeLegalizeOps())
10243    return SDValue();
10244
10245  SDValue Src = N->getOperand(0);
10246  SDValue Mask = N->getOperand(1);
10247
10248  if (!Src.hasOneUse())
10249    return SDValue();
10250
10251  // GLD1* instructions perform an implicit zero-extend, which makes them
10252  // perfect candidates for combining.
10253  switch (Src->getOpcode()) {
10254  case AArch64ISD::GLD1:
10255  case AArch64ISD::GLD1_SCALED:
10256  case AArch64ISD::GLD1_SXTW:
10257  case AArch64ISD::GLD1_SXTW_SCALED:
10258  case AArch64ISD::GLD1_UXTW:
10259  case AArch64ISD::GLD1_UXTW_SCALED:
10260  case AArch64ISD::GLD1_IMM:
10261    break;
10262  default:
10263    return SDValue();
10264  }
10265
10266  EVT MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
10267
10268  if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
10269    return Src;
10270
10271  return SDValue();
10272}
10273
10274static SDValue performANDCombine(SDNode *N,
10275                                 TargetLowering::DAGCombinerInfo &DCI) {
10276  SelectionDAG &DAG = DCI.DAG;
10277  SDValue LHS = N->getOperand(0);
10278  EVT VT = N->getValueType(0);
10279  if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
10280    return SDValue();
10281
10282  if (VT.isScalableVector())
10283    return performSVEAndCombine(N, DCI);
10284
10285  BuildVectorSDNode *BVN =
10286      dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
10287  if (!BVN)
10288    return SDValue();
10289
10290  // AND does not accept an immediate, so check if we can use a BIC immediate
10291  // instruction instead. We do this here instead of using a (and x, (mvni imm))
10292  // pattern in isel, because some immediates may be lowered to the preferred
10293  // (and x, (movi imm)) form, even though an mvni representation also exists.
10294  APInt DefBits(VT.getSizeInBits(), 0);
10295  APInt UndefBits(VT.getSizeInBits(), 0);
10296  if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10297    SDValue NewOp;
10298
10299    DefBits = ~DefBits;
10300    if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10301                                    DefBits, &LHS)) ||
10302        (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10303                                    DefBits, &LHS)))
10304      return NewOp;
10305
10306    UndefBits = ~UndefBits;
10307    if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10308                                    UndefBits, &LHS)) ||
10309        (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10310                                    UndefBits, &LHS)))
10311      return NewOp;
10312  }
10313
10314  return SDValue();
10315}
10316
10317static SDValue performSRLCombine(SDNode *N,
10318                                 TargetLowering::DAGCombinerInfo &DCI) {
10319  SelectionDAG &DAG = DCI.DAG;
10320  EVT VT = N->getValueType(0);
10321  if (VT != MVT::i32 && VT != MVT::i64)
10322    return SDValue();
10323
10324  // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
10325  // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
10326  // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
10327  SDValue N0 = N->getOperand(0);
10328  if (N0.getOpcode() == ISD::BSWAP) {
10329    SDLoc DL(N);
10330    SDValue N1 = N->getOperand(1);
10331    SDValue N00 = N0.getOperand(0);
10332    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10333      uint64_t ShiftAmt = C->getZExtValue();
10334      if (VT == MVT::i32 && ShiftAmt == 16 &&
10335          DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
10336        return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10337      if (VT == MVT::i64 && ShiftAmt == 32 &&
10338          DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
10339        return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10340    }
10341  }
10342  return SDValue();
10343}
10344
10345static SDValue performConcatVectorsCombine(SDNode *N,
10346                                           TargetLowering::DAGCombinerInfo &DCI,
10347                                           SelectionDAG &DAG) {
10348  SDLoc dl(N);
10349  EVT VT = N->getValueType(0);
10350  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
10351
10352  // Optimize concat_vectors of truncated vectors, where the intermediate
10353  // type is illegal, to avoid said illegality,  e.g.,
10354  //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
10355  //                          (v2i16 (truncate (v2i64)))))
10356  // ->
10357  //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10358  //                                    (v4i32 (bitcast (v2i64))),
10359  //                                    <0, 2, 4, 6>)))
10360  // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10361  // on both input and result type, so we might generate worse code.
10362  // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10363  if (N->getNumOperands() == 2 &&
10364      N0->getOpcode() == ISD::TRUNCATE &&
10365      N1->getOpcode() == ISD::TRUNCATE) {
10366    SDValue N00 = N0->getOperand(0);
10367    SDValue N10 = N1->getOperand(0);
10368    EVT N00VT = N00.getValueType();
10369
10370    if (N00VT == N10.getValueType() &&
10371        (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10372        N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10373      MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10374      SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10375      for (size_t i = 0; i < Mask.size(); ++i)
10376        Mask[i] = i * 2;
10377      return DAG.getNode(ISD::TRUNCATE, dl, VT,
10378                         DAG.getVectorShuffle(
10379                             MidVT, dl,
10380                             DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10381                             DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10382    }
10383  }
10384
10385  // Wait 'til after everything is legalized to try this. That way we have
10386  // legal vector types and such.
10387  if (DCI.isBeforeLegalizeOps())
10388    return SDValue();
10389
10390  // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10391  // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10392  // canonicalise to that.
10393  if (N0 == N1 && VT.getVectorNumElements() == 2) {
10394    assert(VT.getScalarSizeInBits() == 64);
10395    return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10396                       DAG.getConstant(0, dl, MVT::i64));
10397  }
10398
10399  // Canonicalise concat_vectors so that the right-hand vector has as few
10400  // bit-casts as possible before its real operation. The primary matching
10401  // destination for these operations will be the narrowing "2" instructions,
10402  // which depend on the operation being performed on this right-hand vector.
10403  // For example,
10404  //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
10405  // becomes
10406  //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10407
10408  if (N1->getOpcode() != ISD::BITCAST)
10409    return SDValue();
10410  SDValue RHS = N1->getOperand(0);
10411  MVT RHSTy = RHS.getValueType().getSimpleVT();
10412  // If the RHS is not a vector, this is not the pattern we're looking for.
10413  if (!RHSTy.isVector())
10414    return SDValue();
10415
10416  LLVM_DEBUG(
10417      dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10418
10419  MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10420                                  RHSTy.getVectorNumElements() * 2);
10421  return DAG.getNode(ISD::BITCAST, dl, VT,
10422                     DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10423                                 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10424                                 RHS));
10425}
10426
10427static SDValue tryCombineFixedPointConvert(SDNode *N,
10428                                           TargetLowering::DAGCombinerInfo &DCI,
10429                                           SelectionDAG &DAG) {
10430  // Wait until after everything is legalized to try this. That way we have
10431  // legal vector types and such.
10432  if (DCI.isBeforeLegalizeOps())
10433    return SDValue();
10434  // Transform a scalar conversion of a value from a lane extract into a
10435  // lane extract of a vector conversion. E.g., from foo1 to foo2:
10436  // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10437  // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10438  //
10439  // The second form interacts better with instruction selection and the
10440  // register allocator to avoid cross-class register copies that aren't
10441  // coalescable due to a lane reference.
10442
10443  // Check the operand and see if it originates from a lane extract.
10444  SDValue Op1 = N->getOperand(1);
10445  if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10446    // Yep, no additional predication needed. Perform the transform.
10447    SDValue IID = N->getOperand(0);
10448    SDValue Shift = N->getOperand(2);
10449    SDValue Vec = Op1.getOperand(0);
10450    SDValue Lane = Op1.getOperand(1);
10451    EVT ResTy = N->getValueType(0);
10452    EVT VecResTy;
10453    SDLoc DL(N);
10454
10455    // The vector width should be 128 bits by the time we get here, even
10456    // if it started as 64 bits (the extract_vector handling will have
10457    // done so).
10458    assert(Vec.getValueSizeInBits() == 128 &&
10459           "unexpected vector size on extract_vector_elt!");
10460    if (Vec.getValueType() == MVT::v4i32)
10461      VecResTy = MVT::v4f32;
10462    else if (Vec.getValueType() == MVT::v2i64)
10463      VecResTy = MVT::v2f64;
10464    else
10465      llvm_unreachable("unexpected vector type!");
10466
10467    SDValue Convert =
10468        DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10469    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10470  }
10471  return SDValue();
10472}
10473
10474// AArch64 high-vector "long" operations are formed by performing the non-high
10475// version on an extract_subvector of each operand which gets the high half:
10476//
10477//  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10478//
10479// However, there are cases which don't have an extract_high explicitly, but
10480// have another operation that can be made compatible with one for free. For
10481// example:
10482//
10483//  (dupv64 scalar) --> (extract_high (dup128 scalar))
10484//
10485// This routine does the actual conversion of such DUPs, once outer routines
10486// have determined that everything else is in order.
10487// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10488// similarly here.
10489static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10490  switch (N.getOpcode()) {
10491  case AArch64ISD::DUP:
10492  case AArch64ISD::DUPLANE8:
10493  case AArch64ISD::DUPLANE16:
10494  case AArch64ISD::DUPLANE32:
10495  case AArch64ISD::DUPLANE64:
10496  case AArch64ISD::MOVI:
10497  case AArch64ISD::MOVIshift:
10498  case AArch64ISD::MOVIedit:
10499  case AArch64ISD::MOVImsl:
10500  case AArch64ISD::MVNIshift:
10501  case AArch64ISD::MVNImsl:
10502    break;
10503  default:
10504    // FMOV could be supported, but isn't very useful, as it would only occur
10505    // if you passed a bitcast' floating point immediate to an eligible long
10506    // integer op (addl, smull, ...).
10507    return SDValue();
10508  }
10509
10510  MVT NarrowTy = N.getSimpleValueType();
10511  if (!NarrowTy.is64BitVector())
10512    return SDValue();
10513
10514  MVT ElementTy = NarrowTy.getVectorElementType();
10515  unsigned NumElems = NarrowTy.getVectorNumElements();
10516  MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10517
10518  SDLoc dl(N);
10519  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10520                     DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10521                     DAG.getConstant(NumElems, dl, MVT::i64));
10522}
10523
10524static bool isEssentiallyExtractHighSubvector(SDValue N) {
10525  if (N.getOpcode() == ISD::BITCAST)
10526    N = N.getOperand(0);
10527  if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10528    return false;
10529  return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10530         N.getOperand(0).getValueType().getVectorNumElements() / 2;
10531}
10532
10533/// Helper structure to keep track of ISD::SET_CC operands.
10534struct GenericSetCCInfo {
10535  const SDValue *Opnd0;
10536  const SDValue *Opnd1;
10537  ISD::CondCode CC;
10538};
10539
10540/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10541struct AArch64SetCCInfo {
10542  const SDValue *Cmp;
10543  AArch64CC::CondCode CC;
10544};
10545
10546/// Helper structure to keep track of SetCC information.
10547union SetCCInfo {
10548  GenericSetCCInfo Generic;
10549  AArch64SetCCInfo AArch64;
10550};
10551
10552/// Helper structure to be able to read SetCC information.  If set to
10553/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10554/// GenericSetCCInfo.
10555struct SetCCInfoAndKind {
10556  SetCCInfo Info;
10557  bool IsAArch64;
10558};
10559
10560/// Check whether or not \p Op is a SET_CC operation, either a generic or
10561/// an
10562/// AArch64 lowered one.
10563/// \p SetCCInfo is filled accordingly.
10564/// \post SetCCInfo is meanginfull only when this function returns true.
10565/// \return True when Op is a kind of SET_CC operation.
10566static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10567  // If this is a setcc, this is straight forward.
10568  if (Op.getOpcode() == ISD::SETCC) {
10569    SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10570    SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10571    SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10572    SetCCInfo.IsAArch64 = false;
10573    return true;
10574  }
10575  // Otherwise, check if this is a matching csel instruction.
10576  // In other words:
10577  // - csel 1, 0, cc
10578  // - csel 0, 1, !cc
10579  if (Op.getOpcode() != AArch64ISD::CSEL)
10580    return false;
10581  // Set the information about the operands.
10582  // TODO: we want the operands of the Cmp not the csel
10583  SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10584  SetCCInfo.IsAArch64 = true;
10585  SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10586      cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10587
10588  // Check that the operands matches the constraints:
10589  // (1) Both operands must be constants.
10590  // (2) One must be 1 and the other must be 0.
10591  ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10592  ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10593
10594  // Check (1).
10595  if (!TValue || !FValue)
10596    return false;
10597
10598  // Check (2).
10599  if (!TValue->isOne()) {
10600    // Update the comparison when we are interested in !cc.
10601    std::swap(TValue, FValue);
10602    SetCCInfo.Info.AArch64.CC =
10603        AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10604  }
10605  return TValue->isOne() && FValue->isNullValue();
10606}
10607
10608// Returns true if Op is setcc or zext of setcc.
10609static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10610  if (isSetCC(Op, Info))
10611    return true;
10612  return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10613    isSetCC(Op->getOperand(0), Info));
10614}
10615
10616// The folding we want to perform is:
10617// (add x, [zext] (setcc cc ...) )
10618//   -->
10619// (csel x, (add x, 1), !cc ...)
10620//
10621// The latter will get matched to a CSINC instruction.
10622static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10623  assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10624  SDValue LHS = Op->getOperand(0);
10625  SDValue RHS = Op->getOperand(1);
10626  SetCCInfoAndKind InfoAndKind;
10627
10628  // If neither operand is a SET_CC, give up.
10629  if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10630    std::swap(LHS, RHS);
10631    if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10632      return SDValue();
10633  }
10634
10635  // FIXME: This could be generatized to work for FP comparisons.
10636  EVT CmpVT = InfoAndKind.IsAArch64
10637                  ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10638                  : InfoAndKind.Info.Generic.Opnd0->getValueType();
10639  if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10640    return SDValue();
10641
10642  SDValue CCVal;
10643  SDValue Cmp;
10644  SDLoc dl(Op);
10645  if (InfoAndKind.IsAArch64) {
10646    CCVal = DAG.getConstant(
10647        AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10648        MVT::i32);
10649    Cmp = *InfoAndKind.Info.AArch64.Cmp;
10650  } else
10651    Cmp = getAArch64Cmp(
10652        *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
10653        ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
10654        dl);
10655
10656  EVT VT = Op->getValueType(0);
10657  LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10658  return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10659}
10660
10661// The basic add/sub long vector instructions have variants with "2" on the end
10662// which act on the high-half of their inputs. They are normally matched by
10663// patterns like:
10664//
10665// (add (zeroext (extract_high LHS)),
10666//      (zeroext (extract_high RHS)))
10667// -> uaddl2 vD, vN, vM
10668//
10669// However, if one of the extracts is something like a duplicate, this
10670// instruction can still be used profitably. This function puts the DAG into a
10671// more appropriate form for those patterns to trigger.
10672static SDValue performAddSubLongCombine(SDNode *N,
10673                                        TargetLowering::DAGCombinerInfo &DCI,
10674                                        SelectionDAG &DAG) {
10675  if (DCI.isBeforeLegalizeOps())
10676    return SDValue();
10677
10678  MVT VT = N->getSimpleValueType(0);
10679  if (!VT.is128BitVector()) {
10680    if (N->getOpcode() == ISD::ADD)
10681      return performSetccAddFolding(N, DAG);
10682    return SDValue();
10683  }
10684
10685  // Make sure both branches are extended in the same way.
10686  SDValue LHS = N->getOperand(0);
10687  SDValue RHS = N->getOperand(1);
10688  if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10689       LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10690      LHS.getOpcode() != RHS.getOpcode())
10691    return SDValue();
10692
10693  unsigned ExtType = LHS.getOpcode();
10694
10695  // It's not worth doing if at least one of the inputs isn't already an
10696  // extract, but we don't know which it'll be so we have to try both.
10697  if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10698    RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10699    if (!RHS.getNode())
10700      return SDValue();
10701
10702    RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10703  } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10704    LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10705    if (!LHS.getNode())
10706      return SDValue();
10707
10708    LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10709  }
10710
10711  return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10712}
10713
10714// Massage DAGs which we can use the high-half "long" operations on into
10715// something isel will recognize better. E.g.
10716//
10717// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10718//   (aarch64_neon_umull (extract_high (v2i64 vec)))
10719//                     (extract_high (v2i64 (dup128 scalar)))))
10720//
10721static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10722                                       TargetLowering::DAGCombinerInfo &DCI,
10723                                       SelectionDAG &DAG) {
10724  if (DCI.isBeforeLegalizeOps())
10725    return SDValue();
10726
10727  SDValue LHS = N->getOperand(1);
10728  SDValue RHS = N->getOperand(2);
10729  assert(LHS.getValueType().is64BitVector() &&
10730         RHS.getValueType().is64BitVector() &&
10731         "unexpected shape for long operation");
10732
10733  // Either node could be a DUP, but it's not worth doing both of them (you'd
10734  // just as well use the non-high version) so look for a corresponding extract
10735  // operation on the other "wing".
10736  if (isEssentiallyExtractHighSubvector(LHS)) {
10737    RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10738    if (!RHS.getNode())
10739      return SDValue();
10740  } else if (isEssentiallyExtractHighSubvector(RHS)) {
10741    LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10742    if (!LHS.getNode())
10743      return SDValue();
10744  }
10745
10746  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10747                     N->getOperand(0), LHS, RHS);
10748}
10749
10750static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10751  MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10752  unsigned ElemBits = ElemTy.getSizeInBits();
10753
10754  int64_t ShiftAmount;
10755  if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10756    APInt SplatValue, SplatUndef;
10757    unsigned SplatBitSize;
10758    bool HasAnyUndefs;
10759    if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10760                              HasAnyUndefs, ElemBits) ||
10761        SplatBitSize != ElemBits)
10762      return SDValue();
10763
10764    ShiftAmount = SplatValue.getSExtValue();
10765  } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10766    ShiftAmount = CVN->getSExtValue();
10767  } else
10768    return SDValue();
10769
10770  unsigned Opcode;
10771  bool IsRightShift;
10772  switch (IID) {
10773  default:
10774    llvm_unreachable("Unknown shift intrinsic");
10775  case Intrinsic::aarch64_neon_sqshl:
10776    Opcode = AArch64ISD::SQSHL_I;
10777    IsRightShift = false;
10778    break;
10779  case Intrinsic::aarch64_neon_uqshl:
10780    Opcode = AArch64ISD::UQSHL_I;
10781    IsRightShift = false;
10782    break;
10783  case Intrinsic::aarch64_neon_srshl:
10784    Opcode = AArch64ISD::SRSHR_I;
10785    IsRightShift = true;
10786    break;
10787  case Intrinsic::aarch64_neon_urshl:
10788    Opcode = AArch64ISD::URSHR_I;
10789    IsRightShift = true;
10790    break;
10791  case Intrinsic::aarch64_neon_sqshlu:
10792    Opcode = AArch64ISD::SQSHLU_I;
10793    IsRightShift = false;
10794    break;
10795  case Intrinsic::aarch64_neon_sshl:
10796  case Intrinsic::aarch64_neon_ushl:
10797    // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
10798    // left shift for positive shift amounts. Below, we only replace the current
10799    // node with VSHL, if this condition is met.
10800    Opcode = AArch64ISD::VSHL;
10801    IsRightShift = false;
10802    break;
10803  }
10804
10805  if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10806    SDLoc dl(N);
10807    return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10808                       DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10809  } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10810    SDLoc dl(N);
10811    return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10812                       DAG.getConstant(ShiftAmount, dl, MVT::i32));
10813  }
10814
10815  return SDValue();
10816}
10817
10818// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10819// the intrinsics must be legal and take an i32, this means there's almost
10820// certainly going to be a zext in the DAG which we can eliminate.
10821static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10822  SDValue AndN = N->getOperand(2);
10823  if (AndN.getOpcode() != ISD::AND)
10824    return SDValue();
10825
10826  ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10827  if (!CMask || CMask->getZExtValue() != Mask)
10828    return SDValue();
10829
10830  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10831                     N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10832}
10833
10834static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10835                                           SelectionDAG &DAG) {
10836  SDLoc dl(N);
10837  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10838                     DAG.getNode(Opc, dl,
10839                                 N->getOperand(1).getSimpleValueType(),
10840                                 N->getOperand(1)),
10841                     DAG.getConstant(0, dl, MVT::i64));
10842}
10843
10844static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
10845                                    SelectionDAG &DAG) {
10846  SDLoc dl(N);
10847  LLVMContext &Ctx = *DAG.getContext();
10848  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10849
10850  EVT VT = N->getValueType(0);
10851  SDValue Pred = N->getOperand(1);
10852  SDValue Data = N->getOperand(2);
10853  EVT DataVT = Data.getValueType();
10854
10855  if (DataVT.getVectorElementType().isScalarInteger() &&
10856      (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
10857    if (!TLI.isTypeLegal(DataVT))
10858      return SDValue();
10859
10860    EVT OutputVT = EVT::getVectorVT(Ctx, VT,
10861      AArch64::NeonBitsPerVector / VT.getSizeInBits());
10862    SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
10863    SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
10864    SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
10865
10866    return Result;
10867  }
10868
10869  return SDValue();
10870}
10871
10872static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
10873  SDLoc dl(N);
10874  LLVMContext &Ctx = *DAG.getContext();
10875  EVT VT = N->getValueType(0);
10876
10877  assert(VT.isScalableVector() && "Expected a scalable vector.");
10878
10879  // Current lowering only supports the SVE-ACLE types.
10880  if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
10881    return SDValue();
10882
10883  unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
10884  unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
10885  EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
10886
10887  // Convert everything to the domain of EXT (i.e bytes).
10888  SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
10889  SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
10890  SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
10891                            DAG.getConstant(ElemSize, dl, MVT::i32));
10892
10893  SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
10894  return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
10895}
10896
10897static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID,
10898                                        bool Invert,
10899                                        TargetLowering::DAGCombinerInfo &DCI,
10900                                        SelectionDAG &DAG) {
10901  if (DCI.isBeforeLegalize())
10902    return SDValue();
10903
10904  SDValue Comparator = N->getOperand(3);
10905  if (Comparator.getOpcode() == AArch64ISD::DUP ||
10906      Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
10907    unsigned IID = getIntrinsicID(N);
10908    EVT VT = N->getValueType(0);
10909    EVT CmpVT = N->getOperand(2).getValueType();
10910    SDValue Pred = N->getOperand(1);
10911    SDValue Imm;
10912    SDLoc DL(N);
10913
10914    switch (IID) {
10915    default:
10916      llvm_unreachable("Called with wrong intrinsic!");
10917      break;
10918
10919    // Signed comparisons
10920    case Intrinsic::aarch64_sve_cmpeq_wide:
10921    case Intrinsic::aarch64_sve_cmpne_wide:
10922    case Intrinsic::aarch64_sve_cmpge_wide:
10923    case Intrinsic::aarch64_sve_cmpgt_wide:
10924    case Intrinsic::aarch64_sve_cmplt_wide:
10925    case Intrinsic::aarch64_sve_cmple_wide: {
10926      if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10927        int64_t ImmVal = CN->getSExtValue();
10928        if (ImmVal >= -16 && ImmVal <= 15)
10929          Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10930        else
10931          return SDValue();
10932      }
10933      break;
10934    }
10935    // Unsigned comparisons
10936    case Intrinsic::aarch64_sve_cmphs_wide:
10937    case Intrinsic::aarch64_sve_cmphi_wide:
10938    case Intrinsic::aarch64_sve_cmplo_wide:
10939    case Intrinsic::aarch64_sve_cmpls_wide:  {
10940      if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10941        uint64_t ImmVal = CN->getZExtValue();
10942        if (ImmVal <= 127)
10943          Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10944        else
10945          return SDValue();
10946      }
10947      break;
10948    }
10949    }
10950
10951    SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
10952    SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64);
10953    SDValue Op0, Op1;
10954    if (Invert) {
10955      Op0 = Splat;
10956      Op1 = N->getOperand(2);
10957    } else {
10958      Op0 = N->getOperand(2);
10959      Op1 = Splat;
10960    }
10961    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10962                       ID, Pred, Op0, Op1);
10963  }
10964
10965  return SDValue();
10966}
10967
10968static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
10969                        AArch64CC::CondCode Cond) {
10970  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10971
10972  SDLoc DL(Op);
10973  assert(Op.getValueType().isScalableVector() &&
10974         TLI.isTypeLegal(Op.getValueType()) &&
10975         "Expected legal scalable vector type!");
10976
10977  // Ensure target specific opcodes are using legal type.
10978  EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
10979  SDValue TVal = DAG.getConstant(1, DL, OutVT);
10980  SDValue FVal = DAG.getConstant(0, DL, OutVT);
10981
10982  // Set condition code (CC) flags.
10983  SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
10984
10985  // Convert CC to integer based on requested condition.
10986  // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
10987  SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
10988  SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
10989  return DAG.getZExtOrTrunc(Res, DL, VT);
10990}
10991
10992static SDValue performIntrinsicCombine(SDNode *N,
10993                                       TargetLowering::DAGCombinerInfo &DCI,
10994                                       const AArch64Subtarget *Subtarget) {
10995  SelectionDAG &DAG = DCI.DAG;
10996  unsigned IID = getIntrinsicID(N);
10997  switch (IID) {
10998  default:
10999    break;
11000  case Intrinsic::aarch64_neon_vcvtfxs2fp:
11001  case Intrinsic::aarch64_neon_vcvtfxu2fp:
11002    return tryCombineFixedPointConvert(N, DCI, DAG);
11003  case Intrinsic::aarch64_neon_saddv:
11004    return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11005  case Intrinsic::aarch64_neon_uaddv:
11006    return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11007  case Intrinsic::aarch64_neon_sminv:
11008    return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11009  case Intrinsic::aarch64_neon_uminv:
11010    return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11011  case Intrinsic::aarch64_neon_smaxv:
11012    return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11013  case Intrinsic::aarch64_neon_umaxv:
11014    return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11015  case Intrinsic::aarch64_neon_fmax:
11016    return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11017                       N->getOperand(1), N->getOperand(2));
11018  case Intrinsic::aarch64_neon_fmin:
11019    return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11020                       N->getOperand(1), N->getOperand(2));
11021  case Intrinsic::aarch64_neon_fmaxnm:
11022    return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11023                       N->getOperand(1), N->getOperand(2));
11024  case Intrinsic::aarch64_neon_fminnm:
11025    return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11026                       N->getOperand(1), N->getOperand(2));
11027  case Intrinsic::aarch64_neon_smull:
11028  case Intrinsic::aarch64_neon_umull:
11029  case Intrinsic::aarch64_neon_pmull:
11030  case Intrinsic::aarch64_neon_sqdmull:
11031    return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11032  case Intrinsic::aarch64_neon_sqshl:
11033  case Intrinsic::aarch64_neon_uqshl:
11034  case Intrinsic::aarch64_neon_sqshlu:
11035  case Intrinsic::aarch64_neon_srshl:
11036  case Intrinsic::aarch64_neon_urshl:
11037  case Intrinsic::aarch64_neon_sshl:
11038  case Intrinsic::aarch64_neon_ushl:
11039    return tryCombineShiftImm(IID, N, DAG);
11040  case Intrinsic::aarch64_crc32b:
11041  case Intrinsic::aarch64_crc32cb:
11042    return tryCombineCRC32(0xff, N, DAG);
11043  case Intrinsic::aarch64_crc32h:
11044  case Intrinsic::aarch64_crc32ch:
11045    return tryCombineCRC32(0xffff, N, DAG);
11046  case Intrinsic::aarch64_sve_smaxv:
11047    return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11048  case Intrinsic::aarch64_sve_umaxv:
11049    return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11050  case Intrinsic::aarch64_sve_sminv:
11051    return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11052  case Intrinsic::aarch64_sve_uminv:
11053    return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11054  case Intrinsic::aarch64_sve_orv:
11055    return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11056  case Intrinsic::aarch64_sve_eorv:
11057    return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11058  case Intrinsic::aarch64_sve_andv:
11059    return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11060  case Intrinsic::aarch64_sve_ext:
11061    return LowerSVEIntrinsicEXT(N, DAG);
11062  case Intrinsic::aarch64_sve_cmpeq_wide:
11063    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq,
11064                                    false, DCI, DAG);
11065  case Intrinsic::aarch64_sve_cmpne_wide:
11066    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne,
11067                                    false, DCI, DAG);
11068  case Intrinsic::aarch64_sve_cmpge_wide:
11069    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11070                                    false, DCI, DAG);
11071  case Intrinsic::aarch64_sve_cmpgt_wide:
11072    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11073                                    false, DCI, DAG);
11074  case Intrinsic::aarch64_sve_cmplt_wide:
11075    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11076                                    true, DCI, DAG);
11077  case Intrinsic::aarch64_sve_cmple_wide:
11078    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11079                                    true, DCI, DAG);
11080  case Intrinsic::aarch64_sve_cmphs_wide:
11081    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs,
11082                                    false, DCI, DAG);
11083  case Intrinsic::aarch64_sve_cmphi_wide:
11084    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi,
11085                                    false, DCI, DAG);
11086  case Intrinsic::aarch64_sve_cmplo_wide:
11087    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true,
11088                                    DCI, DAG);
11089  case Intrinsic::aarch64_sve_cmpls_wide:
11090    return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true,
11091                                    DCI, DAG);
11092  case Intrinsic::aarch64_sve_ptest_any:
11093    return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11094                    AArch64CC::ANY_ACTIVE);
11095  case Intrinsic::aarch64_sve_ptest_first:
11096    return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11097                    AArch64CC::FIRST_ACTIVE);
11098  case Intrinsic::aarch64_sve_ptest_last:
11099    return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11100                    AArch64CC::LAST_ACTIVE);
11101  }
11102  return SDValue();
11103}
11104
11105static SDValue performExtendCombine(SDNode *N,
11106                                    TargetLowering::DAGCombinerInfo &DCI,
11107                                    SelectionDAG &DAG) {
11108  // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
11109  // we can convert that DUP into another extract_high (of a bigger DUP), which
11110  // helps the backend to decide that an sabdl2 would be useful, saving a real
11111  // extract_high operation.
11112  if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
11113      N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
11114    SDNode *ABDNode = N->getOperand(0).getNode();
11115    unsigned IID = getIntrinsicID(ABDNode);
11116    if (IID == Intrinsic::aarch64_neon_sabd ||
11117        IID == Intrinsic::aarch64_neon_uabd) {
11118      SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
11119      if (!NewABD.getNode())
11120        return SDValue();
11121
11122      return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
11123                         NewABD);
11124    }
11125  }
11126
11127  // This is effectively a custom type legalization for AArch64.
11128  //
11129  // Type legalization will split an extend of a small, legal, type to a larger
11130  // illegal type by first splitting the destination type, often creating
11131  // illegal source types, which then get legalized in isel-confusing ways,
11132  // leading to really terrible codegen. E.g.,
11133  //   %result = v8i32 sext v8i8 %value
11134  // becomes
11135  //   %losrc = extract_subreg %value, ...
11136  //   %hisrc = extract_subreg %value, ...
11137  //   %lo = v4i32 sext v4i8 %losrc
11138  //   %hi = v4i32 sext v4i8 %hisrc
11139  // Things go rapidly downhill from there.
11140  //
11141  // For AArch64, the [sz]ext vector instructions can only go up one element
11142  // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
11143  // take two instructions.
11144  //
11145  // This implies that the most efficient way to do the extend from v8i8
11146  // to two v4i32 values is to first extend the v8i8 to v8i16, then do
11147  // the normal splitting to happen for the v8i16->v8i32.
11148
11149  // This is pre-legalization to catch some cases where the default
11150  // type legalization will create ill-tempered code.
11151  if (!DCI.isBeforeLegalizeOps())
11152    return SDValue();
11153
11154  // We're only interested in cleaning things up for non-legal vector types
11155  // here. If both the source and destination are legal, things will just
11156  // work naturally without any fiddling.
11157  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11158  EVT ResVT = N->getValueType(0);
11159  if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
11160    return SDValue();
11161  // If the vector type isn't a simple VT, it's beyond the scope of what
11162  // we're  worried about here. Let legalization do its thing and hope for
11163  // the best.
11164  SDValue Src = N->getOperand(0);
11165  EVT SrcVT = Src->getValueType(0);
11166  if (!ResVT.isSimple() || !SrcVT.isSimple())
11167    return SDValue();
11168
11169  // If the source VT is a 64-bit vector, we can play games and get the
11170  // better results we want.
11171  if (SrcVT.getSizeInBits() != 64)
11172    return SDValue();
11173
11174  unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
11175  unsigned ElementCount = SrcVT.getVectorNumElements();
11176  SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
11177  SDLoc DL(N);
11178  Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
11179
11180  // Now split the rest of the operation into two halves, each with a 64
11181  // bit source.
11182  EVT LoVT, HiVT;
11183  SDValue Lo, Hi;
11184  unsigned NumElements = ResVT.getVectorNumElements();
11185  assert(!(NumElements & 1) && "Splitting vector, but not in half!");
11186  LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
11187                                 ResVT.getVectorElementType(), NumElements / 2);
11188
11189  EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
11190                               LoVT.getVectorNumElements());
11191  Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11192                   DAG.getConstant(0, DL, MVT::i64));
11193  Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11194                   DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
11195  Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
11196  Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
11197
11198  // Now combine the parts back together so we still have a single result
11199  // like the combiner expects.
11200  return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
11201}
11202
11203static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
11204                               SDValue SplatVal, unsigned NumVecElts) {
11205  assert(!St.isTruncatingStore() && "cannot split truncating vector store");
11206  unsigned OrigAlignment = St.getAlignment();
11207  unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
11208
11209  // Create scalar stores. This is at least as good as the code sequence for a
11210  // split unaligned store which is a dup.s, ext.b, and two stores.
11211  // Most of the time the three stores should be replaced by store pair
11212  // instructions (stp).
11213  SDLoc DL(&St);
11214  SDValue BasePtr = St.getBasePtr();
11215  uint64_t BaseOffset = 0;
11216
11217  const MachinePointerInfo &PtrInfo = St.getPointerInfo();
11218  SDValue NewST1 =
11219      DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
11220                   OrigAlignment, St.getMemOperand()->getFlags());
11221
11222  // As this in ISel, we will not merge this add which may degrade results.
11223  if (BasePtr->getOpcode() == ISD::ADD &&
11224      isa<ConstantSDNode>(BasePtr->getOperand(1))) {
11225    BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
11226    BasePtr = BasePtr->getOperand(0);
11227  }
11228
11229  unsigned Offset = EltOffset;
11230  while (--NumVecElts) {
11231    unsigned Alignment = MinAlign(OrigAlignment, Offset);
11232    SDValue OffsetPtr =
11233        DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11234                    DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
11235    NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
11236                          PtrInfo.getWithOffset(Offset), Alignment,
11237                          St.getMemOperand()->getFlags());
11238    Offset += EltOffset;
11239  }
11240  return NewST1;
11241}
11242
11243static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
11244  SDLoc DL(N);
11245  EVT VT = N->getValueType(0);
11246  EVT PtrTy = N->getOperand(3).getValueType();
11247
11248  EVT LoadVT = VT;
11249  if (VT.isFloatingPoint())
11250    LoadVT = VT.changeTypeToInteger();
11251
11252  auto *MINode = cast<MemIntrinsicSDNode>(N);
11253  SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
11254  SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
11255                                MINode->getOperand(3), DAG.getUNDEF(PtrTy),
11256                                MINode->getOperand(2), PassThru,
11257                                MINode->getMemoryVT(), MINode->getMemOperand(),
11258                                ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
11259
11260   if (VT.isFloatingPoint()) {
11261     SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
11262     return DAG.getMergeValues(Ops, DL);
11263   }
11264
11265  return L;
11266}
11267
11268static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
11269  SDLoc DL(N);
11270
11271  SDValue Data = N->getOperand(2);
11272  EVT DataVT = Data.getValueType();
11273  EVT PtrTy = N->getOperand(4).getValueType();
11274
11275  if (DataVT.isFloatingPoint())
11276    Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
11277
11278  auto *MINode = cast<MemIntrinsicSDNode>(N);
11279  return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
11280                            DAG.getUNDEF(PtrTy), MINode->getOperand(3),
11281                            MINode->getMemoryVT(), MINode->getMemOperand(),
11282                            ISD::UNINDEXED, false, false);
11283}
11284
11285/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
11286/// load store optimizer pass will merge them to store pair stores.  This should
11287/// be better than a movi to create the vector zero followed by a vector store
11288/// if the zero constant is not re-used, since one instructions and one register
11289/// live range will be removed.
11290///
11291/// For example, the final generated code should be:
11292///
11293///   stp xzr, xzr, [x0]
11294///
11295/// instead of:
11296///
11297///   movi v0.2d, #0
11298///   str q0, [x0]
11299///
11300static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11301  SDValue StVal = St.getValue();
11302  EVT VT = StVal.getValueType();
11303
11304  // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
11305  // 2, 3 or 4 i32 elements.
11306  int NumVecElts = VT.getVectorNumElements();
11307  if (!(((NumVecElts == 2 || NumVecElts == 3) &&
11308         VT.getVectorElementType().getSizeInBits() == 64) ||
11309        ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
11310         VT.getVectorElementType().getSizeInBits() == 32)))
11311    return SDValue();
11312
11313  if (StVal.getOpcode() != ISD::BUILD_VECTOR)
11314    return SDValue();
11315
11316  // If the zero constant has more than one use then the vector store could be
11317  // better since the constant mov will be amortized and stp q instructions
11318  // should be able to be formed.
11319  if (!StVal.hasOneUse())
11320    return SDValue();
11321
11322  // If the store is truncating then it's going down to i16 or smaller, which
11323  // means it can be implemented in a single store anyway.
11324  if (St.isTruncatingStore())
11325    return SDValue();
11326
11327  // If the immediate offset of the address operand is too large for the stp
11328  // instruction, then bail out.
11329  if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
11330    int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
11331    if (Offset < -512 || Offset > 504)
11332      return SDValue();
11333  }
11334
11335  for (int I = 0; I < NumVecElts; ++I) {
11336    SDValue EltVal = StVal.getOperand(I);
11337    if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
11338      return SDValue();
11339  }
11340
11341  // Use a CopyFromReg WZR/XZR here to prevent
11342  // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
11343  SDLoc DL(&St);
11344  unsigned ZeroReg;
11345  EVT ZeroVT;
11346  if (VT.getVectorElementType().getSizeInBits() == 32) {
11347    ZeroReg = AArch64::WZR;
11348    ZeroVT = MVT::i32;
11349  } else {
11350    ZeroReg = AArch64::XZR;
11351    ZeroVT = MVT::i64;
11352  }
11353  SDValue SplatVal =
11354      DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
11355  return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11356}
11357
11358/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
11359/// value. The load store optimizer pass will merge them to store pair stores.
11360/// This has better performance than a splat of the scalar followed by a split
11361/// vector store. Even if the stores are not merged it is four stores vs a dup,
11362/// followed by an ext.b and two stores.
11363static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11364  SDValue StVal = St.getValue();
11365  EVT VT = StVal.getValueType();
11366
11367  // Don't replace floating point stores, they possibly won't be transformed to
11368  // stp because of the store pair suppress pass.
11369  if (VT.isFloatingPoint())
11370    return SDValue();
11371
11372  // We can express a splat as store pair(s) for 2 or 4 elements.
11373  unsigned NumVecElts = VT.getVectorNumElements();
11374  if (NumVecElts != 4 && NumVecElts != 2)
11375    return SDValue();
11376
11377  // If the store is truncating then it's going down to i16 or smaller, which
11378  // means it can be implemented in a single store anyway.
11379  if (St.isTruncatingStore())
11380    return SDValue();
11381
11382  // Check that this is a splat.
11383  // Make sure that each of the relevant vector element locations are inserted
11384  // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
11385  std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
11386  SDValue SplatVal;
11387  for (unsigned I = 0; I < NumVecElts; ++I) {
11388    // Check for insert vector elements.
11389    if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
11390      return SDValue();
11391
11392    // Check that same value is inserted at each vector element.
11393    if (I == 0)
11394      SplatVal = StVal.getOperand(1);
11395    else if (StVal.getOperand(1) != SplatVal)
11396      return SDValue();
11397
11398    // Check insert element index.
11399    ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
11400    if (!CIndex)
11401      return SDValue();
11402    uint64_t IndexVal = CIndex->getZExtValue();
11403    if (IndexVal >= NumVecElts)
11404      return SDValue();
11405    IndexNotInserted.reset(IndexVal);
11406
11407    StVal = StVal.getOperand(0);
11408  }
11409  // Check that all vector element locations were inserted to.
11410  if (IndexNotInserted.any())
11411      return SDValue();
11412
11413  return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11414}
11415
11416static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11417                           SelectionDAG &DAG,
11418                           const AArch64Subtarget *Subtarget) {
11419
11420  StoreSDNode *S = cast<StoreSDNode>(N);
11421  if (S->isVolatile() || S->isIndexed())
11422    return SDValue();
11423
11424  SDValue StVal = S->getValue();
11425  EVT VT = StVal.getValueType();
11426  if (!VT.isVector())
11427    return SDValue();
11428
11429  // If we get a splat of zeros, convert this vector store to a store of
11430  // scalars. They will be merged into store pairs of xzr thereby removing one
11431  // instruction and one register.
11432  if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
11433    return ReplacedZeroSplat;
11434
11435  // FIXME: The logic for deciding if an unaligned store should be split should
11436  // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
11437  // a call to that function here.
11438
11439  if (!Subtarget->isMisaligned128StoreSlow())
11440    return SDValue();
11441
11442  // Don't split at -Oz.
11443  if (DAG.getMachineFunction().getFunction().hasMinSize())
11444    return SDValue();
11445
11446  // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
11447  // those up regresses performance on micro-benchmarks and olden/bh.
11448  if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
11449    return SDValue();
11450
11451  // Split unaligned 16B stores. They are terrible for performance.
11452  // Don't split stores with alignment of 1 or 2. Code that uses clang vector
11453  // extensions can use this to mark that it does not want splitting to happen
11454  // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
11455  // eliminating alignment hazards is only 1 in 8 for alignment of 2.
11456  if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
11457      S->getAlignment() <= 2)
11458    return SDValue();
11459
11460  // If we get a splat of a scalar convert this vector store to a store of
11461  // scalars. They will be merged into store pairs thereby removing two
11462  // instructions.
11463  if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
11464    return ReplacedSplat;
11465
11466  SDLoc DL(S);
11467
11468  // Split VT into two.
11469  EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11470  unsigned NumElts = HalfVT.getVectorNumElements();
11471  SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11472                                   DAG.getConstant(0, DL, MVT::i64));
11473  SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11474                                   DAG.getConstant(NumElts, DL, MVT::i64));
11475  SDValue BasePtr = S->getBasePtr();
11476  SDValue NewST1 =
11477      DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
11478                   S->getAlignment(), S->getMemOperand()->getFlags());
11479  SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11480                                  DAG.getConstant(8, DL, MVT::i64));
11481  return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
11482                      S->getPointerInfo(), S->getAlignment(),
11483                      S->getMemOperand()->getFlags());
11484}
11485
11486/// Target-specific DAG combine function for post-increment LD1 (lane) and
11487/// post-increment LD1R.
11488static SDValue performPostLD1Combine(SDNode *N,
11489                                     TargetLowering::DAGCombinerInfo &DCI,
11490                                     bool IsLaneOp) {
11491  if (DCI.isBeforeLegalizeOps())
11492    return SDValue();
11493
11494  SelectionDAG &DAG = DCI.DAG;
11495  EVT VT = N->getValueType(0);
11496
11497  unsigned LoadIdx = IsLaneOp ? 1 : 0;
11498  SDNode *LD = N->getOperand(LoadIdx).getNode();
11499  // If it is not LOAD, can not do such combine.
11500  if (LD->getOpcode() != ISD::LOAD)
11501    return SDValue();
11502
11503  // The vector lane must be a constant in the LD1LANE opcode.
11504  SDValue Lane;
11505  if (IsLaneOp) {
11506    Lane = N->getOperand(2);
11507    auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
11508    if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
11509      return SDValue();
11510  }
11511
11512  LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
11513  EVT MemVT = LoadSDN->getMemoryVT();
11514  // Check if memory operand is the same type as the vector element.
11515  if (MemVT != VT.getVectorElementType())
11516    return SDValue();
11517
11518  // Check if there are other uses. If so, do not combine as it will introduce
11519  // an extra load.
11520  for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
11521       ++UI) {
11522    if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
11523      continue;
11524    if (*UI != N)
11525      return SDValue();
11526  }
11527
11528  SDValue Addr = LD->getOperand(1);
11529  SDValue Vector = N->getOperand(0);
11530  // Search for a use of the address operand that is an increment.
11531  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
11532       Addr.getNode()->use_end(); UI != UE; ++UI) {
11533    SDNode *User = *UI;
11534    if (User->getOpcode() != ISD::ADD
11535        || UI.getUse().getResNo() != Addr.getResNo())
11536      continue;
11537
11538    // If the increment is a constant, it must match the memory ref size.
11539    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11540    if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11541      uint32_t IncVal = CInc->getZExtValue();
11542      unsigned NumBytes = VT.getScalarSizeInBits() / 8;
11543      if (IncVal != NumBytes)
11544        continue;
11545      Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11546    }
11547
11548    // To avoid cycle construction make sure that neither the load nor the add
11549    // are predecessors to each other or the Vector.
11550    SmallPtrSet<const SDNode *, 32> Visited;
11551    SmallVector<const SDNode *, 16> Worklist;
11552    Visited.insert(Addr.getNode());
11553    Worklist.push_back(User);
11554    Worklist.push_back(LD);
11555    Worklist.push_back(Vector.getNode());
11556    if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
11557        SDNode::hasPredecessorHelper(User, Visited, Worklist))
11558      continue;
11559
11560    SmallVector<SDValue, 8> Ops;
11561    Ops.push_back(LD->getOperand(0));  // Chain
11562    if (IsLaneOp) {
11563      Ops.push_back(Vector);           // The vector to be inserted
11564      Ops.push_back(Lane);             // The lane to be inserted in the vector
11565    }
11566    Ops.push_back(Addr);
11567    Ops.push_back(Inc);
11568
11569    EVT Tys[3] = { VT, MVT::i64, MVT::Other };
11570    SDVTList SDTys = DAG.getVTList(Tys);
11571    unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
11572    SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
11573                                           MemVT,
11574                                           LoadSDN->getMemOperand());
11575
11576    // Update the uses.
11577    SDValue NewResults[] = {
11578        SDValue(LD, 0),            // The result of load
11579        SDValue(UpdN.getNode(), 2) // Chain
11580    };
11581    DCI.CombineTo(LD, NewResults);
11582    DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
11583    DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
11584
11585    break;
11586  }
11587  return SDValue();
11588}
11589
11590/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
11591/// address translation.
11592static bool performTBISimplification(SDValue Addr,
11593                                     TargetLowering::DAGCombinerInfo &DCI,
11594                                     SelectionDAG &DAG) {
11595  APInt DemandedMask = APInt::getLowBitsSet(64, 56);
11596  KnownBits Known;
11597  TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11598                                        !DCI.isBeforeLegalizeOps());
11599  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11600  if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
11601    DCI.CommitTargetLoweringOpt(TLO);
11602    return true;
11603  }
11604  return false;
11605}
11606
11607static SDValue performSTORECombine(SDNode *N,
11608                                   TargetLowering::DAGCombinerInfo &DCI,
11609                                   SelectionDAG &DAG,
11610                                   const AArch64Subtarget *Subtarget) {
11611  if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11612    return Split;
11613
11614  if (Subtarget->supportsAddressTopByteIgnored() &&
11615      performTBISimplification(N->getOperand(2), DCI, DAG))
11616    return SDValue(N, 0);
11617
11618  return SDValue();
11619}
11620
11621
11622/// Target-specific DAG combine function for NEON load/store intrinsics
11623/// to merge base address updates.
11624static SDValue performNEONPostLDSTCombine(SDNode *N,
11625                                          TargetLowering::DAGCombinerInfo &DCI,
11626                                          SelectionDAG &DAG) {
11627  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11628    return SDValue();
11629
11630  unsigned AddrOpIdx = N->getNumOperands() - 1;
11631  SDValue Addr = N->getOperand(AddrOpIdx);
11632
11633  // Search for a use of the address operand that is an increment.
11634  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11635       UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11636    SDNode *User = *UI;
11637    if (User->getOpcode() != ISD::ADD ||
11638        UI.getUse().getResNo() != Addr.getResNo())
11639      continue;
11640
11641    // Check that the add is independent of the load/store.  Otherwise, folding
11642    // it would create a cycle.
11643    SmallPtrSet<const SDNode *, 32> Visited;
11644    SmallVector<const SDNode *, 16> Worklist;
11645    Visited.insert(Addr.getNode());
11646    Worklist.push_back(N);
11647    Worklist.push_back(User);
11648    if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11649        SDNode::hasPredecessorHelper(User, Visited, Worklist))
11650      continue;
11651
11652    // Find the new opcode for the updating load/store.
11653    bool IsStore = false;
11654    bool IsLaneOp = false;
11655    bool IsDupOp = false;
11656    unsigned NewOpc = 0;
11657    unsigned NumVecs = 0;
11658    unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11659    switch (IntNo) {
11660    default: llvm_unreachable("unexpected intrinsic for Neon base update");
11661    case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
11662      NumVecs = 2; break;
11663    case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
11664      NumVecs = 3; break;
11665    case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
11666      NumVecs = 4; break;
11667    case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
11668      NumVecs = 2; IsStore = true; break;
11669    case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
11670      NumVecs = 3; IsStore = true; break;
11671    case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
11672      NumVecs = 4; IsStore = true; break;
11673    case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
11674      NumVecs = 2; break;
11675    case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
11676      NumVecs = 3; break;
11677    case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
11678      NumVecs = 4; break;
11679    case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
11680      NumVecs = 2; IsStore = true; break;
11681    case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
11682      NumVecs = 3; IsStore = true; break;
11683    case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
11684      NumVecs = 4; IsStore = true; break;
11685    case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
11686      NumVecs = 2; IsDupOp = true; break;
11687    case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
11688      NumVecs = 3; IsDupOp = true; break;
11689    case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
11690      NumVecs = 4; IsDupOp = true; break;
11691    case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
11692      NumVecs = 2; IsLaneOp = true; break;
11693    case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
11694      NumVecs = 3; IsLaneOp = true; break;
11695    case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
11696      NumVecs = 4; IsLaneOp = true; break;
11697    case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
11698      NumVecs = 2; IsStore = true; IsLaneOp = true; break;
11699    case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
11700      NumVecs = 3; IsStore = true; IsLaneOp = true; break;
11701    case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
11702      NumVecs = 4; IsStore = true; IsLaneOp = true; break;
11703    }
11704
11705    EVT VecTy;
11706    if (IsStore)
11707      VecTy = N->getOperand(2).getValueType();
11708    else
11709      VecTy = N->getValueType(0);
11710
11711    // If the increment is a constant, it must match the memory ref size.
11712    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11713    if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11714      uint32_t IncVal = CInc->getZExtValue();
11715      unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11716      if (IsLaneOp || IsDupOp)
11717        NumBytes /= VecTy.getVectorNumElements();
11718      if (IncVal != NumBytes)
11719        continue;
11720      Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11721    }
11722    SmallVector<SDValue, 8> Ops;
11723    Ops.push_back(N->getOperand(0)); // Incoming chain
11724    // Load lane and store have vector list as input.
11725    if (IsLaneOp || IsStore)
11726      for (unsigned i = 2; i < AddrOpIdx; ++i)
11727        Ops.push_back(N->getOperand(i));
11728    Ops.push_back(Addr); // Base register
11729    Ops.push_back(Inc);
11730
11731    // Return Types.
11732    EVT Tys[6];
11733    unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11734    unsigned n;
11735    for (n = 0; n < NumResultVecs; ++n)
11736      Tys[n] = VecTy;
11737    Tys[n++] = MVT::i64;  // Type of write back register
11738    Tys[n] = MVT::Other;  // Type of the chain
11739    SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
11740
11741    MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11742    SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11743                                           MemInt->getMemoryVT(),
11744                                           MemInt->getMemOperand());
11745
11746    // Update the uses.
11747    std::vector<SDValue> NewResults;
11748    for (unsigned i = 0; i < NumResultVecs; ++i) {
11749      NewResults.push_back(SDValue(UpdN.getNode(), i));
11750    }
11751    NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11752    DCI.CombineTo(N, NewResults);
11753    DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11754
11755    break;
11756  }
11757  return SDValue();
11758}
11759
11760// Checks to see if the value is the prescribed width and returns information
11761// about its extension mode.
11762static
11763bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11764  ExtType = ISD::NON_EXTLOAD;
11765  switch(V.getNode()->getOpcode()) {
11766  default:
11767    return false;
11768  case ISD::LOAD: {
11769    LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11770    if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11771       || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11772      ExtType = LoadNode->getExtensionType();
11773      return true;
11774    }
11775    return false;
11776  }
11777  case ISD::AssertSext: {
11778    VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11779    if ((TypeNode->getVT() == MVT::i8 && width == 8)
11780       || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11781      ExtType = ISD::SEXTLOAD;
11782      return true;
11783    }
11784    return false;
11785  }
11786  case ISD::AssertZext: {
11787    VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11788    if ((TypeNode->getVT() == MVT::i8 && width == 8)
11789       || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11790      ExtType = ISD::ZEXTLOAD;
11791      return true;
11792    }
11793    return false;
11794  }
11795  case ISD::Constant:
11796  case ISD::TargetConstant: {
11797    return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11798           1LL << (width - 1);
11799  }
11800  }
11801
11802  return true;
11803}
11804
11805// This function does a whole lot of voodoo to determine if the tests are
11806// equivalent without and with a mask. Essentially what happens is that given a
11807// DAG resembling:
11808//
11809//  +-------------+ +-------------+ +-------------+ +-------------+
11810//  |    Input    | | AddConstant | | CompConstant| |     CC      |
11811//  +-------------+ +-------------+ +-------------+ +-------------+
11812//           |           |           |               |
11813//           V           V           |    +----------+
11814//          +-------------+  +----+  |    |
11815//          |     ADD     |  |0xff|  |    |
11816//          +-------------+  +----+  |    |
11817//                  |           |    |    |
11818//                  V           V    |    |
11819//                 +-------------+   |    |
11820//                 |     AND     |   |    |
11821//                 +-------------+   |    |
11822//                      |            |    |
11823//                      +-----+      |    |
11824//                            |      |    |
11825//                            V      V    V
11826//                           +-------------+
11827//                           |     CMP     |
11828//                           +-------------+
11829//
11830// The AND node may be safely removed for some combinations of inputs. In
11831// particular we need to take into account the extension type of the Input,
11832// the exact values of AddConstant, CompConstant, and CC, along with the nominal
11833// width of the input (this can work for any width inputs, the above graph is
11834// specific to 8 bits.
11835//
11836// The specific equations were worked out by generating output tables for each
11837// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11838// problem was simplified by working with 4 bit inputs, which means we only
11839// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11840// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11841// patterns present in both extensions (0,7). For every distinct set of
11842// AddConstant and CompConstants bit patterns we can consider the masked and
11843// unmasked versions to be equivalent if the result of this function is true for
11844// all 16 distinct bit patterns of for the current extension type of Input (w0).
11845//
11846//   sub      w8, w0, w1
11847//   and      w10, w8, #0x0f
11848//   cmp      w8, w2
11849//   cset     w9, AArch64CC
11850//   cmp      w10, w2
11851//   cset     w11, AArch64CC
11852//   cmp      w9, w11
11853//   cset     w0, eq
11854//   ret
11855//
11856// Since the above function shows when the outputs are equivalent it defines
11857// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11858// would be expensive to run during compiles. The equations below were written
11859// in a test harness that confirmed they gave equivalent outputs to the above
11860// for all inputs function, so they can be used determine if the removal is
11861// legal instead.
11862//
11863// isEquivalentMaskless() is the code for testing if the AND can be removed
11864// factored out of the DAG recognition as the DAG can take several forms.
11865
11866static bool isEquivalentMaskless(unsigned CC, unsigned width,
11867                                 ISD::LoadExtType ExtType, int AddConstant,
11868                                 int CompConstant) {
11869  // By being careful about our equations and only writing the in term
11870  // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11871  // make them generally applicable to all bit widths.
11872  int MaxUInt = (1 << width);
11873
11874  // For the purposes of these comparisons sign extending the type is
11875  // equivalent to zero extending the add and displacing it by half the integer
11876  // width. Provided we are careful and make sure our equations are valid over
11877  // the whole range we can just adjust the input and avoid writing equations
11878  // for sign extended inputs.
11879  if (ExtType == ISD::SEXTLOAD)
11880    AddConstant -= (1 << (width-1));
11881
11882  switch(CC) {
11883  case AArch64CC::LE:
11884  case AArch64CC::GT:
11885    if ((AddConstant == 0) ||
11886        (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11887        (AddConstant >= 0 && CompConstant < 0) ||
11888        (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11889      return true;
11890    break;
11891  case AArch64CC::LT:
11892  case AArch64CC::GE:
11893    if ((AddConstant == 0) ||
11894        (AddConstant >= 0 && CompConstant <= 0) ||
11895        (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11896      return true;
11897    break;
11898  case AArch64CC::HI:
11899  case AArch64CC::LS:
11900    if ((AddConstant >= 0 && CompConstant < 0) ||
11901       (AddConstant <= 0 && CompConstant >= -1 &&
11902        CompConstant < AddConstant + MaxUInt))
11903      return true;
11904   break;
11905  case AArch64CC::PL:
11906  case AArch64CC::MI:
11907    if ((AddConstant == 0) ||
11908        (AddConstant > 0 && CompConstant <= 0) ||
11909        (AddConstant < 0 && CompConstant <= AddConstant))
11910      return true;
11911    break;
11912  case AArch64CC::LO:
11913  case AArch64CC::HS:
11914    if ((AddConstant >= 0 && CompConstant <= 0) ||
11915        (AddConstant <= 0 && CompConstant >= 0 &&
11916         CompConstant <= AddConstant + MaxUInt))
11917      return true;
11918    break;
11919  case AArch64CC::EQ:
11920  case AArch64CC::NE:
11921    if ((AddConstant > 0 && CompConstant < 0) ||
11922        (AddConstant < 0 && CompConstant >= 0 &&
11923         CompConstant < AddConstant + MaxUInt) ||
11924        (AddConstant >= 0 && CompConstant >= 0 &&
11925         CompConstant >= AddConstant) ||
11926        (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11927      return true;
11928    break;
11929  case AArch64CC::VS:
11930  case AArch64CC::VC:
11931  case AArch64CC::AL:
11932  case AArch64CC::NV:
11933    return true;
11934  case AArch64CC::Invalid:
11935    break;
11936  }
11937
11938  return false;
11939}
11940
11941static
11942SDValue performCONDCombine(SDNode *N,
11943                           TargetLowering::DAGCombinerInfo &DCI,
11944                           SelectionDAG &DAG, unsigned CCIndex,
11945                           unsigned CmpIndex) {
11946  unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11947  SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11948  unsigned CondOpcode = SubsNode->getOpcode();
11949
11950  if (CondOpcode != AArch64ISD::SUBS)
11951    return SDValue();
11952
11953  // There is a SUBS feeding this condition. Is it fed by a mask we can
11954  // use?
11955
11956  SDNode *AndNode = SubsNode->getOperand(0).getNode();
11957  unsigned MaskBits = 0;
11958
11959  if (AndNode->getOpcode() != ISD::AND)
11960    return SDValue();
11961
11962  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11963    uint32_t CNV = CN->getZExtValue();
11964    if (CNV == 255)
11965      MaskBits = 8;
11966    else if (CNV == 65535)
11967      MaskBits = 16;
11968  }
11969
11970  if (!MaskBits)
11971    return SDValue();
11972
11973  SDValue AddValue = AndNode->getOperand(0);
11974
11975  if (AddValue.getOpcode() != ISD::ADD)
11976    return SDValue();
11977
11978  // The basic dag structure is correct, grab the inputs and validate them.
11979
11980  SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11981  SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11982  SDValue SubsInputValue = SubsNode->getOperand(1);
11983
11984  // The mask is present and the provenance of all the values is a smaller type,
11985  // lets see if the mask is superfluous.
11986
11987  if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11988      !isa<ConstantSDNode>(SubsInputValue.getNode()))
11989    return SDValue();
11990
11991  ISD::LoadExtType ExtType;
11992
11993  if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11994      !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11995      !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11996    return SDValue();
11997
11998  if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11999                cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
12000                cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
12001    return SDValue();
12002
12003  // The AND is not necessary, remove it.
12004
12005  SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
12006                               SubsNode->getValueType(1));
12007  SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
12008
12009  SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
12010  DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
12011
12012  return SDValue(N, 0);
12013}
12014
12015// Optimize compare with zero and branch.
12016static SDValue performBRCONDCombine(SDNode *N,
12017                                    TargetLowering::DAGCombinerInfo &DCI,
12018                                    SelectionDAG &DAG) {
12019  MachineFunction &MF = DAG.getMachineFunction();
12020  // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
12021  // will not be produced, as they are conditional branch instructions that do
12022  // not set flags.
12023  if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
12024    return SDValue();
12025
12026  if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
12027    N = NV.getNode();
12028  SDValue Chain = N->getOperand(0);
12029  SDValue Dest = N->getOperand(1);
12030  SDValue CCVal = N->getOperand(2);
12031  SDValue Cmp = N->getOperand(3);
12032
12033  assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
12034  unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
12035  if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
12036    return SDValue();
12037
12038  unsigned CmpOpc = Cmp.getOpcode();
12039  if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
12040    return SDValue();
12041
12042  // Only attempt folding if there is only one use of the flag and no use of the
12043  // value.
12044  if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
12045    return SDValue();
12046
12047  SDValue LHS = Cmp.getOperand(0);
12048  SDValue RHS = Cmp.getOperand(1);
12049
12050  assert(LHS.getValueType() == RHS.getValueType() &&
12051         "Expected the value type to be the same for both operands!");
12052  if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
12053    return SDValue();
12054
12055  if (isNullConstant(LHS))
12056    std::swap(LHS, RHS);
12057
12058  if (!isNullConstant(RHS))
12059    return SDValue();
12060
12061  if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
12062      LHS.getOpcode() == ISD::SRL)
12063    return SDValue();
12064
12065  // Fold the compare into the branch instruction.
12066  SDValue BR;
12067  if (CC == AArch64CC::EQ)
12068    BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12069  else
12070    BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12071
12072  // Do not add new nodes to DAG combiner worklist.
12073  DCI.CombineTo(N, BR, false);
12074
12075  return SDValue();
12076}
12077
12078// Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
12079// as well as whether the test should be inverted.  This code is required to
12080// catch these cases (as opposed to standard dag combines) because
12081// AArch64ISD::TBZ is matched during legalization.
12082static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
12083                                 SelectionDAG &DAG) {
12084
12085  if (!Op->hasOneUse())
12086    return Op;
12087
12088  // We don't handle undef/constant-fold cases below, as they should have
12089  // already been taken care of (e.g. and of 0, test of undefined shifted bits,
12090  // etc.)
12091
12092  // (tbz (trunc x), b) -> (tbz x, b)
12093  // This case is just here to enable more of the below cases to be caught.
12094  if (Op->getOpcode() == ISD::TRUNCATE &&
12095      Bit < Op->getValueType(0).getSizeInBits()) {
12096    return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12097  }
12098
12099  // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
12100  if (Op->getOpcode() == ISD::ANY_EXTEND &&
12101      Bit < Op->getOperand(0).getValueSizeInBits()) {
12102    return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12103  }
12104
12105  if (Op->getNumOperands() != 2)
12106    return Op;
12107
12108  auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12109  if (!C)
12110    return Op;
12111
12112  switch (Op->getOpcode()) {
12113  default:
12114    return Op;
12115
12116  // (tbz (and x, m), b) -> (tbz x, b)
12117  case ISD::AND:
12118    if ((C->getZExtValue() >> Bit) & 1)
12119      return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12120    return Op;
12121
12122  // (tbz (shl x, c), b) -> (tbz x, b-c)
12123  case ISD::SHL:
12124    if (C->getZExtValue() <= Bit &&
12125        (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12126      Bit = Bit - C->getZExtValue();
12127      return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12128    }
12129    return Op;
12130
12131  // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
12132  case ISD::SRA:
12133    Bit = Bit + C->getZExtValue();
12134    if (Bit >= Op->getValueType(0).getSizeInBits())
12135      Bit = Op->getValueType(0).getSizeInBits() - 1;
12136    return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12137
12138  // (tbz (srl x, c), b) -> (tbz x, b+c)
12139  case ISD::SRL:
12140    if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12141      Bit = Bit + C->getZExtValue();
12142      return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12143    }
12144    return Op;
12145
12146  // (tbz (xor x, -1), b) -> (tbnz x, b)
12147  case ISD::XOR:
12148    if ((C->getZExtValue() >> Bit) & 1)
12149      Invert = !Invert;
12150    return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12151  }
12152}
12153
12154// Optimize test single bit zero/non-zero and branch.
12155static SDValue performTBZCombine(SDNode *N,
12156                                 TargetLowering::DAGCombinerInfo &DCI,
12157                                 SelectionDAG &DAG) {
12158  unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12159  bool Invert = false;
12160  SDValue TestSrc = N->getOperand(1);
12161  SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
12162
12163  if (TestSrc == NewTestSrc)
12164    return SDValue();
12165
12166  unsigned NewOpc = N->getOpcode();
12167  if (Invert) {
12168    if (NewOpc == AArch64ISD::TBZ)
12169      NewOpc = AArch64ISD::TBNZ;
12170    else {
12171      assert(NewOpc == AArch64ISD::TBNZ);
12172      NewOpc = AArch64ISD::TBZ;
12173    }
12174  }
12175
12176  SDLoc DL(N);
12177  return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
12178                     DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
12179}
12180
12181// vselect (v1i1 setcc) ->
12182//     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
12183// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
12184// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
12185// such VSELECT.
12186static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
12187  SDValue N0 = N->getOperand(0);
12188  EVT CCVT = N0.getValueType();
12189
12190  if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
12191      CCVT.getVectorElementType() != MVT::i1)
12192    return SDValue();
12193
12194  EVT ResVT = N->getValueType(0);
12195  EVT CmpVT = N0.getOperand(0).getValueType();
12196  // Only combine when the result type is of the same size as the compared
12197  // operands.
12198  if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
12199    return SDValue();
12200
12201  SDValue IfTrue = N->getOperand(1);
12202  SDValue IfFalse = N->getOperand(2);
12203  SDValue SetCC =
12204      DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
12205                   N0.getOperand(0), N0.getOperand(1),
12206                   cast<CondCodeSDNode>(N0.getOperand(2))->get());
12207  return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
12208                     IfTrue, IfFalse);
12209}
12210
12211/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
12212/// the compare-mask instructions rather than going via NZCV, even if LHS and
12213/// RHS are really scalar. This replaces any scalar setcc in the above pattern
12214/// with a vector one followed by a DUP shuffle on the result.
12215static SDValue performSelectCombine(SDNode *N,
12216                                    TargetLowering::DAGCombinerInfo &DCI) {
12217  SelectionDAG &DAG = DCI.DAG;
12218  SDValue N0 = N->getOperand(0);
12219  EVT ResVT = N->getValueType(0);
12220
12221  if (N0.getOpcode() != ISD::SETCC)
12222    return SDValue();
12223
12224  // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
12225  // scalar SetCCResultType. We also don't expect vectors, because we assume
12226  // that selects fed by vector SETCCs are canonicalized to VSELECT.
12227  assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
12228         "Scalar-SETCC feeding SELECT has unexpected result type!");
12229
12230  // If NumMaskElts == 0, the comparison is larger than select result. The
12231  // largest real NEON comparison is 64-bits per lane, which means the result is
12232  // at most 32-bits and an illegal vector. Just bail out for now.
12233  EVT SrcVT = N0.getOperand(0).getValueType();
12234
12235  // Don't try to do this optimization when the setcc itself has i1 operands.
12236  // There are no legal vectors of i1, so this would be pointless.
12237  if (SrcVT == MVT::i1)
12238    return SDValue();
12239
12240  int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
12241  if (!ResVT.isVector() || NumMaskElts == 0)
12242    return SDValue();
12243
12244  SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
12245  EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
12246
12247  // Also bail out if the vector CCVT isn't the same size as ResVT.
12248  // This can happen if the SETCC operand size doesn't divide the ResVT size
12249  // (e.g., f64 vs v3f32).
12250  if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
12251    return SDValue();
12252
12253  // Make sure we didn't create illegal types, if we're not supposed to.
12254  assert(DCI.isBeforeLegalize() ||
12255         DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
12256
12257  // First perform a vector comparison, where lane 0 is the one we're interested
12258  // in.
12259  SDLoc DL(N0);
12260  SDValue LHS =
12261      DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
12262  SDValue RHS =
12263      DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
12264  SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
12265
12266  // Now duplicate the comparison mask we want across all other lanes.
12267  SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
12268  SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
12269  Mask = DAG.getNode(ISD::BITCAST, DL,
12270                     ResVT.changeVectorElementTypeToInteger(), Mask);
12271
12272  return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
12273}
12274
12275/// Get rid of unnecessary NVCASTs (that don't change the type).
12276static SDValue performNVCASTCombine(SDNode *N) {
12277  if (N->getValueType(0) == N->getOperand(0).getValueType())
12278    return N->getOperand(0);
12279
12280  return SDValue();
12281}
12282
12283// If all users of the globaladdr are of the form (globaladdr + constant), find
12284// the smallest constant, fold it into the globaladdr's offset and rewrite the
12285// globaladdr as (globaladdr + constant) - constant.
12286static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
12287                                           const AArch64Subtarget *Subtarget,
12288                                           const TargetMachine &TM) {
12289  auto *GN = cast<GlobalAddressSDNode>(N);
12290  if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
12291      AArch64II::MO_NO_FLAG)
12292    return SDValue();
12293
12294  uint64_t MinOffset = -1ull;
12295  for (SDNode *N : GN->uses()) {
12296    if (N->getOpcode() != ISD::ADD)
12297      return SDValue();
12298    auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
12299    if (!C)
12300      C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12301    if (!C)
12302      return SDValue();
12303    MinOffset = std::min(MinOffset, C->getZExtValue());
12304  }
12305  uint64_t Offset = MinOffset + GN->getOffset();
12306
12307  // Require that the new offset is larger than the existing one. Otherwise, we
12308  // can end up oscillating between two possible DAGs, for example,
12309  // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
12310  if (Offset <= uint64_t(GN->getOffset()))
12311    return SDValue();
12312
12313  // Check whether folding this offset is legal. It must not go out of bounds of
12314  // the referenced object to avoid violating the code model, and must be
12315  // smaller than 2^21 because this is the largest offset expressible in all
12316  // object formats.
12317  //
12318  // This check also prevents us from folding negative offsets, which will end
12319  // up being treated in the same way as large positive ones. They could also
12320  // cause code model violations, and aren't really common enough to matter.
12321  if (Offset >= (1 << 21))
12322    return SDValue();
12323
12324  const GlobalValue *GV = GN->getGlobal();
12325  Type *T = GV->getValueType();
12326  if (!T->isSized() ||
12327      Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
12328    return SDValue();
12329
12330  SDLoc DL(GN);
12331  SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
12332  return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
12333                     DAG.getConstant(MinOffset, DL, MVT::i64));
12334}
12335
12336// Returns an SVE type that ContentTy can be trivially sign or zero extended
12337// into.
12338static MVT getSVEContainerType(EVT ContentTy) {
12339  assert(ContentTy.isSimple() && "No SVE containers for extended types");
12340
12341  switch (ContentTy.getSimpleVT().SimpleTy) {
12342  default:
12343    llvm_unreachable("No known SVE container for this MVT type");
12344  case MVT::nxv2i8:
12345  case MVT::nxv2i16:
12346  case MVT::nxv2i32:
12347  case MVT::nxv2i64:
12348  case MVT::nxv2f32:
12349  case MVT::nxv2f64:
12350    return MVT::nxv2i64;
12351  case MVT::nxv4i8:
12352  case MVT::nxv4i16:
12353  case MVT::nxv4i32:
12354  case MVT::nxv4f32:
12355    return MVT::nxv4i32;
12356  }
12357}
12358
12359static SDValue performST1ScatterCombine(SDNode *N, SelectionDAG &DAG,
12360                                        unsigned Opcode,
12361                                        bool OnlyPackedOffsets = true) {
12362  const SDValue Src = N->getOperand(2);
12363  const EVT SrcVT = Src->getValueType(0);
12364  assert(SrcVT.isScalableVector() &&
12365         "Scatter stores are only possible for SVE vectors");
12366
12367  SDLoc DL(N);
12368  MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
12369
12370  // Make sure that source data will fit into an SVE register
12371  if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12372    return SDValue();
12373
12374  // For FPs, ACLE only supports _packed_ single and double precision types.
12375  if (SrcElVT.isFloatingPoint())
12376    if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
12377      return SDValue();
12378
12379  // Depending on the addressing mode, this is either a pointer or a vector of
12380  // pointers (that fits into one register)
12381  const SDValue Base = N->getOperand(4);
12382  // Depending on the addressing mode, this is either a single offset or a
12383  // vector of offsets  (that fits into one register)
12384  SDValue Offset = N->getOperand(5);
12385
12386  auto &TLI = DAG.getTargetLoweringInfo();
12387  if (!TLI.isTypeLegal(Base.getValueType()))
12388    return SDValue();
12389
12390  // Some scatter store variants allow unpacked offsets, but only as nxv2i32
12391  // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12392  // nxv2i64. Legalize accordingly.
12393  if (!OnlyPackedOffsets &&
12394      Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12395    Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12396
12397  if (!TLI.isTypeLegal(Offset.getValueType()))
12398    return SDValue();
12399
12400  // Source value type that is representable in hardware
12401  EVT HwSrcVt = getSVEContainerType(SrcVT);
12402
12403  // Keep the original type of the input data to store - this is needed to
12404  // differentiate between ST1B, ST1H, ST1W and ST1D. For FP values we want the
12405  // integer equivalent, so just use HwSrcVt.
12406  SDValue InputVT = DAG.getValueType(SrcVT);
12407  if (SrcVT.isFloatingPoint())
12408    InputVT = DAG.getValueType(HwSrcVt);
12409
12410  SDVTList VTs = DAG.getVTList(MVT::Other);
12411  SDValue SrcNew;
12412
12413  if (Src.getValueType().isFloatingPoint())
12414    SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
12415  else
12416    SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
12417
12418  SDValue Ops[] = {N->getOperand(0), // Chain
12419                   SrcNew,
12420                   N->getOperand(3), // Pg
12421                   Base,
12422                   Offset,
12423                   InputVT};
12424
12425  return DAG.getNode(Opcode, DL, VTs, Ops);
12426}
12427
12428static SDValue performLD1GatherCombine(SDNode *N, SelectionDAG &DAG,
12429                                       unsigned Opcode,
12430                                       bool OnlyPackedOffsets = true) {
12431  EVT RetVT = N->getValueType(0);
12432  assert(RetVT.isScalableVector() &&
12433         "Gather loads are only possible for SVE vectors");
12434  SDLoc DL(N);
12435
12436  if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12437    return SDValue();
12438
12439  // Depending on the addressing mode, this is either a pointer or a vector of
12440  // pointers (that fits into one register)
12441  const SDValue Base = N->getOperand(3);
12442  // Depending on the addressing mode, this is either a single offset or a
12443  // vector of offsets  (that fits into one register)
12444  SDValue Offset = N->getOperand(4);
12445
12446  auto &TLI = DAG.getTargetLoweringInfo();
12447  if (!TLI.isTypeLegal(Base.getValueType()))
12448    return SDValue();
12449
12450  // Some gather load variants allow unpacked offsets, but only as nxv2i32
12451  // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12452  // nxv2i64. Legalize accordingly.
12453  if (!OnlyPackedOffsets &&
12454      Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12455    Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12456
12457  // Return value type that is representable in hardware
12458  EVT HwRetVt = getSVEContainerType(RetVT);
12459
12460  // Keep the original output value type around - this will better inform
12461  // optimisations (e.g. instruction folding when load is followed by
12462  // zext/sext). This will only be used for ints, so the value for FPs
12463  // doesn't matter.
12464  SDValue OutVT = DAG.getValueType(RetVT);
12465  if (RetVT.isFloatingPoint())
12466    OutVT = DAG.getValueType(HwRetVt);
12467
12468  SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
12469  SDValue Ops[] = {N->getOperand(0), // Chain
12470                   N->getOperand(2), // Pg
12471                   Base, Offset, OutVT};
12472
12473  SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
12474  SDValue LoadChain = SDValue(Load.getNode(), 1);
12475
12476  if (RetVT.isInteger() && (RetVT != HwRetVt))
12477    Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
12478
12479  // If the original return value was FP, bitcast accordingly. Doing it here
12480  // means that we can avoid adding TableGen patterns for FPs.
12481  if (RetVT.isFloatingPoint())
12482    Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
12483
12484  return DAG.getMergeValues({Load, LoadChain}, DL);
12485}
12486
12487
12488static SDValue
12489performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12490                              SelectionDAG &DAG) {
12491  if (DCI.isBeforeLegalizeOps())
12492    return SDValue();
12493
12494  SDValue Src = N->getOperand(0);
12495  unsigned Opc = Src->getOpcode();
12496
12497  // Gather load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
12498  // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
12499  unsigned NewOpc;
12500  switch (Opc) {
12501  case AArch64ISD::GLD1:
12502    NewOpc = AArch64ISD::GLD1S;
12503    break;
12504  case AArch64ISD::GLD1_SCALED:
12505    NewOpc = AArch64ISD::GLD1S_SCALED;
12506    break;
12507  case AArch64ISD::GLD1_SXTW:
12508    NewOpc = AArch64ISD::GLD1S_SXTW;
12509    break;
12510  case AArch64ISD::GLD1_SXTW_SCALED:
12511    NewOpc = AArch64ISD::GLD1S_SXTW_SCALED;
12512    break;
12513  case AArch64ISD::GLD1_UXTW:
12514    NewOpc = AArch64ISD::GLD1S_UXTW;
12515    break;
12516  case AArch64ISD::GLD1_UXTW_SCALED:
12517    NewOpc = AArch64ISD::GLD1S_UXTW_SCALED;
12518    break;
12519  case AArch64ISD::GLD1_IMM:
12520    NewOpc = AArch64ISD::GLD1S_IMM;
12521    break;
12522  default:
12523    return SDValue();
12524  }
12525
12526  EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12527  EVT GLD1SrcMemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
12528
12529  if ((SignExtSrcVT != GLD1SrcMemVT) || !Src.hasOneUse())
12530    return SDValue();
12531
12532  EVT DstVT = N->getValueType(0);
12533  SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
12534  SDValue Ops[] = {Src->getOperand(0), Src->getOperand(1), Src->getOperand(2),
12535                   Src->getOperand(3), Src->getOperand(4)};
12536
12537  SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
12538  DCI.CombineTo(N, ExtLoad);
12539  DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
12540
12541  // Return N so it doesn't get rechecked
12542  return SDValue(N, 0);
12543}
12544
12545SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
12546                                                 DAGCombinerInfo &DCI) const {
12547  SelectionDAG &DAG = DCI.DAG;
12548  switch (N->getOpcode()) {
12549  default:
12550    LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
12551    break;
12552  case ISD::ADD:
12553  case ISD::SUB:
12554    return performAddSubLongCombine(N, DCI, DAG);
12555  case ISD::XOR:
12556    return performXorCombine(N, DAG, DCI, Subtarget);
12557  case ISD::MUL:
12558    return performMulCombine(N, DAG, DCI, Subtarget);
12559  case ISD::SINT_TO_FP:
12560  case ISD::UINT_TO_FP:
12561    return performIntToFpCombine(N, DAG, Subtarget);
12562  case ISD::FP_TO_SINT:
12563  case ISD::FP_TO_UINT:
12564    return performFpToIntCombine(N, DAG, DCI, Subtarget);
12565  case ISD::FDIV:
12566    return performFDivCombine(N, DAG, DCI, Subtarget);
12567  case ISD::OR:
12568    return performORCombine(N, DCI, Subtarget);
12569  case ISD::AND:
12570    return performANDCombine(N, DCI);
12571  case ISD::SRL:
12572    return performSRLCombine(N, DCI);
12573  case ISD::INTRINSIC_WO_CHAIN:
12574    return performIntrinsicCombine(N, DCI, Subtarget);
12575  case ISD::ANY_EXTEND:
12576  case ISD::ZERO_EXTEND:
12577  case ISD::SIGN_EXTEND:
12578    return performExtendCombine(N, DCI, DAG);
12579  case ISD::SIGN_EXTEND_INREG:
12580    return performSignExtendInRegCombine(N, DCI, DAG);
12581  case ISD::CONCAT_VECTORS:
12582    return performConcatVectorsCombine(N, DCI, DAG);
12583  case ISD::SELECT:
12584    return performSelectCombine(N, DCI);
12585  case ISD::VSELECT:
12586    return performVSelectCombine(N, DCI.DAG);
12587  case ISD::LOAD:
12588    if (performTBISimplification(N->getOperand(1), DCI, DAG))
12589      return SDValue(N, 0);
12590    break;
12591  case ISD::STORE:
12592    return performSTORECombine(N, DCI, DAG, Subtarget);
12593  case AArch64ISD::BRCOND:
12594    return performBRCONDCombine(N, DCI, DAG);
12595  case AArch64ISD::TBNZ:
12596  case AArch64ISD::TBZ:
12597    return performTBZCombine(N, DCI, DAG);
12598  case AArch64ISD::CSEL:
12599    return performCONDCombine(N, DCI, DAG, 2, 3);
12600  case AArch64ISD::DUP:
12601    return performPostLD1Combine(N, DCI, false);
12602  case AArch64ISD::NVCAST:
12603    return performNVCASTCombine(N);
12604  case ISD::INSERT_VECTOR_ELT:
12605    return performPostLD1Combine(N, DCI, true);
12606  case ISD::INTRINSIC_VOID:
12607  case ISD::INTRINSIC_W_CHAIN:
12608    switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12609    case Intrinsic::aarch64_neon_ld2:
12610    case Intrinsic::aarch64_neon_ld3:
12611    case Intrinsic::aarch64_neon_ld4:
12612    case Intrinsic::aarch64_neon_ld1x2:
12613    case Intrinsic::aarch64_neon_ld1x3:
12614    case Intrinsic::aarch64_neon_ld1x4:
12615    case Intrinsic::aarch64_neon_ld2lane:
12616    case Intrinsic::aarch64_neon_ld3lane:
12617    case Intrinsic::aarch64_neon_ld4lane:
12618    case Intrinsic::aarch64_neon_ld2r:
12619    case Intrinsic::aarch64_neon_ld3r:
12620    case Intrinsic::aarch64_neon_ld4r:
12621    case Intrinsic::aarch64_neon_st2:
12622    case Intrinsic::aarch64_neon_st3:
12623    case Intrinsic::aarch64_neon_st4:
12624    case Intrinsic::aarch64_neon_st1x2:
12625    case Intrinsic::aarch64_neon_st1x3:
12626    case Intrinsic::aarch64_neon_st1x4:
12627    case Intrinsic::aarch64_neon_st2lane:
12628    case Intrinsic::aarch64_neon_st3lane:
12629    case Intrinsic::aarch64_neon_st4lane:
12630      return performNEONPostLDSTCombine(N, DCI, DAG);
12631    case Intrinsic::aarch64_sve_ldnt1:
12632      return performLDNT1Combine(N, DAG);
12633    case Intrinsic::aarch64_sve_stnt1:
12634      return performSTNT1Combine(N, DAG);
12635    case Intrinsic::aarch64_sve_ld1_gather:
12636      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1);
12637    case Intrinsic::aarch64_sve_ld1_gather_index:
12638      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SCALED);
12639    case Intrinsic::aarch64_sve_ld1_gather_sxtw:
12640      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW,
12641                                      /*OnlyPackedOffsets=*/false);
12642    case Intrinsic::aarch64_sve_ld1_gather_uxtw:
12643      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW,
12644                                      /*OnlyPackedOffsets=*/false);
12645    case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
12646      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED,
12647                                      /*OnlyPackedOffsets=*/false);
12648    case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
12649      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED,
12650                                      /*OnlyPackedOffsets=*/false);
12651    case Intrinsic::aarch64_sve_ld1_gather_imm:
12652      return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_IMM);
12653    case Intrinsic::aarch64_sve_st1_scatter:
12654      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1);
12655    case Intrinsic::aarch64_sve_st1_scatter_index:
12656      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SCALED);
12657    case Intrinsic::aarch64_sve_st1_scatter_sxtw:
12658      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW,
12659                                      /*OnlyPackedOffsets=*/false);
12660    case Intrinsic::aarch64_sve_st1_scatter_uxtw:
12661      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW,
12662                                      /*OnlyPackedOffsets=*/false);
12663    case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
12664      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED,
12665                                      /*OnlyPackedOffsets=*/false);
12666    case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
12667      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED,
12668                                      /*OnlyPackedOffsets=*/false);
12669    case Intrinsic::aarch64_sve_st1_scatter_imm:
12670      return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_IMM);
12671    default:
12672      break;
12673    }
12674    break;
12675  case ISD::GlobalAddress:
12676    return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
12677  }
12678  return SDValue();
12679}
12680
12681// Check if the return value is used as only a return value, as otherwise
12682// we can't perform a tail-call. In particular, we need to check for
12683// target ISD nodes that are returns and any other "odd" constructs
12684// that the generic analysis code won't necessarily catch.
12685bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
12686                                               SDValue &Chain) const {
12687  if (N->getNumValues() != 1)
12688    return false;
12689  if (!N->hasNUsesOfValue(1, 0))
12690    return false;
12691
12692  SDValue TCChain = Chain;
12693  SDNode *Copy = *N->use_begin();
12694  if (Copy->getOpcode() == ISD::CopyToReg) {
12695    // If the copy has a glue operand, we conservatively assume it isn't safe to
12696    // perform a tail call.
12697    if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
12698        MVT::Glue)
12699      return false;
12700    TCChain = Copy->getOperand(0);
12701  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
12702    return false;
12703
12704  bool HasRet = false;
12705  for (SDNode *Node : Copy->uses()) {
12706    if (Node->getOpcode() != AArch64ISD::RET_FLAG)
12707      return false;
12708    HasRet = true;
12709  }
12710
12711  if (!HasRet)
12712    return false;
12713
12714  Chain = TCChain;
12715  return true;
12716}
12717
12718// Return whether the an instruction can potentially be optimized to a tail
12719// call. This will cause the optimizers to attempt to move, or duplicate,
12720// return instructions to help enable tail call optimizations for this
12721// instruction.
12722bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
12723  return CI->isTailCall();
12724}
12725
12726bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
12727                                                   SDValue &Offset,
12728                                                   ISD::MemIndexedMode &AM,
12729                                                   bool &IsInc,
12730                                                   SelectionDAG &DAG) const {
12731  if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
12732    return false;
12733
12734  Base = Op->getOperand(0);
12735  // All of the indexed addressing mode instructions take a signed
12736  // 9 bit immediate offset.
12737  if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
12738    int64_t RHSC = RHS->getSExtValue();
12739    if (Op->getOpcode() == ISD::SUB)
12740      RHSC = -(uint64_t)RHSC;
12741    if (!isInt<9>(RHSC))
12742      return false;
12743    IsInc = (Op->getOpcode() == ISD::ADD);
12744    Offset = Op->getOperand(1);
12745    return true;
12746  }
12747  return false;
12748}
12749
12750bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12751                                                      SDValue &Offset,
12752                                                      ISD::MemIndexedMode &AM,
12753                                                      SelectionDAG &DAG) const {
12754  EVT VT;
12755  SDValue Ptr;
12756  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12757    VT = LD->getMemoryVT();
12758    Ptr = LD->getBasePtr();
12759  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12760    VT = ST->getMemoryVT();
12761    Ptr = ST->getBasePtr();
12762  } else
12763    return false;
12764
12765  bool IsInc;
12766  if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
12767    return false;
12768  AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
12769  return true;
12770}
12771
12772bool AArch64TargetLowering::getPostIndexedAddressParts(
12773    SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
12774    ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
12775  EVT VT;
12776  SDValue Ptr;
12777  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12778    VT = LD->getMemoryVT();
12779    Ptr = LD->getBasePtr();
12780  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12781    VT = ST->getMemoryVT();
12782    Ptr = ST->getBasePtr();
12783  } else
12784    return false;
12785
12786  bool IsInc;
12787  if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
12788    return false;
12789  // Post-indexing updates the base, so it's not a valid transform
12790  // if that's not the same as the load's pointer.
12791  if (Ptr != Base)
12792    return false;
12793  AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
12794  return true;
12795}
12796
12797static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
12798                                  SelectionDAG &DAG) {
12799  SDLoc DL(N);
12800  SDValue Op = N->getOperand(0);
12801
12802  if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
12803    return;
12804
12805  Op = SDValue(
12806      DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
12807                         DAG.getUNDEF(MVT::i32), Op,
12808                         DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
12809      0);
12810  Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
12811  Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
12812}
12813
12814static void ReplaceReductionResults(SDNode *N,
12815                                    SmallVectorImpl<SDValue> &Results,
12816                                    SelectionDAG &DAG, unsigned InterOp,
12817                                    unsigned AcrossOp) {
12818  EVT LoVT, HiVT;
12819  SDValue Lo, Hi;
12820  SDLoc dl(N);
12821  std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
12822  std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
12823  SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
12824  SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
12825  Results.push_back(SplitVal);
12826}
12827
12828static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
12829  SDLoc DL(N);
12830  SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
12831  SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
12832                           DAG.getNode(ISD::SRL, DL, MVT::i128, N,
12833                                       DAG.getConstant(64, DL, MVT::i64)));
12834  return std::make_pair(Lo, Hi);
12835}
12836
12837// Create an even/odd pair of X registers holding integer value V.
12838static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
12839  SDLoc dl(V.getNode());
12840  SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
12841  SDValue VHi = DAG.getAnyExtOrTrunc(
12842      DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
12843      dl, MVT::i64);
12844  if (DAG.getDataLayout().isBigEndian())
12845    std::swap (VLo, VHi);
12846  SDValue RegClass =
12847      DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
12848  SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
12849  SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
12850  const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
12851  return SDValue(
12852      DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
12853}
12854
12855static void ReplaceCMP_SWAP_128Results(SDNode *N,
12856                                       SmallVectorImpl<SDValue> &Results,
12857                                       SelectionDAG &DAG,
12858                                       const AArch64Subtarget *Subtarget) {
12859  assert(N->getValueType(0) == MVT::i128 &&
12860         "AtomicCmpSwap on types less than 128 should be legal");
12861
12862  if (Subtarget->hasLSE()) {
12863    // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
12864    // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
12865    SDValue Ops[] = {
12866        createGPRPairNode(DAG, N->getOperand(2)), // Compare value
12867        createGPRPairNode(DAG, N->getOperand(3)), // Store value
12868        N->getOperand(1), // Ptr
12869        N->getOperand(0), // Chain in
12870    };
12871
12872    MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12873
12874    unsigned Opcode;
12875    switch (MemOp->getOrdering()) {
12876    case AtomicOrdering::Monotonic:
12877      Opcode = AArch64::CASPX;
12878      break;
12879    case AtomicOrdering::Acquire:
12880      Opcode = AArch64::CASPAX;
12881      break;
12882    case AtomicOrdering::Release:
12883      Opcode = AArch64::CASPLX;
12884      break;
12885    case AtomicOrdering::AcquireRelease:
12886    case AtomicOrdering::SequentiallyConsistent:
12887      Opcode = AArch64::CASPALX;
12888      break;
12889    default:
12890      llvm_unreachable("Unexpected ordering!");
12891    }
12892
12893    MachineSDNode *CmpSwap = DAG.getMachineNode(
12894        Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
12895    DAG.setNodeMemRefs(CmpSwap, {MemOp});
12896
12897    unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
12898    if (DAG.getDataLayout().isBigEndian())
12899      std::swap(SubReg1, SubReg2);
12900    Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
12901                                                 SDValue(CmpSwap, 0)));
12902    Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
12903                                                 SDValue(CmpSwap, 0)));
12904    Results.push_back(SDValue(CmpSwap, 1)); // Chain out
12905    return;
12906  }
12907
12908  auto Desired = splitInt128(N->getOperand(2), DAG);
12909  auto New = splitInt128(N->getOperand(3), DAG);
12910  SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
12911                   New.first,        New.second,    N->getOperand(0)};
12912  SDNode *CmpSwap = DAG.getMachineNode(
12913      AArch64::CMP_SWAP_128, SDLoc(N),
12914      DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
12915
12916  MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12917  DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
12918
12919  Results.push_back(SDValue(CmpSwap, 0));
12920  Results.push_back(SDValue(CmpSwap, 1));
12921  Results.push_back(SDValue(CmpSwap, 3));
12922}
12923
12924void AArch64TargetLowering::ReplaceNodeResults(
12925    SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
12926  switch (N->getOpcode()) {
12927  default:
12928    llvm_unreachable("Don't know how to custom expand this");
12929  case ISD::BITCAST:
12930    ReplaceBITCASTResults(N, Results, DAG);
12931    return;
12932  case ISD::VECREDUCE_ADD:
12933  case ISD::VECREDUCE_SMAX:
12934  case ISD::VECREDUCE_SMIN:
12935  case ISD::VECREDUCE_UMAX:
12936  case ISD::VECREDUCE_UMIN:
12937    Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
12938    return;
12939
12940  case AArch64ISD::SADDV:
12941    ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
12942    return;
12943  case AArch64ISD::UADDV:
12944    ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
12945    return;
12946  case AArch64ISD::SMINV:
12947    ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
12948    return;
12949  case AArch64ISD::UMINV:
12950    ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
12951    return;
12952  case AArch64ISD::SMAXV:
12953    ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
12954    return;
12955  case AArch64ISD::UMAXV:
12956    ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
12957    return;
12958  case ISD::FP_TO_UINT:
12959  case ISD::FP_TO_SINT:
12960    assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
12961    // Let normal code take care of it by not adding anything to Results.
12962    return;
12963  case ISD::ATOMIC_CMP_SWAP:
12964    ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
12965    return;
12966  case ISD::LOAD: {
12967    assert(SDValue(N, 0).getValueType() == MVT::i128 &&
12968           "unexpected load's value type");
12969    LoadSDNode *LoadNode = cast<LoadSDNode>(N);
12970    if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
12971      // Non-volatile loads are optimized later in AArch64's load/store
12972      // optimizer.
12973      return;
12974    }
12975
12976    SDValue Result = DAG.getMemIntrinsicNode(
12977        AArch64ISD::LDP, SDLoc(N),
12978        DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
12979        {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
12980        LoadNode->getMemOperand());
12981
12982    SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
12983                               Result.getValue(0), Result.getValue(1));
12984    Results.append({Pair, Result.getValue(2) /* Chain */});
12985    return;
12986  }
12987  case ISD::INTRINSIC_WO_CHAIN: {
12988    EVT VT = N->getValueType(0);
12989    assert((VT == MVT::i8 || VT == MVT::i16) &&
12990           "custom lowering for unexpected type");
12991
12992    ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
12993    Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12994    switch (IntID) {
12995    default:
12996      return;
12997    case Intrinsic::aarch64_sve_clasta_n: {
12998      SDLoc DL(N);
12999      auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13000      auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
13001                           N->getOperand(1), Op2, N->getOperand(3));
13002      Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13003      return;
13004    }
13005    case Intrinsic::aarch64_sve_clastb_n: {
13006      SDLoc DL(N);
13007      auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13008      auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
13009                           N->getOperand(1), Op2, N->getOperand(3));
13010      Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13011      return;
13012    }
13013    case Intrinsic::aarch64_sve_lasta: {
13014      SDLoc DL(N);
13015      auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
13016                           N->getOperand(1), N->getOperand(2));
13017      Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13018      return;
13019    }
13020    case Intrinsic::aarch64_sve_lastb: {
13021      SDLoc DL(N);
13022      auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
13023                           N->getOperand(1), N->getOperand(2));
13024      Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13025      return;
13026    }
13027    }
13028  }
13029  }
13030}
13031
13032bool AArch64TargetLowering::useLoadStackGuardNode() const {
13033  if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
13034    return TargetLowering::useLoadStackGuardNode();
13035  return true;
13036}
13037
13038unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
13039  // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13040  // reciprocal if there are three or more FDIVs.
13041  return 3;
13042}
13043
13044TargetLoweringBase::LegalizeTypeAction
13045AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
13046  // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
13047  // v4i16, v2i32 instead of to promote.
13048  if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
13049      VT == MVT::v1f32)
13050    return TypeWidenVector;
13051
13052  return TargetLoweringBase::getPreferredVectorAction(VT);
13053}
13054
13055// Loads and stores less than 128-bits are already atomic; ones above that
13056// are doomed anyway, so defer to the default libcall and blame the OS when
13057// things go wrong.
13058bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13059  unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13060  return Size == 128;
13061}
13062
13063// Loads and stores less than 128-bits are already atomic; ones above that
13064// are doomed anyway, so defer to the default libcall and blame the OS when
13065// things go wrong.
13066TargetLowering::AtomicExpansionKind
13067AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13068  unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13069  return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
13070}
13071
13072// For the real atomic operations, we have ldxr/stxr up to 128 bits,
13073TargetLowering::AtomicExpansionKind
13074AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13075  if (AI->isFloatingPointOperation())
13076    return AtomicExpansionKind::CmpXChg;
13077
13078  unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13079  if (Size > 128) return AtomicExpansionKind::None;
13080  // Nand not supported in LSE.
13081  if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
13082  // Leave 128 bits to LLSC.
13083  return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
13084}
13085
13086TargetLowering::AtomicExpansionKind
13087AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
13088    AtomicCmpXchgInst *AI) const {
13089  // If subtarget has LSE, leave cmpxchg intact for codegen.
13090  if (Subtarget->hasLSE())
13091    return AtomicExpansionKind::None;
13092  // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13093  // implement cmpxchg without spilling. If the address being exchanged is also
13094  // on the stack and close enough to the spill slot, this can lead to a
13095  // situation where the monitor always gets cleared and the atomic operation
13096  // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13097  if (getTargetMachine().getOptLevel() == 0)
13098    return AtomicExpansionKind::None;
13099  return AtomicExpansionKind::LLSC;
13100}
13101
13102Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13103                                             AtomicOrdering Ord) const {
13104  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13105  Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13106  bool IsAcquire = isAcquireOrStronger(Ord);
13107
13108  // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
13109  // intrinsic must return {i64, i64} and we have to recombine them into a
13110  // single i128 here.
13111  if (ValTy->getPrimitiveSizeInBits() == 128) {
13112    Intrinsic::ID Int =
13113        IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
13114    Function *Ldxr = Intrinsic::getDeclaration(M, Int);
13115
13116    Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13117    Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
13118
13119    Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13120    Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13121    Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13122    Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13123    return Builder.CreateOr(
13124        Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
13125  }
13126
13127  Type *Tys[] = { Addr->getType() };
13128  Intrinsic::ID Int =
13129      IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
13130  Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
13131
13132  Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
13133
13134  const DataLayout &DL = M->getDataLayout();
13135  IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
13136  Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
13137
13138  return Builder.CreateBitCast(Trunc, EltTy);
13139}
13140
13141void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13142    IRBuilder<> &Builder) const {
13143  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13144  Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
13145}
13146
13147Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
13148                                                   Value *Val, Value *Addr,
13149                                                   AtomicOrdering Ord) const {
13150  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13151  bool IsRelease = isReleaseOrStronger(Ord);
13152
13153  // Since the intrinsics must have legal type, the i128 intrinsics take two
13154  // parameters: "i64, i64". We must marshal Val into the appropriate form
13155  // before the call.
13156  if (Val->getType()->getPrimitiveSizeInBits() == 128) {
13157    Intrinsic::ID Int =
13158        IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
13159    Function *Stxr = Intrinsic::getDeclaration(M, Int);
13160    Type *Int64Ty = Type::getInt64Ty(M->getContext());
13161
13162    Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
13163    Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
13164    Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13165    return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
13166  }
13167
13168  Intrinsic::ID Int =
13169      IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
13170  Type *Tys[] = { Addr->getType() };
13171  Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
13172
13173  const DataLayout &DL = M->getDataLayout();
13174  IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
13175  Val = Builder.CreateBitCast(Val, IntValTy);
13176
13177  return Builder.CreateCall(Stxr,
13178                            {Builder.CreateZExtOrBitCast(
13179                                 Val, Stxr->getFunctionType()->getParamType(0)),
13180                             Addr});
13181}
13182
13183bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
13184    Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13185  return Ty->isArrayTy();
13186}
13187
13188bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
13189                                                            EVT) const {
13190  return false;
13191}
13192
13193static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
13194  Module *M = IRB.GetInsertBlock()->getParent()->getParent();
13195  Function *ThreadPointerFunc =
13196      Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
13197  return IRB.CreatePointerCast(
13198      IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
13199                             Offset),
13200      IRB.getInt8PtrTy()->getPointerTo(0));
13201}
13202
13203Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
13204  // Android provides a fixed TLS slot for the stack cookie. See the definition
13205  // of TLS_SLOT_STACK_GUARD in
13206  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13207  if (Subtarget->isTargetAndroid())
13208    return UseTlsOffset(IRB, 0x28);
13209
13210  // Fuchsia is similar.
13211  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
13212  if (Subtarget->isTargetFuchsia())
13213    return UseTlsOffset(IRB, -0x10);
13214
13215  return TargetLowering::getIRStackGuard(IRB);
13216}
13217
13218void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
13219  // MSVC CRT provides functionalities for stack protection.
13220  if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
13221    // MSVC CRT has a global variable holding security cookie.
13222    M.getOrInsertGlobal("__security_cookie",
13223                        Type::getInt8PtrTy(M.getContext()));
13224
13225    // MSVC CRT has a function to validate security cookie.
13226    FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
13227        "__security_check_cookie", Type::getVoidTy(M.getContext()),
13228        Type::getInt8PtrTy(M.getContext()));
13229    if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
13230      F->setCallingConv(CallingConv::Win64);
13231      F->addAttribute(1, Attribute::AttrKind::InReg);
13232    }
13233    return;
13234  }
13235  TargetLowering::insertSSPDeclarations(M);
13236}
13237
13238Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
13239  // MSVC CRT has a global variable holding security cookie.
13240  if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13241    return M.getGlobalVariable("__security_cookie");
13242  return TargetLowering::getSDagStackGuard(M);
13243}
13244
13245Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
13246  // MSVC CRT has a function to validate security cookie.
13247  if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13248    return M.getFunction("__security_check_cookie");
13249  return TargetLowering::getSSPStackGuardCheck(M);
13250}
13251
13252Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
13253  // Android provides a fixed TLS slot for the SafeStack pointer. See the
13254  // definition of TLS_SLOT_SAFESTACK in
13255  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13256  if (Subtarget->isTargetAndroid())
13257    return UseTlsOffset(IRB, 0x48);
13258
13259  // Fuchsia is similar.
13260  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
13261  if (Subtarget->isTargetFuchsia())
13262    return UseTlsOffset(IRB, -0x8);
13263
13264  return TargetLowering::getSafeStackPointerLocation(IRB);
13265}
13266
13267bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
13268    const Instruction &AndI) const {
13269  // Only sink 'and' mask to cmp use block if it is masking a single bit, since
13270  // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
13271  // may be beneficial to sink in other cases, but we would have to check that
13272  // the cmp would not get folded into the br to form a cbz for these to be
13273  // beneficial.
13274  ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
13275  if (!Mask)
13276    return false;
13277  return Mask->getValue().isPowerOf2();
13278}
13279
13280bool AArch64TargetLowering::
13281    shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13282        SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
13283        unsigned OldShiftOpcode, unsigned NewShiftOpcode,
13284        SelectionDAG &DAG) const {
13285  // Does baseline recommend not to perform the fold by default?
13286  if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13287          X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
13288    return false;
13289  // Else, if this is a vector shift, prefer 'shl'.
13290  return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
13291}
13292
13293bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
13294                                              SDNode *N) const {
13295  if (DAG.getMachineFunction().getFunction().hasMinSize() &&
13296      !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
13297    return false;
13298  return true;
13299}
13300
13301void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13302  // Update IsSplitCSR in AArch64unctionInfo.
13303  AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
13304  AFI->setIsSplitCSR(true);
13305}
13306
13307void AArch64TargetLowering::insertCopiesSplitCSR(
13308    MachineBasicBlock *Entry,
13309    const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13310  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13311  const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13312  if (!IStart)
13313    return;
13314
13315  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13316  MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13317  MachineBasicBlock::iterator MBBI = Entry->begin();
13318  for (const MCPhysReg *I = IStart; *I; ++I) {
13319    const TargetRegisterClass *RC = nullptr;
13320    if (AArch64::GPR64RegClass.contains(*I))
13321      RC = &AArch64::GPR64RegClass;
13322    else if (AArch64::FPR64RegClass.contains(*I))
13323      RC = &AArch64::FPR64RegClass;
13324    else
13325      llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13326
13327    Register NewVR = MRI->createVirtualRegister(RC);
13328    // Create copy from CSR to a virtual register.
13329    // FIXME: this currently does not emit CFI pseudo-instructions, it works
13330    // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13331    // nounwind. If we want to generalize this later, we may need to emit
13332    // CFI pseudo-instructions.
13333    assert(Entry->getParent()->getFunction().hasFnAttribute(
13334               Attribute::NoUnwind) &&
13335           "Function should be nounwind in insertCopiesSplitCSR!");
13336    Entry->addLiveIn(*I);
13337    BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13338        .addReg(*I);
13339
13340    // Insert the copy-back instructions right before the terminator.
13341    for (auto *Exit : Exits)
13342      BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13343              TII->get(TargetOpcode::COPY), *I)
13344          .addReg(NewVR);
13345  }
13346}
13347
13348bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
13349  // Integer division on AArch64 is expensive. However, when aggressively
13350  // optimizing for code size, we prefer to use a div instruction, as it is
13351  // usually smaller than the alternative sequence.
13352  // The exception to this is vector division. Since AArch64 doesn't have vector
13353  // integer division, leaving the division as-is is a loss even in terms of
13354  // size, because it will have to be scalarized, while the alternative code
13355  // sequence can be performed in vector form.
13356  bool OptSize =
13357      Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
13358  return OptSize && !VT.isVector();
13359}
13360
13361bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13362  // We want inc-of-add for scalars and sub-of-not for vectors.
13363  return VT.isScalarInteger();
13364}
13365
13366bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
13367  return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
13368}
13369
13370unsigned
13371AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
13372  if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
13373    return getPointerTy(DL).getSizeInBits();
13374
13375  return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
13376}
13377
13378void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
13379  MF.getFrameInfo().computeMaxCallFrameSize(MF);
13380  TargetLoweringBase::finalizeLowering(MF);
13381}
13382
13383// Unlike X86, we let frame lowering assign offsets to all catch objects.
13384bool AArch64TargetLowering::needsFixedCatchObjects() const {
13385  return false;
13386}
13387