xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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 
93 using namespace llvm;
94 using namespace llvm::PatternMatch;
95 
96 #define DEBUG_TYPE "aarch64-lower"
97 
98 STATISTIC(NumTailCalls, "Number of tail calls");
99 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
119 /// Returns true if VT's elements occupy the lowest bit positions of its
120 /// associated register class without any intervening space.
121 ///
122 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
123 /// same register class, but only nxv8f16 can be treated as a packed vector.
124 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
125   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
126          "Expected legal vector type!");
127   return VT.isFixedLengthVector() ||
128          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
129 }
130 
131 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
132                                              const AArch64Subtarget &STI)
133     : TargetLowering(TM), Subtarget(&STI) {
134   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
135   // we have to make something up. Arbitrarily, choose ZeroOrOne.
136   setBooleanContents(ZeroOrOneBooleanContent);
137   // When comparing vectors the result sets the different elements in the
138   // vector to all-one or all-zero.
139   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
140 
141   // Set up the register classes.
142   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
143   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
144 
145   if (Subtarget->hasFPARMv8()) {
146     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
147     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
148     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
149     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
150     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
151   }
152 
153   if (Subtarget->hasNEON()) {
154     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
155     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
156     // Someone set us up the NEON.
157     addDRTypeForNEON(MVT::v2f32);
158     addDRTypeForNEON(MVT::v8i8);
159     addDRTypeForNEON(MVT::v4i16);
160     addDRTypeForNEON(MVT::v2i32);
161     addDRTypeForNEON(MVT::v1i64);
162     addDRTypeForNEON(MVT::v1f64);
163     addDRTypeForNEON(MVT::v4f16);
164     addDRTypeForNEON(MVT::v4bf16);
165 
166     addQRTypeForNEON(MVT::v4f32);
167     addQRTypeForNEON(MVT::v2f64);
168     addQRTypeForNEON(MVT::v16i8);
169     addQRTypeForNEON(MVT::v8i16);
170     addQRTypeForNEON(MVT::v4i32);
171     addQRTypeForNEON(MVT::v2i64);
172     addQRTypeForNEON(MVT::v8f16);
173     addQRTypeForNEON(MVT::v8bf16);
174   }
175 
176   if (Subtarget->hasSVE()) {
177     // Add legal sve predicate types
178     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
179     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
180     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
181     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
182 
183     // Add legal sve data types
184     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
185     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
186     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
187     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
188 
189     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
190     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
191     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
192     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
193     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
194     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
195 
196     if (Subtarget->hasBF16()) {
197       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
198       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
199       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
200     }
201 
202     if (useSVEForFixedLengthVectors()) {
203       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
204         if (useSVEForFixedLengthVectorVT(VT))
205           addRegisterClass(VT, &AArch64::ZPRRegClass);
206 
207       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
208         if (useSVEForFixedLengthVectorVT(VT))
209           addRegisterClass(VT, &AArch64::ZPRRegClass);
210     }
211 
212     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
213       setOperationAction(ISD::SADDSAT, VT, Legal);
214       setOperationAction(ISD::UADDSAT, VT, Legal);
215       setOperationAction(ISD::SSUBSAT, VT, Legal);
216       setOperationAction(ISD::USUBSAT, VT, Legal);
217       setOperationAction(ISD::UREM, VT, Expand);
218       setOperationAction(ISD::SREM, VT, Expand);
219       setOperationAction(ISD::SDIVREM, VT, Expand);
220       setOperationAction(ISD::UDIVREM, VT, Expand);
221     }
222 
223     for (auto VT :
224          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
225            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
226       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
227 
228     for (auto VT :
229          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
230            MVT::nxv2f64 }) {
231       setCondCodeAction(ISD::SETO, VT, Expand);
232       setCondCodeAction(ISD::SETOLT, VT, Expand);
233       setCondCodeAction(ISD::SETOLE, VT, Expand);
234       setCondCodeAction(ISD::SETULT, VT, Expand);
235       setCondCodeAction(ISD::SETULE, VT, Expand);
236       setCondCodeAction(ISD::SETUGE, VT, Expand);
237       setCondCodeAction(ISD::SETUGT, VT, Expand);
238       setCondCodeAction(ISD::SETUEQ, VT, Expand);
239       setCondCodeAction(ISD::SETUNE, VT, Expand);
240     }
241   }
242 
243   // Compute derived properties from the register classes
244   computeRegisterProperties(Subtarget->getRegisterInfo());
245 
246   // Provide all sorts of operation actions
247   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
248   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
249   setOperationAction(ISD::SETCC, MVT::i32, Custom);
250   setOperationAction(ISD::SETCC, MVT::i64, Custom);
251   setOperationAction(ISD::SETCC, MVT::f16, Custom);
252   setOperationAction(ISD::SETCC, MVT::f32, Custom);
253   setOperationAction(ISD::SETCC, MVT::f64, Custom);
254   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
255   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
256   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
257   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
258   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
259   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
260   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
261   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
262   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
263   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
264   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
265   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
266   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
267   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
268   setOperationAction(ISD::SELECT, MVT::i32, Custom);
269   setOperationAction(ISD::SELECT, MVT::i64, Custom);
270   setOperationAction(ISD::SELECT, MVT::f16, Custom);
271   setOperationAction(ISD::SELECT, MVT::f32, Custom);
272   setOperationAction(ISD::SELECT, MVT::f64, Custom);
273   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
274   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
275   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
276   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
277   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
278   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
279   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
284 
285   setOperationAction(ISD::FREM, MVT::f32, Expand);
286   setOperationAction(ISD::FREM, MVT::f64, Expand);
287   setOperationAction(ISD::FREM, MVT::f80, Expand);
288 
289   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
290 
291   // Custom lowering hooks are needed for XOR
292   // to fold it into CSINC/CSINV.
293   setOperationAction(ISD::XOR, MVT::i32, Custom);
294   setOperationAction(ISD::XOR, MVT::i64, Custom);
295 
296   // Virtually no operation on f128 is legal, but LLVM can't expand them when
297   // there's a valid register class, so we need custom operations in most cases.
298   setOperationAction(ISD::FABS, MVT::f128, Expand);
299   setOperationAction(ISD::FADD, MVT::f128, Custom);
300   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
301   setOperationAction(ISD::FCOS, MVT::f128, Expand);
302   setOperationAction(ISD::FDIV, MVT::f128, Custom);
303   setOperationAction(ISD::FMA, MVT::f128, Expand);
304   setOperationAction(ISD::FMUL, MVT::f128, Custom);
305   setOperationAction(ISD::FNEG, MVT::f128, Expand);
306   setOperationAction(ISD::FPOW, MVT::f128, Expand);
307   setOperationAction(ISD::FREM, MVT::f128, Expand);
308   setOperationAction(ISD::FRINT, MVT::f128, Expand);
309   setOperationAction(ISD::FSIN, MVT::f128, Expand);
310   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
311   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
312   setOperationAction(ISD::FSUB, MVT::f128, Custom);
313   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
314   setOperationAction(ISD::SETCC, MVT::f128, Custom);
315   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
316   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
317   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
318   setOperationAction(ISD::SELECT, MVT::f128, Custom);
319   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
320   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
321 
322   // Lowering for many of the conversions is actually specified by the non-f128
323   // type. The LowerXXX function will be trivial when f128 isn't involved.
324   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
325   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
326   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
327   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
328   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
329   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
330   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
331   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
332   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
333   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
334   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
335   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
336   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
337   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
338   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
339   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
340   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
341   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
342   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
343   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
344   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
345   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
346   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
347   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
348   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
349   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
350   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
351   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
352 
353   // Variable arguments.
354   setOperationAction(ISD::VASTART, MVT::Other, Custom);
355   setOperationAction(ISD::VAARG, MVT::Other, Custom);
356   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
357   setOperationAction(ISD::VAEND, MVT::Other, Expand);
358 
359   // Variable-sized objects.
360   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
361   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
362 
363   if (Subtarget->isTargetWindows())
364     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
365   else
366     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
367 
368   // Constant pool entries
369   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
370 
371   // BlockAddress
372   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
373 
374   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
375   setOperationAction(ISD::ADDC, MVT::i32, Custom);
376   setOperationAction(ISD::ADDE, MVT::i32, Custom);
377   setOperationAction(ISD::SUBC, MVT::i32, Custom);
378   setOperationAction(ISD::SUBE, MVT::i32, Custom);
379   setOperationAction(ISD::ADDC, MVT::i64, Custom);
380   setOperationAction(ISD::ADDE, MVT::i64, Custom);
381   setOperationAction(ISD::SUBC, MVT::i64, Custom);
382   setOperationAction(ISD::SUBE, MVT::i64, Custom);
383 
384   // AArch64 lacks both left-rotate and popcount instructions.
385   setOperationAction(ISD::ROTL, MVT::i32, Expand);
386   setOperationAction(ISD::ROTL, MVT::i64, Expand);
387   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
388     setOperationAction(ISD::ROTL, VT, Expand);
389     setOperationAction(ISD::ROTR, VT, Expand);
390   }
391 
392   // AArch64 doesn't have i32 MULH{S|U}.
393   setOperationAction(ISD::MULHU, MVT::i32, Expand);
394   setOperationAction(ISD::MULHS, MVT::i32, Expand);
395 
396   // AArch64 doesn't have {U|S}MUL_LOHI.
397   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
398   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
399 
400   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
401   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
402   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
403 
404   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
405   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
406   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
407     setOperationAction(ISD::SDIVREM, VT, Expand);
408     setOperationAction(ISD::UDIVREM, VT, Expand);
409   }
410   setOperationAction(ISD::SREM, MVT::i32, Expand);
411   setOperationAction(ISD::SREM, MVT::i64, Expand);
412   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
413   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
414   setOperationAction(ISD::UREM, MVT::i32, Expand);
415   setOperationAction(ISD::UREM, MVT::i64, Expand);
416 
417   // Custom lower Add/Sub/Mul with overflow.
418   setOperationAction(ISD::SADDO, MVT::i32, Custom);
419   setOperationAction(ISD::SADDO, MVT::i64, Custom);
420   setOperationAction(ISD::UADDO, MVT::i32, Custom);
421   setOperationAction(ISD::UADDO, MVT::i64, Custom);
422   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
423   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
424   setOperationAction(ISD::USUBO, MVT::i32, Custom);
425   setOperationAction(ISD::USUBO, MVT::i64, Custom);
426   setOperationAction(ISD::SMULO, MVT::i32, Custom);
427   setOperationAction(ISD::SMULO, MVT::i64, Custom);
428   setOperationAction(ISD::UMULO, MVT::i32, Custom);
429   setOperationAction(ISD::UMULO, MVT::i64, Custom);
430 
431   setOperationAction(ISD::FSIN, MVT::f32, Expand);
432   setOperationAction(ISD::FSIN, MVT::f64, Expand);
433   setOperationAction(ISD::FCOS, MVT::f32, Expand);
434   setOperationAction(ISD::FCOS, MVT::f64, Expand);
435   setOperationAction(ISD::FPOW, MVT::f32, Expand);
436   setOperationAction(ISD::FPOW, MVT::f64, Expand);
437   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439   if (Subtarget->hasFullFP16())
440     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
441   else
442     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
443 
444   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
445   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
446   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
447   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
448   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
449   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
450   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
451   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
452   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
453   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
454   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
455   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
456   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
457   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
458   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
459   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
460   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
461   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
462   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
463   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
464   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
465   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
466   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
467   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
468   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
469   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
470   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
471   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
472   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
473   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
474   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
475   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
476   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
477 
478   if (!Subtarget->hasFullFP16()) {
479     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
480     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
481     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
482     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
483     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
484     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
485     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
486     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
487     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
488     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
489     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
490     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
491     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
492     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
493     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
494     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
495     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
496     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
497     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
498     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
499     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
500     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
501 
502     // promote v4f16 to v4f32 when that is known to be safe.
503     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
504     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
505     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
506     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
507     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
508     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
509     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
510     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
511 
512     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
513     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
514     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
515     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
516     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
517     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
518     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
519     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
520     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
521     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
522     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
523     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
524     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
525     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
526     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
527 
528     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
529     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
530     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
531     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
532     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
533     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
534     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
535     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
536     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
537     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
538     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
539     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
540     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
541     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
542     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
543     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
544     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
545     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
546     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
547     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
548   }
549 
550   // AArch64 has implementations of a lot of rounding-like FP operations.
551   for (MVT Ty : {MVT::f32, MVT::f64}) {
552     setOperationAction(ISD::FFLOOR, Ty, Legal);
553     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
554     setOperationAction(ISD::FCEIL, Ty, Legal);
555     setOperationAction(ISD::FRINT, Ty, Legal);
556     setOperationAction(ISD::FTRUNC, Ty, Legal);
557     setOperationAction(ISD::FROUND, Ty, Legal);
558     setOperationAction(ISD::FMINNUM, Ty, Legal);
559     setOperationAction(ISD::FMAXNUM, Ty, Legal);
560     setOperationAction(ISD::FMINIMUM, Ty, Legal);
561     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
562     setOperationAction(ISD::LROUND, Ty, Legal);
563     setOperationAction(ISD::LLROUND, Ty, Legal);
564     setOperationAction(ISD::LRINT, Ty, Legal);
565     setOperationAction(ISD::LLRINT, Ty, Legal);
566   }
567 
568   if (Subtarget->hasFullFP16()) {
569     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
570     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
571     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
572     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
573     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
574     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
575     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
576     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
577     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
578     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
579   }
580 
581   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
582 
583   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
584 
585   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
586   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
587   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
588   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
589   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
590 
591   // 128-bit loads and stores can be done without expanding
592   setOperationAction(ISD::LOAD, MVT::i128, Custom);
593   setOperationAction(ISD::STORE, MVT::i128, Custom);
594 
595   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
596   // custom lowering, as there are no un-paired non-temporal stores and
597   // legalization will break up 256 bit inputs.
598   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
599   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
600   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
601   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
602   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
603   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
604   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
605 
606   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
607   // This requires the Performance Monitors extension.
608   if (Subtarget->hasPerfMon())
609     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
610 
611   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
612       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
613     // Issue __sincos_stret if available.
614     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
615     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
616   } else {
617     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
618     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
619   }
620 
621   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
622     // MSVCRT doesn't have powi; fall back to pow
623     setLibcallName(RTLIB::POWI_F32, nullptr);
624     setLibcallName(RTLIB::POWI_F64, nullptr);
625   }
626 
627   // Make floating-point constants legal for the large code model, so they don't
628   // become loads from the constant pool.
629   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
630     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
631     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
632   }
633 
634   // AArch64 does not have floating-point extending loads, i1 sign-extending
635   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
636   for (MVT VT : MVT::fp_valuetypes()) {
637     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
638     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
639     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
640     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
641   }
642   for (MVT VT : MVT::integer_valuetypes())
643     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
644 
645   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
646   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
647   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
648   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
649   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
650   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
651   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
652 
653   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
654   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
655   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
656 
657   // Indexed loads and stores are supported.
658   for (unsigned im = (unsigned)ISD::PRE_INC;
659        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
660     setIndexedLoadAction(im, MVT::i8, Legal);
661     setIndexedLoadAction(im, MVT::i16, Legal);
662     setIndexedLoadAction(im, MVT::i32, Legal);
663     setIndexedLoadAction(im, MVT::i64, Legal);
664     setIndexedLoadAction(im, MVT::f64, Legal);
665     setIndexedLoadAction(im, MVT::f32, Legal);
666     setIndexedLoadAction(im, MVT::f16, Legal);
667     setIndexedLoadAction(im, MVT::bf16, Legal);
668     setIndexedStoreAction(im, MVT::i8, Legal);
669     setIndexedStoreAction(im, MVT::i16, Legal);
670     setIndexedStoreAction(im, MVT::i32, Legal);
671     setIndexedStoreAction(im, MVT::i64, Legal);
672     setIndexedStoreAction(im, MVT::f64, Legal);
673     setIndexedStoreAction(im, MVT::f32, Legal);
674     setIndexedStoreAction(im, MVT::f16, Legal);
675     setIndexedStoreAction(im, MVT::bf16, Legal);
676   }
677 
678   // Trap.
679   setOperationAction(ISD::TRAP, MVT::Other, Legal);
680   if (Subtarget->isTargetWindows())
681     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
682 
683   // We combine OR nodes for bitfield operations.
684   setTargetDAGCombine(ISD::OR);
685   // Try to create BICs for vector ANDs.
686   setTargetDAGCombine(ISD::AND);
687 
688   // Vector add and sub nodes may conceal a high-half opportunity.
689   // Also, try to fold ADD into CSINC/CSINV..
690   setTargetDAGCombine(ISD::ADD);
691   setTargetDAGCombine(ISD::SUB);
692   setTargetDAGCombine(ISD::SRL);
693   setTargetDAGCombine(ISD::XOR);
694   setTargetDAGCombine(ISD::SINT_TO_FP);
695   setTargetDAGCombine(ISD::UINT_TO_FP);
696 
697   setTargetDAGCombine(ISD::FP_TO_SINT);
698   setTargetDAGCombine(ISD::FP_TO_UINT);
699   setTargetDAGCombine(ISD::FDIV);
700 
701   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
702 
703   setTargetDAGCombine(ISD::ANY_EXTEND);
704   setTargetDAGCombine(ISD::ZERO_EXTEND);
705   setTargetDAGCombine(ISD::SIGN_EXTEND);
706   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
707   setTargetDAGCombine(ISD::CONCAT_VECTORS);
708   setTargetDAGCombine(ISD::STORE);
709   if (Subtarget->supportsAddressTopByteIgnored())
710     setTargetDAGCombine(ISD::LOAD);
711 
712   setTargetDAGCombine(ISD::MUL);
713 
714   setTargetDAGCombine(ISD::SELECT);
715   setTargetDAGCombine(ISD::VSELECT);
716 
717   setTargetDAGCombine(ISD::INTRINSIC_VOID);
718   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
719   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
720 
721   setTargetDAGCombine(ISD::GlobalAddress);
722 
723   // In case of strict alignment, avoid an excessive number of byte wide stores.
724   MaxStoresPerMemsetOptSize = 8;
725   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
726                        ? MaxStoresPerMemsetOptSize : 32;
727 
728   MaxGluedStoresPerMemcpy = 4;
729   MaxStoresPerMemcpyOptSize = 4;
730   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
731                        ? MaxStoresPerMemcpyOptSize : 16;
732 
733   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
734 
735   MaxLoadsPerMemcmpOptSize = 4;
736   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
737                       ? MaxLoadsPerMemcmpOptSize : 8;
738 
739   setStackPointerRegisterToSaveRestore(AArch64::SP);
740 
741   setSchedulingPreference(Sched::Hybrid);
742 
743   EnableExtLdPromotion = true;
744 
745   // Set required alignment.
746   setMinFunctionAlignment(Align(4));
747   // Set preferred alignments.
748   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
749   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
750 
751   // Only change the limit for entries in a jump table if specified by
752   // the sub target, but not at the command line.
753   unsigned MaxJT = STI.getMaximumJumpTableSize();
754   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
755     setMaximumJumpTableSize(MaxJT);
756 
757   setHasExtractBitsInsn(true);
758 
759   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
760 
761   if (Subtarget->hasNEON()) {
762     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
763     // silliness like this:
764     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
765     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
766     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
767     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
768     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
769     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
770     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
771     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
772     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
774     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
775     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
776     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
777     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
778     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
779     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
780     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
781     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
782     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
783     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
784     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
785     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
786     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
787     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
788     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
789 
790     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
791     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
792     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
793     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
794     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
795 
796     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
797 
798     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
799     // elements smaller than i32, so promote the input to i32 first.
800     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
801     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
802     // i8 vector elements also need promotion to i32 for v8i8
803     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
804     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
805     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
806     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
807     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
808     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
809     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
810     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
811     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
812     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
813     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
814 
815     if (Subtarget->hasFullFP16()) {
816       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
817       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
818       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
819       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
820     } else {
821       // when AArch64 doesn't have fullfp16 support, promote the input
822       // to i32 first.
823       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
824       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
825       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
826       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
827     }
828 
829     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
830     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
831 
832     // AArch64 doesn't have MUL.2d:
833     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
834     // Custom handling for some quad-vector types to detect MULL.
835     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
836     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
837     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
838 
839     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
840                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
841       // Vector reductions
842       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
843       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
844       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
845       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
846       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
847 
848       // Saturates
849       setOperationAction(ISD::SADDSAT, VT, Legal);
850       setOperationAction(ISD::UADDSAT, VT, Legal);
851       setOperationAction(ISD::SSUBSAT, VT, Legal);
852       setOperationAction(ISD::USUBSAT, VT, Legal);
853 
854       setOperationAction(ISD::TRUNCATE, VT, Custom);
855     }
856     for (MVT VT : { MVT::v4f16, MVT::v2f32,
857                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
858       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
859       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
860     }
861 
862     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
863     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
864     // Likewise, narrowing and extending vector loads/stores aren't handled
865     // directly.
866     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
867       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
868 
869       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
870         setOperationAction(ISD::MULHS, VT, Legal);
871         setOperationAction(ISD::MULHU, VT, Legal);
872       } else {
873         setOperationAction(ISD::MULHS, VT, Expand);
874         setOperationAction(ISD::MULHU, VT, Expand);
875       }
876       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
877       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
878 
879       setOperationAction(ISD::BSWAP, VT, Expand);
880       setOperationAction(ISD::CTTZ, VT, Expand);
881 
882       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
883         setTruncStoreAction(VT, InnerVT, Expand);
884         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
885         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
886         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
887       }
888     }
889 
890     // AArch64 has implementations of a lot of rounding-like FP operations.
891     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
892       setOperationAction(ISD::FFLOOR, Ty, Legal);
893       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
894       setOperationAction(ISD::FCEIL, Ty, Legal);
895       setOperationAction(ISD::FRINT, Ty, Legal);
896       setOperationAction(ISD::FTRUNC, Ty, Legal);
897       setOperationAction(ISD::FROUND, Ty, Legal);
898     }
899 
900     if (Subtarget->hasFullFP16()) {
901       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
902         setOperationAction(ISD::FFLOOR, Ty, Legal);
903         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
904         setOperationAction(ISD::FCEIL, Ty, Legal);
905         setOperationAction(ISD::FRINT, Ty, Legal);
906         setOperationAction(ISD::FTRUNC, Ty, Legal);
907         setOperationAction(ISD::FROUND, Ty, Legal);
908       }
909     }
910 
911     if (Subtarget->hasSVE())
912       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
913 
914     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
915   }
916 
917   if (Subtarget->hasSVE()) {
918     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
919     // splat of 0 or undef) once vector selects supported in SVE codegen. See
920     // D68877 for more details.
921     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
922       if (isTypeLegal(VT)) {
923         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
924         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
925         setOperationAction(ISD::SELECT, VT, Custom);
926         setOperationAction(ISD::SDIV, VT, Custom);
927         setOperationAction(ISD::UDIV, VT, Custom);
928         setOperationAction(ISD::SMIN, VT, Custom);
929         setOperationAction(ISD::UMIN, VT, Custom);
930         setOperationAction(ISD::SMAX, VT, Custom);
931         setOperationAction(ISD::UMAX, VT, Custom);
932         setOperationAction(ISD::SHL, VT, Custom);
933         setOperationAction(ISD::SRL, VT, Custom);
934         setOperationAction(ISD::SRA, VT, Custom);
935         if (VT.getScalarType() == MVT::i1) {
936           setOperationAction(ISD::SETCC, VT, Custom);
937           setOperationAction(ISD::TRUNCATE, VT, Custom);
938           setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
939         }
940       }
941     }
942 
943     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32})
944       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
945 
946     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
947     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
948 
949     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
950       if (isTypeLegal(VT)) {
951         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
952         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
953         setOperationAction(ISD::SELECT, VT, Custom);
954         setOperationAction(ISD::FMA, VT, Custom);
955       }
956     }
957 
958     // NOTE: Currently this has to happen after computeRegisterProperties rather
959     // than the preferred option of combining it with the addRegisterClass call.
960     if (useSVEForFixedLengthVectors()) {
961       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
962         if (useSVEForFixedLengthVectorVT(VT))
963           addTypeForFixedLengthSVE(VT);
964       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
965         if (useSVEForFixedLengthVectorVT(VT))
966           addTypeForFixedLengthSVE(VT);
967 
968       // 64bit results can mean a bigger than NEON input.
969       for (auto VT : {MVT::v8i8, MVT::v4i16})
970         setOperationAction(ISD::TRUNCATE, VT, Custom);
971       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
972 
973       // 128bit results imply a bigger than NEON input.
974       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
975         setOperationAction(ISD::TRUNCATE, VT, Custom);
976       for (auto VT : {MVT::v8f16, MVT::v4f32})
977         setOperationAction(ISD::FP_ROUND, VT, Expand);
978     }
979   }
980 
981   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
982 }
983 
984 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
985   assert(VT.isVector() && "VT should be a vector type");
986 
987   if (VT.isFloatingPoint()) {
988     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
989     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
990     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
991   }
992 
993   // Mark vector float intrinsics as expand.
994   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
995     setOperationAction(ISD::FSIN, VT, Expand);
996     setOperationAction(ISD::FCOS, VT, Expand);
997     setOperationAction(ISD::FPOW, VT, Expand);
998     setOperationAction(ISD::FLOG, VT, Expand);
999     setOperationAction(ISD::FLOG2, VT, Expand);
1000     setOperationAction(ISD::FLOG10, VT, Expand);
1001     setOperationAction(ISD::FEXP, VT, Expand);
1002     setOperationAction(ISD::FEXP2, VT, Expand);
1003 
1004     // But we do support custom-lowering for FCOPYSIGN.
1005     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1006   }
1007 
1008   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1009   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1010   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1011   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1012   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1013   setOperationAction(ISD::SRA, VT, Custom);
1014   setOperationAction(ISD::SRL, VT, Custom);
1015   setOperationAction(ISD::SHL, VT, Custom);
1016   setOperationAction(ISD::OR, VT, Custom);
1017   setOperationAction(ISD::SETCC, VT, Custom);
1018   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1019 
1020   setOperationAction(ISD::SELECT, VT, Expand);
1021   setOperationAction(ISD::SELECT_CC, VT, Expand);
1022   setOperationAction(ISD::VSELECT, VT, Expand);
1023   for (MVT InnerVT : MVT::all_valuetypes())
1024     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1025 
1026   // CNT supports only B element sizes, then use UADDLP to widen.
1027   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1028     setOperationAction(ISD::CTPOP, VT, Custom);
1029 
1030   setOperationAction(ISD::UDIV, VT, Expand);
1031   setOperationAction(ISD::SDIV, VT, Expand);
1032   setOperationAction(ISD::UREM, VT, Expand);
1033   setOperationAction(ISD::SREM, VT, Expand);
1034   setOperationAction(ISD::FREM, VT, Expand);
1035 
1036   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1037   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1038 
1039   if (!VT.isFloatingPoint())
1040     setOperationAction(ISD::ABS, VT, Legal);
1041 
1042   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1043   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1044     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1045       setOperationAction(Opcode, VT, Legal);
1046 
1047   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1048   if (VT.isFloatingPoint() &&
1049       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1050     for (unsigned Opcode :
1051          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1052       setOperationAction(Opcode, VT, Legal);
1053 
1054   if (Subtarget->isLittleEndian()) {
1055     for (unsigned im = (unsigned)ISD::PRE_INC;
1056          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1057       setIndexedLoadAction(im, VT, Legal);
1058       setIndexedStoreAction(im, VT, Legal);
1059     }
1060   }
1061 }
1062 
1063 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1064   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1065 
1066   // By default everything must be expanded.
1067   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1068     setOperationAction(Op, VT, Expand);
1069 
1070   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1071   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1072 
1073   // Lower fixed length vector operations to scalable equivalents.
1074   setOperationAction(ISD::ADD, VT, Custom);
1075   setOperationAction(ISD::FADD, VT, Custom);
1076   setOperationAction(ISD::LOAD, VT, Custom);
1077   setOperationAction(ISD::STORE, VT, Custom);
1078   setOperationAction(ISD::TRUNCATE, VT, Custom);
1079 }
1080 
1081 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1082   addRegisterClass(VT, &AArch64::FPR64RegClass);
1083   addTypeForNEON(VT, MVT::v2i32);
1084 }
1085 
1086 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1087   addRegisterClass(VT, &AArch64::FPR128RegClass);
1088   addTypeForNEON(VT, MVT::v4i32);
1089 }
1090 
1091 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1092                                               LLVMContext &C, EVT VT) const {
1093   if (!VT.isVector())
1094     return MVT::i32;
1095   if (VT.isScalableVector())
1096     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1097   return VT.changeVectorElementTypeToInteger();
1098 }
1099 
1100 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1101                                const APInt &Demanded,
1102                                TargetLowering::TargetLoweringOpt &TLO,
1103                                unsigned NewOpc) {
1104   uint64_t OldImm = Imm, NewImm, Enc;
1105   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1106 
1107   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1108   // bimm64.
1109   if (Imm == 0 || Imm == Mask ||
1110       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1111     return false;
1112 
1113   unsigned EltSize = Size;
1114   uint64_t DemandedBits = Demanded.getZExtValue();
1115 
1116   // Clear bits that are not demanded.
1117   Imm &= DemandedBits;
1118 
1119   while (true) {
1120     // The goal here is to set the non-demanded bits in a way that minimizes
1121     // the number of switching between 0 and 1. In order to achieve this goal,
1122     // we set the non-demanded bits to the value of the preceding demanded bits.
1123     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1124     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1125     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1126     // The final result is 0b11000011.
1127     uint64_t NonDemandedBits = ~DemandedBits;
1128     uint64_t InvertedImm = ~Imm & DemandedBits;
1129     uint64_t RotatedImm =
1130         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1131         NonDemandedBits;
1132     uint64_t Sum = RotatedImm + NonDemandedBits;
1133     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1134     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1135     NewImm = (Imm | Ones) & Mask;
1136 
1137     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1138     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1139     // we halve the element size and continue the search.
1140     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1141       break;
1142 
1143     // We cannot shrink the element size any further if it is 2-bits.
1144     if (EltSize == 2)
1145       return false;
1146 
1147     EltSize /= 2;
1148     Mask >>= EltSize;
1149     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1150 
1151     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1152     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1153       return false;
1154 
1155     // Merge the upper and lower halves of Imm and DemandedBits.
1156     Imm |= Hi;
1157     DemandedBits |= DemandedBitsHi;
1158   }
1159 
1160   ++NumOptimizedImms;
1161 
1162   // Replicate the element across the register width.
1163   while (EltSize < Size) {
1164     NewImm |= NewImm << EltSize;
1165     EltSize *= 2;
1166   }
1167 
1168   (void)OldImm;
1169   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1170          "demanded bits should never be altered");
1171   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1172 
1173   // Create the new constant immediate node.
1174   EVT VT = Op.getValueType();
1175   SDLoc DL(Op);
1176   SDValue New;
1177 
1178   // If the new constant immediate is all-zeros or all-ones, let the target
1179   // independent DAG combine optimize this node.
1180   if (NewImm == 0 || NewImm == OrigMask) {
1181     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1182                           TLO.DAG.getConstant(NewImm, DL, VT));
1183   // Otherwise, create a machine node so that target independent DAG combine
1184   // doesn't undo this optimization.
1185   } else {
1186     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1187     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1188     New = SDValue(
1189         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1190   }
1191 
1192   return TLO.CombineTo(Op, New);
1193 }
1194 
1195 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1196     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1197     TargetLoweringOpt &TLO) const {
1198   // Delay this optimization to as late as possible.
1199   if (!TLO.LegalOps)
1200     return false;
1201 
1202   if (!EnableOptimizeLogicalImm)
1203     return false;
1204 
1205   EVT VT = Op.getValueType();
1206   if (VT.isVector())
1207     return false;
1208 
1209   unsigned Size = VT.getSizeInBits();
1210   assert((Size == 32 || Size == 64) &&
1211          "i32 or i64 is expected after legalization.");
1212 
1213   // Exit early if we demand all bits.
1214   if (DemandedBits.countPopulation() == Size)
1215     return false;
1216 
1217   unsigned NewOpc;
1218   switch (Op.getOpcode()) {
1219   default:
1220     return false;
1221   case ISD::AND:
1222     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1223     break;
1224   case ISD::OR:
1225     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1226     break;
1227   case ISD::XOR:
1228     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1229     break;
1230   }
1231   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1232   if (!C)
1233     return false;
1234   uint64_t Imm = C->getZExtValue();
1235   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1236 }
1237 
1238 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1239 /// Mask are known to be either zero or one and return them Known.
1240 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1241     const SDValue Op, KnownBits &Known,
1242     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1243   switch (Op.getOpcode()) {
1244   default:
1245     break;
1246   case AArch64ISD::CSEL: {
1247     KnownBits Known2;
1248     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1249     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1250     Known.Zero &= Known2.Zero;
1251     Known.One &= Known2.One;
1252     break;
1253   }
1254   case AArch64ISD::LOADgot:
1255   case AArch64ISD::ADDlow: {
1256     if (!Subtarget->isTargetILP32())
1257       break;
1258     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1259     Known.Zero = APInt::getHighBitsSet(64, 32);
1260     break;
1261   }
1262   case ISD::INTRINSIC_W_CHAIN: {
1263     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1264     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1265     switch (IntID) {
1266     default: return;
1267     case Intrinsic::aarch64_ldaxr:
1268     case Intrinsic::aarch64_ldxr: {
1269       unsigned BitWidth = Known.getBitWidth();
1270       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1271       unsigned MemBits = VT.getScalarSizeInBits();
1272       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1273       return;
1274     }
1275     }
1276     break;
1277   }
1278   case ISD::INTRINSIC_WO_CHAIN:
1279   case ISD::INTRINSIC_VOID: {
1280     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1281     switch (IntNo) {
1282     default:
1283       break;
1284     case Intrinsic::aarch64_neon_umaxv:
1285     case Intrinsic::aarch64_neon_uminv: {
1286       // Figure out the datatype of the vector operand. The UMINV instruction
1287       // will zero extend the result, so we can mark as known zero all the
1288       // bits larger than the element datatype. 32-bit or larget doesn't need
1289       // this as those are legal types and will be handled by isel directly.
1290       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1291       unsigned BitWidth = Known.getBitWidth();
1292       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1293         assert(BitWidth >= 8 && "Unexpected width!");
1294         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1295         Known.Zero |= Mask;
1296       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1297         assert(BitWidth >= 16 && "Unexpected width!");
1298         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1299         Known.Zero |= Mask;
1300       }
1301       break;
1302     } break;
1303     }
1304   }
1305   }
1306 }
1307 
1308 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1309                                                   EVT) const {
1310   return MVT::i64;
1311 }
1312 
1313 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1314     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1315     bool *Fast) const {
1316   if (Subtarget->requiresStrictAlign())
1317     return false;
1318 
1319   if (Fast) {
1320     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1321     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1322             // See comments in performSTORECombine() for more details about
1323             // these conditions.
1324 
1325             // Code that uses clang vector extensions can mark that it
1326             // wants unaligned accesses to be treated as fast by
1327             // underspecifying alignment to be 1 or 2.
1328             Align <= 2 ||
1329 
1330             // Disregard v2i64. Memcpy lowering produces those and splitting
1331             // them regresses performance on micro-benchmarks and olden/bh.
1332             VT == MVT::v2i64;
1333   }
1334   return true;
1335 }
1336 
1337 // Same as above but handling LLTs instead.
1338 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1339     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1340     bool *Fast) const {
1341   if (Subtarget->requiresStrictAlign())
1342     return false;
1343 
1344   if (Fast) {
1345     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1346     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1347             Ty.getSizeInBytes() != 16 ||
1348             // See comments in performSTORECombine() for more details about
1349             // these conditions.
1350 
1351             // Code that uses clang vector extensions can mark that it
1352             // wants unaligned accesses to be treated as fast by
1353             // underspecifying alignment to be 1 or 2.
1354             Alignment <= 2 ||
1355 
1356             // Disregard v2i64. Memcpy lowering produces those and splitting
1357             // them regresses performance on micro-benchmarks and olden/bh.
1358             Ty == LLT::vector(2, 64);
1359   }
1360   return true;
1361 }
1362 
1363 FastISel *
1364 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1365                                       const TargetLibraryInfo *libInfo) const {
1366   return AArch64::createFastISel(funcInfo, libInfo);
1367 }
1368 
1369 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1370 #define MAKE_CASE(V)                                                           \
1371   case V:                                                                      \
1372     return #V;
1373   switch ((AArch64ISD::NodeType)Opcode) {
1374   case AArch64ISD::FIRST_NUMBER:
1375     break;
1376     MAKE_CASE(AArch64ISD::CALL)
1377     MAKE_CASE(AArch64ISD::ADRP)
1378     MAKE_CASE(AArch64ISD::ADR)
1379     MAKE_CASE(AArch64ISD::ADDlow)
1380     MAKE_CASE(AArch64ISD::LOADgot)
1381     MAKE_CASE(AArch64ISD::RET_FLAG)
1382     MAKE_CASE(AArch64ISD::BRCOND)
1383     MAKE_CASE(AArch64ISD::CSEL)
1384     MAKE_CASE(AArch64ISD::FCSEL)
1385     MAKE_CASE(AArch64ISD::CSINV)
1386     MAKE_CASE(AArch64ISD::CSNEG)
1387     MAKE_CASE(AArch64ISD::CSINC)
1388     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1389     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1390     MAKE_CASE(AArch64ISD::ADD_PRED)
1391     MAKE_CASE(AArch64ISD::SDIV_PRED)
1392     MAKE_CASE(AArch64ISD::UDIV_PRED)
1393     MAKE_CASE(AArch64ISD::SMIN_MERGE_OP1)
1394     MAKE_CASE(AArch64ISD::UMIN_MERGE_OP1)
1395     MAKE_CASE(AArch64ISD::SMAX_MERGE_OP1)
1396     MAKE_CASE(AArch64ISD::UMAX_MERGE_OP1)
1397     MAKE_CASE(AArch64ISD::SHL_MERGE_OP1)
1398     MAKE_CASE(AArch64ISD::SRL_MERGE_OP1)
1399     MAKE_CASE(AArch64ISD::SRA_MERGE_OP1)
1400     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1401     MAKE_CASE(AArch64ISD::ADC)
1402     MAKE_CASE(AArch64ISD::SBC)
1403     MAKE_CASE(AArch64ISD::ADDS)
1404     MAKE_CASE(AArch64ISD::SUBS)
1405     MAKE_CASE(AArch64ISD::ADCS)
1406     MAKE_CASE(AArch64ISD::SBCS)
1407     MAKE_CASE(AArch64ISD::ANDS)
1408     MAKE_CASE(AArch64ISD::CCMP)
1409     MAKE_CASE(AArch64ISD::CCMN)
1410     MAKE_CASE(AArch64ISD::FCCMP)
1411     MAKE_CASE(AArch64ISD::FCMP)
1412     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1413     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1414     MAKE_CASE(AArch64ISD::DUP)
1415     MAKE_CASE(AArch64ISD::DUPLANE8)
1416     MAKE_CASE(AArch64ISD::DUPLANE16)
1417     MAKE_CASE(AArch64ISD::DUPLANE32)
1418     MAKE_CASE(AArch64ISD::DUPLANE64)
1419     MAKE_CASE(AArch64ISD::MOVI)
1420     MAKE_CASE(AArch64ISD::MOVIshift)
1421     MAKE_CASE(AArch64ISD::MOVIedit)
1422     MAKE_CASE(AArch64ISD::MOVImsl)
1423     MAKE_CASE(AArch64ISD::FMOV)
1424     MAKE_CASE(AArch64ISD::MVNIshift)
1425     MAKE_CASE(AArch64ISD::MVNImsl)
1426     MAKE_CASE(AArch64ISD::BICi)
1427     MAKE_CASE(AArch64ISD::ORRi)
1428     MAKE_CASE(AArch64ISD::BSP)
1429     MAKE_CASE(AArch64ISD::NEG)
1430     MAKE_CASE(AArch64ISD::EXTR)
1431     MAKE_CASE(AArch64ISD::ZIP1)
1432     MAKE_CASE(AArch64ISD::ZIP2)
1433     MAKE_CASE(AArch64ISD::UZP1)
1434     MAKE_CASE(AArch64ISD::UZP2)
1435     MAKE_CASE(AArch64ISD::TRN1)
1436     MAKE_CASE(AArch64ISD::TRN2)
1437     MAKE_CASE(AArch64ISD::REV16)
1438     MAKE_CASE(AArch64ISD::REV32)
1439     MAKE_CASE(AArch64ISD::REV64)
1440     MAKE_CASE(AArch64ISD::EXT)
1441     MAKE_CASE(AArch64ISD::VSHL)
1442     MAKE_CASE(AArch64ISD::VLSHR)
1443     MAKE_CASE(AArch64ISD::VASHR)
1444     MAKE_CASE(AArch64ISD::VSLI)
1445     MAKE_CASE(AArch64ISD::VSRI)
1446     MAKE_CASE(AArch64ISD::CMEQ)
1447     MAKE_CASE(AArch64ISD::CMGE)
1448     MAKE_CASE(AArch64ISD::CMGT)
1449     MAKE_CASE(AArch64ISD::CMHI)
1450     MAKE_CASE(AArch64ISD::CMHS)
1451     MAKE_CASE(AArch64ISD::FCMEQ)
1452     MAKE_CASE(AArch64ISD::FCMGE)
1453     MAKE_CASE(AArch64ISD::FCMGT)
1454     MAKE_CASE(AArch64ISD::CMEQz)
1455     MAKE_CASE(AArch64ISD::CMGEz)
1456     MAKE_CASE(AArch64ISD::CMGTz)
1457     MAKE_CASE(AArch64ISD::CMLEz)
1458     MAKE_CASE(AArch64ISD::CMLTz)
1459     MAKE_CASE(AArch64ISD::FCMEQz)
1460     MAKE_CASE(AArch64ISD::FCMGEz)
1461     MAKE_CASE(AArch64ISD::FCMGTz)
1462     MAKE_CASE(AArch64ISD::FCMLEz)
1463     MAKE_CASE(AArch64ISD::FCMLTz)
1464     MAKE_CASE(AArch64ISD::SADDV)
1465     MAKE_CASE(AArch64ISD::UADDV)
1466     MAKE_CASE(AArch64ISD::SRHADD)
1467     MAKE_CASE(AArch64ISD::URHADD)
1468     MAKE_CASE(AArch64ISD::SMINV)
1469     MAKE_CASE(AArch64ISD::UMINV)
1470     MAKE_CASE(AArch64ISD::SMAXV)
1471     MAKE_CASE(AArch64ISD::UMAXV)
1472     MAKE_CASE(AArch64ISD::SMAXV_PRED)
1473     MAKE_CASE(AArch64ISD::UMAXV_PRED)
1474     MAKE_CASE(AArch64ISD::SMINV_PRED)
1475     MAKE_CASE(AArch64ISD::UMINV_PRED)
1476     MAKE_CASE(AArch64ISD::ORV_PRED)
1477     MAKE_CASE(AArch64ISD::EORV_PRED)
1478     MAKE_CASE(AArch64ISD::ANDV_PRED)
1479     MAKE_CASE(AArch64ISD::CLASTA_N)
1480     MAKE_CASE(AArch64ISD::CLASTB_N)
1481     MAKE_CASE(AArch64ISD::LASTA)
1482     MAKE_CASE(AArch64ISD::LASTB)
1483     MAKE_CASE(AArch64ISD::REV)
1484     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1485     MAKE_CASE(AArch64ISD::TBL)
1486     MAKE_CASE(AArch64ISD::FADD_PRED)
1487     MAKE_CASE(AArch64ISD::FADDA_PRED)
1488     MAKE_CASE(AArch64ISD::FADDV_PRED)
1489     MAKE_CASE(AArch64ISD::FMA_PRED)
1490     MAKE_CASE(AArch64ISD::FMAXV_PRED)
1491     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1492     MAKE_CASE(AArch64ISD::FMINV_PRED)
1493     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1494     MAKE_CASE(AArch64ISD::NOT)
1495     MAKE_CASE(AArch64ISD::BIT)
1496     MAKE_CASE(AArch64ISD::CBZ)
1497     MAKE_CASE(AArch64ISD::CBNZ)
1498     MAKE_CASE(AArch64ISD::TBZ)
1499     MAKE_CASE(AArch64ISD::TBNZ)
1500     MAKE_CASE(AArch64ISD::TC_RETURN)
1501     MAKE_CASE(AArch64ISD::PREFETCH)
1502     MAKE_CASE(AArch64ISD::SITOF)
1503     MAKE_CASE(AArch64ISD::UITOF)
1504     MAKE_CASE(AArch64ISD::NVCAST)
1505     MAKE_CASE(AArch64ISD::SQSHL_I)
1506     MAKE_CASE(AArch64ISD::UQSHL_I)
1507     MAKE_CASE(AArch64ISD::SRSHR_I)
1508     MAKE_CASE(AArch64ISD::URSHR_I)
1509     MAKE_CASE(AArch64ISD::SQSHLU_I)
1510     MAKE_CASE(AArch64ISD::WrapperLarge)
1511     MAKE_CASE(AArch64ISD::LD2post)
1512     MAKE_CASE(AArch64ISD::LD3post)
1513     MAKE_CASE(AArch64ISD::LD4post)
1514     MAKE_CASE(AArch64ISD::ST2post)
1515     MAKE_CASE(AArch64ISD::ST3post)
1516     MAKE_CASE(AArch64ISD::ST4post)
1517     MAKE_CASE(AArch64ISD::LD1x2post)
1518     MAKE_CASE(AArch64ISD::LD1x3post)
1519     MAKE_CASE(AArch64ISD::LD1x4post)
1520     MAKE_CASE(AArch64ISD::ST1x2post)
1521     MAKE_CASE(AArch64ISD::ST1x3post)
1522     MAKE_CASE(AArch64ISD::ST1x4post)
1523     MAKE_CASE(AArch64ISD::LD1DUPpost)
1524     MAKE_CASE(AArch64ISD::LD2DUPpost)
1525     MAKE_CASE(AArch64ISD::LD3DUPpost)
1526     MAKE_CASE(AArch64ISD::LD4DUPpost)
1527     MAKE_CASE(AArch64ISD::LD1LANEpost)
1528     MAKE_CASE(AArch64ISD::LD2LANEpost)
1529     MAKE_CASE(AArch64ISD::LD3LANEpost)
1530     MAKE_CASE(AArch64ISD::LD4LANEpost)
1531     MAKE_CASE(AArch64ISD::ST2LANEpost)
1532     MAKE_CASE(AArch64ISD::ST3LANEpost)
1533     MAKE_CASE(AArch64ISD::ST4LANEpost)
1534     MAKE_CASE(AArch64ISD::SMULL)
1535     MAKE_CASE(AArch64ISD::UMULL)
1536     MAKE_CASE(AArch64ISD::FRECPE)
1537     MAKE_CASE(AArch64ISD::FRECPS)
1538     MAKE_CASE(AArch64ISD::FRSQRTE)
1539     MAKE_CASE(AArch64ISD::FRSQRTS)
1540     MAKE_CASE(AArch64ISD::STG)
1541     MAKE_CASE(AArch64ISD::STZG)
1542     MAKE_CASE(AArch64ISD::ST2G)
1543     MAKE_CASE(AArch64ISD::STZ2G)
1544     MAKE_CASE(AArch64ISD::SUNPKHI)
1545     MAKE_CASE(AArch64ISD::SUNPKLO)
1546     MAKE_CASE(AArch64ISD::UUNPKHI)
1547     MAKE_CASE(AArch64ISD::UUNPKLO)
1548     MAKE_CASE(AArch64ISD::INSR)
1549     MAKE_CASE(AArch64ISD::PTEST)
1550     MAKE_CASE(AArch64ISD::PTRUE)
1551     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1552     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1553     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1554     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1555     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1556     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1557     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1558     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1559     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1560     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1561     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1562     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1563     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1564     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1565     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1566     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1567     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1568     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1569     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1570     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1571     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1572     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1573     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1574     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1575     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1576     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1577     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1578     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1579     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1580     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1581     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1582     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1583     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1584     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1585     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1586     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1587     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1588     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1589     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1590     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1591     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1592     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1593     MAKE_CASE(AArch64ISD::ST1_PRED)
1594     MAKE_CASE(AArch64ISD::SST1_PRED)
1595     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1596     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1597     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1598     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1599     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1600     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1601     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1602     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1603     MAKE_CASE(AArch64ISD::LDP)
1604     MAKE_CASE(AArch64ISD::STP)
1605     MAKE_CASE(AArch64ISD::STNP)
1606     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1607     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1608   }
1609 #undef MAKE_CASE
1610   return nullptr;
1611 }
1612 
1613 MachineBasicBlock *
1614 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1615                                     MachineBasicBlock *MBB) const {
1616   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1617   // phi node:
1618 
1619   // OrigBB:
1620   //     [... previous instrs leading to comparison ...]
1621   //     b.ne TrueBB
1622   //     b EndBB
1623   // TrueBB:
1624   //     ; Fallthrough
1625   // EndBB:
1626   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1627 
1628   MachineFunction *MF = MBB->getParent();
1629   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1630   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1631   DebugLoc DL = MI.getDebugLoc();
1632   MachineFunction::iterator It = ++MBB->getIterator();
1633 
1634   Register DestReg = MI.getOperand(0).getReg();
1635   Register IfTrueReg = MI.getOperand(1).getReg();
1636   Register IfFalseReg = MI.getOperand(2).getReg();
1637   unsigned CondCode = MI.getOperand(3).getImm();
1638   bool NZCVKilled = MI.getOperand(4).isKill();
1639 
1640   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1641   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1642   MF->insert(It, TrueBB);
1643   MF->insert(It, EndBB);
1644 
1645   // Transfer rest of current basic-block to EndBB
1646   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1647                 MBB->end());
1648   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1649 
1650   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1651   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1652   MBB->addSuccessor(TrueBB);
1653   MBB->addSuccessor(EndBB);
1654 
1655   // TrueBB falls through to the end.
1656   TrueBB->addSuccessor(EndBB);
1657 
1658   if (!NZCVKilled) {
1659     TrueBB->addLiveIn(AArch64::NZCV);
1660     EndBB->addLiveIn(AArch64::NZCV);
1661   }
1662 
1663   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1664       .addReg(IfTrueReg)
1665       .addMBB(TrueBB)
1666       .addReg(IfFalseReg)
1667       .addMBB(MBB);
1668 
1669   MI.eraseFromParent();
1670   return EndBB;
1671 }
1672 
1673 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1674        MachineInstr &MI, MachineBasicBlock *BB) const {
1675   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1676              BB->getParent()->getFunction().getPersonalityFn())) &&
1677          "SEH does not use catchret!");
1678   return BB;
1679 }
1680 
1681 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1682     MachineInstr &MI, MachineBasicBlock *BB) const {
1683   switch (MI.getOpcode()) {
1684   default:
1685 #ifndef NDEBUG
1686     MI.dump();
1687 #endif
1688     llvm_unreachable("Unexpected instruction for custom inserter!");
1689 
1690   case AArch64::F128CSEL:
1691     return EmitF128CSEL(MI, BB);
1692 
1693   case TargetOpcode::STACKMAP:
1694   case TargetOpcode::PATCHPOINT:
1695     return emitPatchPoint(MI, BB);
1696 
1697   case AArch64::CATCHRET:
1698     return EmitLoweredCatchRet(MI, BB);
1699   }
1700 }
1701 
1702 //===----------------------------------------------------------------------===//
1703 // AArch64 Lowering private implementation.
1704 //===----------------------------------------------------------------------===//
1705 
1706 //===----------------------------------------------------------------------===//
1707 // Lowering Code
1708 //===----------------------------------------------------------------------===//
1709 
1710 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1711 /// CC
1712 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1713   switch (CC) {
1714   default:
1715     llvm_unreachable("Unknown condition code!");
1716   case ISD::SETNE:
1717     return AArch64CC::NE;
1718   case ISD::SETEQ:
1719     return AArch64CC::EQ;
1720   case ISD::SETGT:
1721     return AArch64CC::GT;
1722   case ISD::SETGE:
1723     return AArch64CC::GE;
1724   case ISD::SETLT:
1725     return AArch64CC::LT;
1726   case ISD::SETLE:
1727     return AArch64CC::LE;
1728   case ISD::SETUGT:
1729     return AArch64CC::HI;
1730   case ISD::SETUGE:
1731     return AArch64CC::HS;
1732   case ISD::SETULT:
1733     return AArch64CC::LO;
1734   case ISD::SETULE:
1735     return AArch64CC::LS;
1736   }
1737 }
1738 
1739 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1740 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1741                                   AArch64CC::CondCode &CondCode,
1742                                   AArch64CC::CondCode &CondCode2) {
1743   CondCode2 = AArch64CC::AL;
1744   switch (CC) {
1745   default:
1746     llvm_unreachable("Unknown FP condition!");
1747   case ISD::SETEQ:
1748   case ISD::SETOEQ:
1749     CondCode = AArch64CC::EQ;
1750     break;
1751   case ISD::SETGT:
1752   case ISD::SETOGT:
1753     CondCode = AArch64CC::GT;
1754     break;
1755   case ISD::SETGE:
1756   case ISD::SETOGE:
1757     CondCode = AArch64CC::GE;
1758     break;
1759   case ISD::SETOLT:
1760     CondCode = AArch64CC::MI;
1761     break;
1762   case ISD::SETOLE:
1763     CondCode = AArch64CC::LS;
1764     break;
1765   case ISD::SETONE:
1766     CondCode = AArch64CC::MI;
1767     CondCode2 = AArch64CC::GT;
1768     break;
1769   case ISD::SETO:
1770     CondCode = AArch64CC::VC;
1771     break;
1772   case ISD::SETUO:
1773     CondCode = AArch64CC::VS;
1774     break;
1775   case ISD::SETUEQ:
1776     CondCode = AArch64CC::EQ;
1777     CondCode2 = AArch64CC::VS;
1778     break;
1779   case ISD::SETUGT:
1780     CondCode = AArch64CC::HI;
1781     break;
1782   case ISD::SETUGE:
1783     CondCode = AArch64CC::PL;
1784     break;
1785   case ISD::SETLT:
1786   case ISD::SETULT:
1787     CondCode = AArch64CC::LT;
1788     break;
1789   case ISD::SETLE:
1790   case ISD::SETULE:
1791     CondCode = AArch64CC::LE;
1792     break;
1793   case ISD::SETNE:
1794   case ISD::SETUNE:
1795     CondCode = AArch64CC::NE;
1796     break;
1797   }
1798 }
1799 
1800 /// Convert a DAG fp condition code to an AArch64 CC.
1801 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1802 /// should be AND'ed instead of OR'ed.
1803 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1804                                      AArch64CC::CondCode &CondCode,
1805                                      AArch64CC::CondCode &CondCode2) {
1806   CondCode2 = AArch64CC::AL;
1807   switch (CC) {
1808   default:
1809     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1810     assert(CondCode2 == AArch64CC::AL);
1811     break;
1812   case ISD::SETONE:
1813     // (a one b)
1814     // == ((a olt b) || (a ogt b))
1815     // == ((a ord b) && (a une b))
1816     CondCode = AArch64CC::VC;
1817     CondCode2 = AArch64CC::NE;
1818     break;
1819   case ISD::SETUEQ:
1820     // (a ueq b)
1821     // == ((a uno b) || (a oeq b))
1822     // == ((a ule b) && (a uge b))
1823     CondCode = AArch64CC::PL;
1824     CondCode2 = AArch64CC::LE;
1825     break;
1826   }
1827 }
1828 
1829 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1830 /// CC usable with the vector instructions. Fewer operations are available
1831 /// without a real NZCV register, so we have to use less efficient combinations
1832 /// to get the same effect.
1833 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1834                                         AArch64CC::CondCode &CondCode,
1835                                         AArch64CC::CondCode &CondCode2,
1836                                         bool &Invert) {
1837   Invert = false;
1838   switch (CC) {
1839   default:
1840     // Mostly the scalar mappings work fine.
1841     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1842     break;
1843   case ISD::SETUO:
1844     Invert = true;
1845     LLVM_FALLTHROUGH;
1846   case ISD::SETO:
1847     CondCode = AArch64CC::MI;
1848     CondCode2 = AArch64CC::GE;
1849     break;
1850   case ISD::SETUEQ:
1851   case ISD::SETULT:
1852   case ISD::SETULE:
1853   case ISD::SETUGT:
1854   case ISD::SETUGE:
1855     // All of the compare-mask comparisons are ordered, but we can switch
1856     // between the two by a double inversion. E.g. ULE == !OGT.
1857     Invert = true;
1858     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1859                           CondCode, CondCode2);
1860     break;
1861   }
1862 }
1863 
1864 static bool isLegalArithImmed(uint64_t C) {
1865   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1866   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1867   LLVM_DEBUG(dbgs() << "Is imm " << C
1868                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1869   return IsLegal;
1870 }
1871 
1872 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1873 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1874 // can be set differently by this operation. It comes down to whether
1875 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1876 // everything is fine. If not then the optimization is wrong. Thus general
1877 // comparisons are only valid if op2 != 0.
1878 //
1879 // So, finally, the only LLVM-native comparisons that don't mention C and V
1880 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1881 // the absence of information about op2.
1882 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1883   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1884          (CC == ISD::SETEQ || CC == ISD::SETNE);
1885 }
1886 
1887 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1888                                       SelectionDAG &DAG, SDValue Chain,
1889                                       bool IsSignaling) {
1890   EVT VT = LHS.getValueType();
1891   assert(VT != MVT::f128);
1892   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1893   unsigned Opcode =
1894       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1895   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1896 }
1897 
1898 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1899                               const SDLoc &dl, SelectionDAG &DAG) {
1900   EVT VT = LHS.getValueType();
1901   const bool FullFP16 =
1902     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1903 
1904   if (VT.isFloatingPoint()) {
1905     assert(VT != MVT::f128);
1906     if (VT == MVT::f16 && !FullFP16) {
1907       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1908       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1909       VT = MVT::f32;
1910     }
1911     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1912   }
1913 
1914   // The CMP instruction is just an alias for SUBS, and representing it as
1915   // SUBS means that it's possible to get CSE with subtract operations.
1916   // A later phase can perform the optimization of setting the destination
1917   // register to WZR/XZR if it ends up being unused.
1918   unsigned Opcode = AArch64ISD::SUBS;
1919 
1920   if (isCMN(RHS, CC)) {
1921     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1922     Opcode = AArch64ISD::ADDS;
1923     RHS = RHS.getOperand(1);
1924   } else if (isCMN(LHS, CC)) {
1925     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1926     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1927     Opcode = AArch64ISD::ADDS;
1928     LHS = LHS.getOperand(1);
1929   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
1930     if (LHS.getOpcode() == ISD::AND) {
1931       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1932       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1933       // of the signed comparisons.
1934       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
1935                                            DAG.getVTList(VT, MVT_CC),
1936                                            LHS.getOperand(0),
1937                                            LHS.getOperand(1));
1938       // Replace all users of (and X, Y) with newly generated (ands X, Y)
1939       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
1940       return ANDSNode.getValue(1);
1941     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
1942       // Use result of ANDS
1943       return LHS.getValue(1);
1944     }
1945   }
1946 
1947   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1948       .getValue(1);
1949 }
1950 
1951 /// \defgroup AArch64CCMP CMP;CCMP matching
1952 ///
1953 /// These functions deal with the formation of CMP;CCMP;... sequences.
1954 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1955 /// a comparison. They set the NZCV flags to a predefined value if their
1956 /// predicate is false. This allows to express arbitrary conjunctions, for
1957 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1958 /// expressed as:
1959 ///   cmp A
1960 ///   ccmp B, inv(CB), CA
1961 ///   check for CB flags
1962 ///
1963 /// This naturally lets us implement chains of AND operations with SETCC
1964 /// operands. And we can even implement some other situations by transforming
1965 /// them:
1966 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1967 ///     negating the flags used in a CCMP/FCCMP operations.
1968 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1969 ///     by negating the flags we test for afterwards. i.e.
1970 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1971 ///   - Note that we can only ever negate all previously processed results.
1972 ///     What we can not implement by flipping the flags to test is a negation
1973 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1974 ///     far, so the 2nd sub-tree we emit would also affect the first).
1975 /// With those tools we can implement some OR operations:
1976 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1977 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1978 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1979 ///     elimination rules from earlier to implement the whole thing as a
1980 ///     CCMP/FCCMP chain.
1981 ///
1982 /// As complete example:
1983 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1984 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1985 /// can be reassociated to:
1986 ///     or (and (setCC (cmp C)) setCD (cmp D))
1987 //         (or (setCA (cmp A)) (setCB (cmp B)))
1988 /// can be transformed to:
1989 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1990 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1991 /// which can be implemented as:
1992 ///   cmp C
1993 ///   ccmp D, inv(CD), CC
1994 ///   ccmp A, CA, inv(CD)
1995 ///   ccmp B, CB, inv(CA)
1996 ///   check for CB flags
1997 ///
1998 /// A counterexample is "or (and A B) (and C D)" which translates to
1999 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2000 /// can only implement 1 of the inner (not) operations, but not both!
2001 /// @{
2002 
2003 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2004 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2005                                          ISD::CondCode CC, SDValue CCOp,
2006                                          AArch64CC::CondCode Predicate,
2007                                          AArch64CC::CondCode OutCC,
2008                                          const SDLoc &DL, SelectionDAG &DAG) {
2009   unsigned Opcode = 0;
2010   const bool FullFP16 =
2011     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2012 
2013   if (LHS.getValueType().isFloatingPoint()) {
2014     assert(LHS.getValueType() != MVT::f128);
2015     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2016       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2017       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2018     }
2019     Opcode = AArch64ISD::FCCMP;
2020   } else if (RHS.getOpcode() == ISD::SUB) {
2021     SDValue SubOp0 = RHS.getOperand(0);
2022     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2023       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2024       Opcode = AArch64ISD::CCMN;
2025       RHS = RHS.getOperand(1);
2026     }
2027   }
2028   if (Opcode == 0)
2029     Opcode = AArch64ISD::CCMP;
2030 
2031   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2032   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2033   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2034   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2035   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2036 }
2037 
2038 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2039 /// expressed as a conjunction. See \ref AArch64CCMP.
2040 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2041 ///                     changing the conditions on the SETCC tests.
2042 ///                     (this means we can call emitConjunctionRec() with
2043 ///                      Negate==true on this sub-tree)
2044 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2045 ///                     cannot do the negation naturally. We are required to
2046 ///                     emit the subtree first in this case.
2047 /// \param WillNegate   Is true if are called when the result of this
2048 ///                     subexpression must be negated. This happens when the
2049 ///                     outer expression is an OR. We can use this fact to know
2050 ///                     that we have a double negation (or (or ...) ...) that
2051 ///                     can be implemented for free.
2052 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2053                                bool &MustBeFirst, bool WillNegate,
2054                                unsigned Depth = 0) {
2055   if (!Val.hasOneUse())
2056     return false;
2057   unsigned Opcode = Val->getOpcode();
2058   if (Opcode == ISD::SETCC) {
2059     if (Val->getOperand(0).getValueType() == MVT::f128)
2060       return false;
2061     CanNegate = true;
2062     MustBeFirst = false;
2063     return true;
2064   }
2065   // Protect against exponential runtime and stack overflow.
2066   if (Depth > 6)
2067     return false;
2068   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2069     bool IsOR = Opcode == ISD::OR;
2070     SDValue O0 = Val->getOperand(0);
2071     SDValue O1 = Val->getOperand(1);
2072     bool CanNegateL;
2073     bool MustBeFirstL;
2074     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2075       return false;
2076     bool CanNegateR;
2077     bool MustBeFirstR;
2078     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2079       return false;
2080 
2081     if (MustBeFirstL && MustBeFirstR)
2082       return false;
2083 
2084     if (IsOR) {
2085       // For an OR expression we need to be able to naturally negate at least
2086       // one side or we cannot do the transformation at all.
2087       if (!CanNegateL && !CanNegateR)
2088         return false;
2089       // If we the result of the OR will be negated and we can naturally negate
2090       // the leafs, then this sub-tree as a whole negates naturally.
2091       CanNegate = WillNegate && CanNegateL && CanNegateR;
2092       // If we cannot naturally negate the whole sub-tree, then this must be
2093       // emitted first.
2094       MustBeFirst = !CanNegate;
2095     } else {
2096       assert(Opcode == ISD::AND && "Must be OR or AND");
2097       // We cannot naturally negate an AND operation.
2098       CanNegate = false;
2099       MustBeFirst = MustBeFirstL || MustBeFirstR;
2100     }
2101     return true;
2102   }
2103   return false;
2104 }
2105 
2106 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2107 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2108 /// Tries to transform the given i1 producing node @p Val to a series compare
2109 /// and conditional compare operations. @returns an NZCV flags producing node
2110 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2111 /// transformation was not possible.
2112 /// \p Negate is true if we want this sub-tree being negated just by changing
2113 /// SETCC conditions.
2114 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2115     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2116     AArch64CC::CondCode Predicate) {
2117   // We're at a tree leaf, produce a conditional comparison operation.
2118   unsigned Opcode = Val->getOpcode();
2119   if (Opcode == ISD::SETCC) {
2120     SDValue LHS = Val->getOperand(0);
2121     SDValue RHS = Val->getOperand(1);
2122     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2123     bool isInteger = LHS.getValueType().isInteger();
2124     if (Negate)
2125       CC = getSetCCInverse(CC, LHS.getValueType());
2126     SDLoc DL(Val);
2127     // Determine OutCC and handle FP special case.
2128     if (isInteger) {
2129       OutCC = changeIntCCToAArch64CC(CC);
2130     } else {
2131       assert(LHS.getValueType().isFloatingPoint());
2132       AArch64CC::CondCode ExtraCC;
2133       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2134       // Some floating point conditions can't be tested with a single condition
2135       // code. Construct an additional comparison in this case.
2136       if (ExtraCC != AArch64CC::AL) {
2137         SDValue ExtraCmp;
2138         if (!CCOp.getNode())
2139           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2140         else
2141           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2142                                                ExtraCC, DL, DAG);
2143         CCOp = ExtraCmp;
2144         Predicate = ExtraCC;
2145       }
2146     }
2147 
2148     // Produce a normal comparison if we are first in the chain
2149     if (!CCOp)
2150       return emitComparison(LHS, RHS, CC, DL, DAG);
2151     // Otherwise produce a ccmp.
2152     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2153                                      DAG);
2154   }
2155   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2156 
2157   bool IsOR = Opcode == ISD::OR;
2158 
2159   SDValue LHS = Val->getOperand(0);
2160   bool CanNegateL;
2161   bool MustBeFirstL;
2162   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2163   assert(ValidL && "Valid conjunction/disjunction tree");
2164   (void)ValidL;
2165 
2166   SDValue RHS = Val->getOperand(1);
2167   bool CanNegateR;
2168   bool MustBeFirstR;
2169   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2170   assert(ValidR && "Valid conjunction/disjunction tree");
2171   (void)ValidR;
2172 
2173   // Swap sub-tree that must come first to the right side.
2174   if (MustBeFirstL) {
2175     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2176     std::swap(LHS, RHS);
2177     std::swap(CanNegateL, CanNegateR);
2178     std::swap(MustBeFirstL, MustBeFirstR);
2179   }
2180 
2181   bool NegateR;
2182   bool NegateAfterR;
2183   bool NegateL;
2184   bool NegateAfterAll;
2185   if (Opcode == ISD::OR) {
2186     // Swap the sub-tree that we can negate naturally to the left.
2187     if (!CanNegateL) {
2188       assert(CanNegateR && "at least one side must be negatable");
2189       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2190       assert(!Negate);
2191       std::swap(LHS, RHS);
2192       NegateR = false;
2193       NegateAfterR = true;
2194     } else {
2195       // Negate the left sub-tree if possible, otherwise negate the result.
2196       NegateR = CanNegateR;
2197       NegateAfterR = !CanNegateR;
2198     }
2199     NegateL = true;
2200     NegateAfterAll = !Negate;
2201   } else {
2202     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2203     assert(!Negate && "Valid conjunction/disjunction tree");
2204 
2205     NegateL = false;
2206     NegateR = false;
2207     NegateAfterR = false;
2208     NegateAfterAll = false;
2209   }
2210 
2211   // Emit sub-trees.
2212   AArch64CC::CondCode RHSCC;
2213   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2214   if (NegateAfterR)
2215     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2216   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2217   if (NegateAfterAll)
2218     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2219   return CmpL;
2220 }
2221 
2222 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2223 /// In some cases this is even possible with OR operations in the expression.
2224 /// See \ref AArch64CCMP.
2225 /// \see emitConjunctionRec().
2226 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2227                                AArch64CC::CondCode &OutCC) {
2228   bool DummyCanNegate;
2229   bool DummyMustBeFirst;
2230   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2231     return SDValue();
2232 
2233   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2234 }
2235 
2236 /// @}
2237 
2238 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2239 /// extension operations.
2240 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2241   auto isSupportedExtend = [&](SDValue V) {
2242     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2243       return true;
2244 
2245     if (V.getOpcode() == ISD::AND)
2246       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2247         uint64_t Mask = MaskCst->getZExtValue();
2248         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2249       }
2250 
2251     return false;
2252   };
2253 
2254   if (!Op.hasOneUse())
2255     return 0;
2256 
2257   if (isSupportedExtend(Op))
2258     return 1;
2259 
2260   unsigned Opc = Op.getOpcode();
2261   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2262     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2263       uint64_t Shift = ShiftCst->getZExtValue();
2264       if (isSupportedExtend(Op.getOperand(0)))
2265         return (Shift <= 4) ? 2 : 1;
2266       EVT VT = Op.getValueType();
2267       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2268         return 1;
2269     }
2270 
2271   return 0;
2272 }
2273 
2274 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2275                              SDValue &AArch64cc, SelectionDAG &DAG,
2276                              const SDLoc &dl) {
2277   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2278     EVT VT = RHS.getValueType();
2279     uint64_t C = RHSC->getZExtValue();
2280     if (!isLegalArithImmed(C)) {
2281       // Constant does not fit, try adjusting it by one?
2282       switch (CC) {
2283       default:
2284         break;
2285       case ISD::SETLT:
2286       case ISD::SETGE:
2287         if ((VT == MVT::i32 && C != 0x80000000 &&
2288              isLegalArithImmed((uint32_t)(C - 1))) ||
2289             (VT == MVT::i64 && C != 0x80000000ULL &&
2290              isLegalArithImmed(C - 1ULL))) {
2291           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2292           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2293           RHS = DAG.getConstant(C, dl, VT);
2294         }
2295         break;
2296       case ISD::SETULT:
2297       case ISD::SETUGE:
2298         if ((VT == MVT::i32 && C != 0 &&
2299              isLegalArithImmed((uint32_t)(C - 1))) ||
2300             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2301           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2302           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2303           RHS = DAG.getConstant(C, dl, VT);
2304         }
2305         break;
2306       case ISD::SETLE:
2307       case ISD::SETGT:
2308         if ((VT == MVT::i32 && C != INT32_MAX &&
2309              isLegalArithImmed((uint32_t)(C + 1))) ||
2310             (VT == MVT::i64 && C != INT64_MAX &&
2311              isLegalArithImmed(C + 1ULL))) {
2312           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2313           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2314           RHS = DAG.getConstant(C, dl, VT);
2315         }
2316         break;
2317       case ISD::SETULE:
2318       case ISD::SETUGT:
2319         if ((VT == MVT::i32 && C != UINT32_MAX &&
2320              isLegalArithImmed((uint32_t)(C + 1))) ||
2321             (VT == MVT::i64 && C != UINT64_MAX &&
2322              isLegalArithImmed(C + 1ULL))) {
2323           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2324           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2325           RHS = DAG.getConstant(C, dl, VT);
2326         }
2327         break;
2328       }
2329     }
2330   }
2331 
2332   // Comparisons are canonicalized so that the RHS operand is simpler than the
2333   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2334   // can fold some shift+extend operations on the RHS operand, so swap the
2335   // operands if that can be done.
2336   //
2337   // For example:
2338   //    lsl     w13, w11, #1
2339   //    cmp     w13, w12
2340   // can be turned into:
2341   //    cmp     w12, w11, lsl #1
2342   if (!isa<ConstantSDNode>(RHS) ||
2343       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2344     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2345 
2346     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2347       std::swap(LHS, RHS);
2348       CC = ISD::getSetCCSwappedOperands(CC);
2349     }
2350   }
2351 
2352   SDValue Cmp;
2353   AArch64CC::CondCode AArch64CC;
2354   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2355     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2356 
2357     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2358     // For the i8 operand, the largest immediate is 255, so this can be easily
2359     // encoded in the compare instruction. For the i16 operand, however, the
2360     // largest immediate cannot be encoded in the compare.
2361     // Therefore, use a sign extending load and cmn to avoid materializing the
2362     // -1 constant. For example,
2363     // movz w1, #65535
2364     // ldrh w0, [x0, #0]
2365     // cmp w0, w1
2366     // >
2367     // ldrsh w0, [x0, #0]
2368     // cmn w0, #1
2369     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2370     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2371     // ensure both the LHS and RHS are truly zero extended and to make sure the
2372     // transformation is profitable.
2373     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2374         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2375         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2376         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2377       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2378       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2379         SDValue SExt =
2380             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2381                         DAG.getValueType(MVT::i16));
2382         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2383                                                    RHS.getValueType()),
2384                              CC, dl, DAG);
2385         AArch64CC = changeIntCCToAArch64CC(CC);
2386       }
2387     }
2388 
2389     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2390       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2391         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2392           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2393       }
2394     }
2395   }
2396 
2397   if (!Cmp) {
2398     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2399     AArch64CC = changeIntCCToAArch64CC(CC);
2400   }
2401   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2402   return Cmp;
2403 }
2404 
2405 static std::pair<SDValue, SDValue>
2406 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2407   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2408          "Unsupported value type");
2409   SDValue Value, Overflow;
2410   SDLoc DL(Op);
2411   SDValue LHS = Op.getOperand(0);
2412   SDValue RHS = Op.getOperand(1);
2413   unsigned Opc = 0;
2414   switch (Op.getOpcode()) {
2415   default:
2416     llvm_unreachable("Unknown overflow instruction!");
2417   case ISD::SADDO:
2418     Opc = AArch64ISD::ADDS;
2419     CC = AArch64CC::VS;
2420     break;
2421   case ISD::UADDO:
2422     Opc = AArch64ISD::ADDS;
2423     CC = AArch64CC::HS;
2424     break;
2425   case ISD::SSUBO:
2426     Opc = AArch64ISD::SUBS;
2427     CC = AArch64CC::VS;
2428     break;
2429   case ISD::USUBO:
2430     Opc = AArch64ISD::SUBS;
2431     CC = AArch64CC::LO;
2432     break;
2433   // Multiply needs a little bit extra work.
2434   case ISD::SMULO:
2435   case ISD::UMULO: {
2436     CC = AArch64CC::NE;
2437     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2438     if (Op.getValueType() == MVT::i32) {
2439       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2440       // For a 32 bit multiply with overflow check we want the instruction
2441       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2442       // need to generate the following pattern:
2443       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2444       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2445       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2446       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2447       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2448                                 DAG.getConstant(0, DL, MVT::i64));
2449       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2450       // operation. We need to clear out the upper 32 bits, because we used a
2451       // widening multiply that wrote all 64 bits. In the end this should be a
2452       // noop.
2453       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2454       if (IsSigned) {
2455         // The signed overflow check requires more than just a simple check for
2456         // any bit set in the upper 32 bits of the result. These bits could be
2457         // just the sign bits of a negative number. To perform the overflow
2458         // check we have to arithmetic shift right the 32nd bit of the result by
2459         // 31 bits. Then we compare the result to the upper 32 bits.
2460         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2461                                         DAG.getConstant(32, DL, MVT::i64));
2462         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2463         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2464                                         DAG.getConstant(31, DL, MVT::i64));
2465         // It is important that LowerBits is last, otherwise the arithmetic
2466         // shift will not be folded into the compare (SUBS).
2467         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2468         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2469                        .getValue(1);
2470       } else {
2471         // The overflow check for unsigned multiply is easy. We only need to
2472         // check if any of the upper 32 bits are set. This can be done with a
2473         // CMP (shifted register). For that we need to generate the following
2474         // pattern:
2475         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2476         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2477                                         DAG.getConstant(32, DL, MVT::i64));
2478         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2479         Overflow =
2480             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2481                         DAG.getConstant(0, DL, MVT::i64),
2482                         UpperBits).getValue(1);
2483       }
2484       break;
2485     }
2486     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2487     // For the 64 bit multiply
2488     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2489     if (IsSigned) {
2490       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2491       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2492                                       DAG.getConstant(63, DL, MVT::i64));
2493       // It is important that LowerBits is last, otherwise the arithmetic
2494       // shift will not be folded into the compare (SUBS).
2495       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2496       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2497                      .getValue(1);
2498     } else {
2499       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2500       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2501       Overflow =
2502           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2503                       DAG.getConstant(0, DL, MVT::i64),
2504                       UpperBits).getValue(1);
2505     }
2506     break;
2507   }
2508   } // switch (...)
2509 
2510   if (Opc) {
2511     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2512 
2513     // Emit the AArch64 operation with overflow check.
2514     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2515     Overflow = Value.getValue(1);
2516   }
2517   return std::make_pair(Value, Overflow);
2518 }
2519 
2520 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2521                                              RTLIB::Libcall Call) const {
2522   bool IsStrict = Op->isStrictFPOpcode();
2523   unsigned Offset = IsStrict ? 1 : 0;
2524   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2525   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2526   MakeLibCallOptions CallOptions;
2527   SDValue Result;
2528   SDLoc dl(Op);
2529   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2530                                         CallOptions, dl, Chain);
2531   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2532 }
2533 
2534 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2535   SDValue Sel = Op.getOperand(0);
2536   SDValue Other = Op.getOperand(1);
2537   SDLoc dl(Sel);
2538 
2539   // If the operand is an overflow checking operation, invert the condition
2540   // code and kill the Not operation. I.e., transform:
2541   // (xor (overflow_op_bool, 1))
2542   //   -->
2543   // (csel 1, 0, invert(cc), overflow_op_bool)
2544   // ... which later gets transformed to just a cset instruction with an
2545   // inverted condition code, rather than a cset + eor sequence.
2546   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2547     // Only lower legal XALUO ops.
2548     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2549       return SDValue();
2550 
2551     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2552     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2553     AArch64CC::CondCode CC;
2554     SDValue Value, Overflow;
2555     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2556     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2557     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2558                        CCVal, Overflow);
2559   }
2560   // If neither operand is a SELECT_CC, give up.
2561   if (Sel.getOpcode() != ISD::SELECT_CC)
2562     std::swap(Sel, Other);
2563   if (Sel.getOpcode() != ISD::SELECT_CC)
2564     return Op;
2565 
2566   // The folding we want to perform is:
2567   // (xor x, (select_cc a, b, cc, 0, -1) )
2568   //   -->
2569   // (csel x, (xor x, -1), cc ...)
2570   //
2571   // The latter will get matched to a CSINV instruction.
2572 
2573   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2574   SDValue LHS = Sel.getOperand(0);
2575   SDValue RHS = Sel.getOperand(1);
2576   SDValue TVal = Sel.getOperand(2);
2577   SDValue FVal = Sel.getOperand(3);
2578 
2579   // FIXME: This could be generalized to non-integer comparisons.
2580   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2581     return Op;
2582 
2583   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2584   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2585 
2586   // The values aren't constants, this isn't the pattern we're looking for.
2587   if (!CFVal || !CTVal)
2588     return Op;
2589 
2590   // We can commute the SELECT_CC by inverting the condition.  This
2591   // might be needed to make this fit into a CSINV pattern.
2592   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2593     std::swap(TVal, FVal);
2594     std::swap(CTVal, CFVal);
2595     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2596   }
2597 
2598   // If the constants line up, perform the transform!
2599   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2600     SDValue CCVal;
2601     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2602 
2603     FVal = Other;
2604     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2605                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2606 
2607     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2608                        CCVal, Cmp);
2609   }
2610 
2611   return Op;
2612 }
2613 
2614 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2615   EVT VT = Op.getValueType();
2616 
2617   // Let legalize expand this if it isn't a legal type yet.
2618   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2619     return SDValue();
2620 
2621   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2622 
2623   unsigned Opc;
2624   bool ExtraOp = false;
2625   switch (Op.getOpcode()) {
2626   default:
2627     llvm_unreachable("Invalid code");
2628   case ISD::ADDC:
2629     Opc = AArch64ISD::ADDS;
2630     break;
2631   case ISD::SUBC:
2632     Opc = AArch64ISD::SUBS;
2633     break;
2634   case ISD::ADDE:
2635     Opc = AArch64ISD::ADCS;
2636     ExtraOp = true;
2637     break;
2638   case ISD::SUBE:
2639     Opc = AArch64ISD::SBCS;
2640     ExtraOp = true;
2641     break;
2642   }
2643 
2644   if (!ExtraOp)
2645     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2646   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2647                      Op.getOperand(2));
2648 }
2649 
2650 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2651   // Let legalize expand this if it isn't a legal type yet.
2652   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2653     return SDValue();
2654 
2655   SDLoc dl(Op);
2656   AArch64CC::CondCode CC;
2657   // The actual operation that sets the overflow or carry flag.
2658   SDValue Value, Overflow;
2659   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2660 
2661   // We use 0 and 1 as false and true values.
2662   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2663   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2664 
2665   // We use an inverted condition, because the conditional select is inverted
2666   // too. This will allow it to be selected to a single instruction:
2667   // CSINC Wd, WZR, WZR, invert(cond).
2668   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2669   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2670                          CCVal, Overflow);
2671 
2672   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2673   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2674 }
2675 
2676 // Prefetch operands are:
2677 // 1: Address to prefetch
2678 // 2: bool isWrite
2679 // 3: int locality (0 = no locality ... 3 = extreme locality)
2680 // 4: bool isDataCache
2681 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2682   SDLoc DL(Op);
2683   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2684   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2685   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2686 
2687   bool IsStream = !Locality;
2688   // When the locality number is set
2689   if (Locality) {
2690     // The front-end should have filtered out the out-of-range values
2691     assert(Locality <= 3 && "Prefetch locality out-of-range");
2692     // The locality degree is the opposite of the cache speed.
2693     // Put the number the other way around.
2694     // The encoding starts at 0 for level 1
2695     Locality = 3 - Locality;
2696   }
2697 
2698   // built the mask value encoding the expected behavior.
2699   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2700                    (!IsData << 3) |     // IsDataCache bit
2701                    (Locality << 1) |    // Cache level bits
2702                    (unsigned)IsStream;  // Stream bit
2703   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2704                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2705 }
2706 
2707 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2708                                               SelectionDAG &DAG) const {
2709   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2710 
2711   RTLIB::Libcall LC;
2712   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2713 
2714   return LowerF128Call(Op, DAG, LC);
2715 }
2716 
2717 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2718                                              SelectionDAG &DAG) const {
2719   bool IsStrict = Op->isStrictFPOpcode();
2720   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2721   EVT SrcVT = SrcVal.getValueType();
2722 
2723   if (SrcVT != MVT::f128) {
2724     // Expand cases where the input is a vector bigger than NEON.
2725     if (useSVEForFixedLengthVectorVT(SrcVT))
2726       return SDValue();
2727 
2728     // It's legal except when f128 is involved
2729     return Op;
2730   }
2731 
2732   RTLIB::Libcall LC;
2733   LC = RTLIB::getFPROUND(SrcVT, Op.getValueType());
2734 
2735   // FP_ROUND node has a second operand indicating whether it is known to be
2736   // precise. That doesn't take part in the LibCall so we can't directly use
2737   // LowerF128Call.
2738   MakeLibCallOptions CallOptions;
2739   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2740   SDValue Result;
2741   SDLoc dl(Op);
2742   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2743                                         CallOptions, dl, Chain);
2744   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2745 }
2746 
2747 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2748                                                     SelectionDAG &DAG) const {
2749   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2750   // Any additional optimization in this function should be recorded
2751   // in the cost tables.
2752   EVT InVT = Op.getOperand(0).getValueType();
2753   EVT VT = Op.getValueType();
2754   unsigned NumElts = InVT.getVectorNumElements();
2755 
2756   // f16 conversions are promoted to f32 when full fp16 is not supported.
2757   if (InVT.getVectorElementType() == MVT::f16 &&
2758       !Subtarget->hasFullFP16()) {
2759     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2760     SDLoc dl(Op);
2761     return DAG.getNode(
2762         Op.getOpcode(), dl, Op.getValueType(),
2763         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2764   }
2765 
2766   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2767     SDLoc dl(Op);
2768     SDValue Cv =
2769         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2770                     Op.getOperand(0));
2771     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2772   }
2773 
2774   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2775     SDLoc dl(Op);
2776     MVT ExtVT =
2777         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2778                          VT.getVectorNumElements());
2779     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2780     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2781   }
2782 
2783   // Type changing conversions are illegal.
2784   return Op;
2785 }
2786 
2787 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2788                                               SelectionDAG &DAG) const {
2789   bool IsStrict = Op->isStrictFPOpcode();
2790   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2791 
2792   if (SrcVal.getValueType().isVector())
2793     return LowerVectorFP_TO_INT(Op, DAG);
2794 
2795   // f16 conversions are promoted to f32 when full fp16 is not supported.
2796   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2797     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2798     SDLoc dl(Op);
2799     return DAG.getNode(
2800         Op.getOpcode(), dl, Op.getValueType(),
2801         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2802   }
2803 
2804   if (SrcVal.getValueType() != MVT::f128) {
2805     // It's legal except when f128 is involved
2806     return Op;
2807   }
2808 
2809   RTLIB::Libcall LC;
2810   if (Op.getOpcode() == ISD::FP_TO_SINT ||
2811       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2812     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2813   else
2814     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2815 
2816   return LowerF128Call(Op, DAG, LC);
2817 }
2818 
2819 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2820   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2821   // Any additional optimization in this function should be recorded
2822   // in the cost tables.
2823   EVT VT = Op.getValueType();
2824   SDLoc dl(Op);
2825   SDValue In = Op.getOperand(0);
2826   EVT InVT = In.getValueType();
2827 
2828   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2829     MVT CastVT =
2830         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2831                          InVT.getVectorNumElements());
2832     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2833     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2834   }
2835 
2836   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2837     unsigned CastOpc =
2838         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2839     EVT CastVT = VT.changeVectorElementTypeToInteger();
2840     In = DAG.getNode(CastOpc, dl, CastVT, In);
2841     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2842   }
2843 
2844   return Op;
2845 }
2846 
2847 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2848                                             SelectionDAG &DAG) const {
2849   if (Op.getValueType().isVector())
2850     return LowerVectorINT_TO_FP(Op, DAG);
2851 
2852   bool IsStrict = Op->isStrictFPOpcode();
2853   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2854 
2855   // f16 conversions are promoted to f32 when full fp16 is not supported.
2856   if (Op.getValueType() == MVT::f16 &&
2857       !Subtarget->hasFullFP16()) {
2858     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2859     SDLoc dl(Op);
2860     return DAG.getNode(
2861         ISD::FP_ROUND, dl, MVT::f16,
2862         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2863         DAG.getIntPtrConstant(0, dl));
2864   }
2865 
2866   // i128 conversions are libcalls.
2867   if (SrcVal.getValueType() == MVT::i128)
2868     return SDValue();
2869 
2870   // Other conversions are legal, unless it's to the completely software-based
2871   // fp128.
2872   if (Op.getValueType() != MVT::f128)
2873     return Op;
2874 
2875   RTLIB::Libcall LC;
2876   if (Op.getOpcode() == ISD::SINT_TO_FP ||
2877       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2878     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2879   else
2880     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2881 
2882   return LowerF128Call(Op, DAG, LC);
2883 }
2884 
2885 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2886                                             SelectionDAG &DAG) const {
2887   // For iOS, we want to call an alternative entry point: __sincos_stret,
2888   // which returns the values in two S / D registers.
2889   SDLoc dl(Op);
2890   SDValue Arg = Op.getOperand(0);
2891   EVT ArgVT = Arg.getValueType();
2892   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2893 
2894   ArgListTy Args;
2895   ArgListEntry Entry;
2896 
2897   Entry.Node = Arg;
2898   Entry.Ty = ArgTy;
2899   Entry.IsSExt = false;
2900   Entry.IsZExt = false;
2901   Args.push_back(Entry);
2902 
2903   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2904                                         : RTLIB::SINCOS_STRET_F32;
2905   const char *LibcallName = getLibcallName(LC);
2906   SDValue Callee =
2907       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2908 
2909   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2910   TargetLowering::CallLoweringInfo CLI(DAG);
2911   CLI.setDebugLoc(dl)
2912       .setChain(DAG.getEntryNode())
2913       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2914 
2915   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2916   return CallResult.first;
2917 }
2918 
2919 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2920   EVT OpVT = Op.getValueType();
2921   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
2922     return SDValue();
2923 
2924   assert(Op.getOperand(0).getValueType() == MVT::i16);
2925   SDLoc DL(Op);
2926 
2927   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2928   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2929   return SDValue(
2930       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
2931                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2932       0);
2933 }
2934 
2935 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2936   if (OrigVT.getSizeInBits() >= 64)
2937     return OrigVT;
2938 
2939   assert(OrigVT.isSimple() && "Expecting a simple value type");
2940 
2941   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2942   switch (OrigSimpleTy) {
2943   default: llvm_unreachable("Unexpected Vector Type");
2944   case MVT::v2i8:
2945   case MVT::v2i16:
2946      return MVT::v2i32;
2947   case MVT::v4i8:
2948     return  MVT::v4i16;
2949   }
2950 }
2951 
2952 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2953                                                  const EVT &OrigTy,
2954                                                  const EVT &ExtTy,
2955                                                  unsigned ExtOpcode) {
2956   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2957   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2958   // 64-bits we need to insert a new extension so that it will be 64-bits.
2959   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2960   if (OrigTy.getSizeInBits() >= 64)
2961     return N;
2962 
2963   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2964   EVT NewVT = getExtensionTo64Bits(OrigTy);
2965 
2966   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2967 }
2968 
2969 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2970                                    bool isSigned) {
2971   EVT VT = N->getValueType(0);
2972 
2973   if (N->getOpcode() != ISD::BUILD_VECTOR)
2974     return false;
2975 
2976   for (const SDValue &Elt : N->op_values()) {
2977     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2978       unsigned EltSize = VT.getScalarSizeInBits();
2979       unsigned HalfSize = EltSize / 2;
2980       if (isSigned) {
2981         if (!isIntN(HalfSize, C->getSExtValue()))
2982           return false;
2983       } else {
2984         if (!isUIntN(HalfSize, C->getZExtValue()))
2985           return false;
2986       }
2987       continue;
2988     }
2989     return false;
2990   }
2991 
2992   return true;
2993 }
2994 
2995 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2996   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2997     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2998                                              N->getOperand(0)->getValueType(0),
2999                                              N->getValueType(0),
3000                                              N->getOpcode());
3001 
3002   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3003   EVT VT = N->getValueType(0);
3004   SDLoc dl(N);
3005   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3006   unsigned NumElts = VT.getVectorNumElements();
3007   MVT TruncVT = MVT::getIntegerVT(EltSize);
3008   SmallVector<SDValue, 8> Ops;
3009   for (unsigned i = 0; i != NumElts; ++i) {
3010     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3011     const APInt &CInt = C->getAPIntValue();
3012     // Element types smaller than 32 bits are not legal, so use i32 elements.
3013     // The values are implicitly truncated so sext vs. zext doesn't matter.
3014     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3015   }
3016   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3017 }
3018 
3019 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3020   return N->getOpcode() == ISD::SIGN_EXTEND ||
3021          isExtendedBUILD_VECTOR(N, DAG, true);
3022 }
3023 
3024 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3025   return N->getOpcode() == ISD::ZERO_EXTEND ||
3026          isExtendedBUILD_VECTOR(N, DAG, false);
3027 }
3028 
3029 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3030   unsigned Opcode = N->getOpcode();
3031   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3032     SDNode *N0 = N->getOperand(0).getNode();
3033     SDNode *N1 = N->getOperand(1).getNode();
3034     return N0->hasOneUse() && N1->hasOneUse() &&
3035       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3036   }
3037   return false;
3038 }
3039 
3040 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3041   unsigned Opcode = N->getOpcode();
3042   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3043     SDNode *N0 = N->getOperand(0).getNode();
3044     SDNode *N1 = N->getOperand(1).getNode();
3045     return N0->hasOneUse() && N1->hasOneUse() &&
3046       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3047   }
3048   return false;
3049 }
3050 
3051 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3052                                                 SelectionDAG &DAG) const {
3053   // The rounding mode is in bits 23:22 of the FPSCR.
3054   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3055   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3056   // so that the shift + and get folded into a bitfield extract.
3057   SDLoc dl(Op);
3058 
3059   SDValue Chain = Op.getOperand(0);
3060   SDValue FPCR_64 = DAG.getNode(
3061       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3062       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3063   Chain = FPCR_64.getValue(1);
3064   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3065   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3066                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3067   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3068                               DAG.getConstant(22, dl, MVT::i32));
3069   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3070                             DAG.getConstant(3, dl, MVT::i32));
3071   return DAG.getMergeValues({AND, Chain}, dl);
3072 }
3073 
3074 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
3075   // Multiplications are only custom-lowered for 128-bit vectors so that
3076   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3077   EVT VT = Op.getValueType();
3078   assert(VT.is128BitVector() && VT.isInteger() &&
3079          "unexpected type for custom-lowering ISD::MUL");
3080   SDNode *N0 = Op.getOperand(0).getNode();
3081   SDNode *N1 = Op.getOperand(1).getNode();
3082   unsigned NewOpc = 0;
3083   bool isMLA = false;
3084   bool isN0SExt = isSignExtended(N0, DAG);
3085   bool isN1SExt = isSignExtended(N1, DAG);
3086   if (isN0SExt && isN1SExt)
3087     NewOpc = AArch64ISD::SMULL;
3088   else {
3089     bool isN0ZExt = isZeroExtended(N0, DAG);
3090     bool isN1ZExt = isZeroExtended(N1, DAG);
3091     if (isN0ZExt && isN1ZExt)
3092       NewOpc = AArch64ISD::UMULL;
3093     else if (isN1SExt || isN1ZExt) {
3094       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3095       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3096       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3097         NewOpc = AArch64ISD::SMULL;
3098         isMLA = true;
3099       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3100         NewOpc =  AArch64ISD::UMULL;
3101         isMLA = true;
3102       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3103         std::swap(N0, N1);
3104         NewOpc =  AArch64ISD::UMULL;
3105         isMLA = true;
3106       }
3107     }
3108 
3109     if (!NewOpc) {
3110       if (VT == MVT::v2i64)
3111         // Fall through to expand this.  It is not legal.
3112         return SDValue();
3113       else
3114         // Other vector multiplications are legal.
3115         return Op;
3116     }
3117   }
3118 
3119   // Legalize to a S/UMULL instruction
3120   SDLoc DL(Op);
3121   SDValue Op0;
3122   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3123   if (!isMLA) {
3124     Op0 = skipExtensionForVectorMULL(N0, DAG);
3125     assert(Op0.getValueType().is64BitVector() &&
3126            Op1.getValueType().is64BitVector() &&
3127            "unexpected types for extended operands to VMULL");
3128     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3129   }
3130   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3131   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3132   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3133   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3134   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3135   EVT Op1VT = Op1.getValueType();
3136   return DAG.getNode(N0->getOpcode(), DL, VT,
3137                      DAG.getNode(NewOpc, DL, VT,
3138                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3139                      DAG.getNode(NewOpc, DL, VT,
3140                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3141 }
3142 
3143 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3144                                int Pattern) {
3145   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3146                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3147 }
3148 
3149 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3150                                                      SelectionDAG &DAG) const {
3151   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3152   SDLoc dl(Op);
3153   switch (IntNo) {
3154   default: return SDValue();    // Don't custom lower most intrinsics.
3155   case Intrinsic::thread_pointer: {
3156     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3157     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3158   }
3159   case Intrinsic::aarch64_neon_abs: {
3160     EVT Ty = Op.getValueType();
3161     if (Ty == MVT::i64) {
3162       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3163                                    Op.getOperand(1));
3164       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3165       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3166     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3167       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3168     } else {
3169       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3170     }
3171   }
3172   case Intrinsic::aarch64_neon_smax:
3173     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3174                        Op.getOperand(1), Op.getOperand(2));
3175   case Intrinsic::aarch64_neon_umax:
3176     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3177                        Op.getOperand(1), Op.getOperand(2));
3178   case Intrinsic::aarch64_neon_smin:
3179     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3180                        Op.getOperand(1), Op.getOperand(2));
3181   case Intrinsic::aarch64_neon_umin:
3182     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3183                        Op.getOperand(1), Op.getOperand(2));
3184 
3185   case Intrinsic::aarch64_sve_sunpkhi:
3186     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3187                        Op.getOperand(1));
3188   case Intrinsic::aarch64_sve_sunpklo:
3189     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3190                        Op.getOperand(1));
3191   case Intrinsic::aarch64_sve_uunpkhi:
3192     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3193                        Op.getOperand(1));
3194   case Intrinsic::aarch64_sve_uunpklo:
3195     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3196                        Op.getOperand(1));
3197   case Intrinsic::aarch64_sve_clasta_n:
3198     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3199                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3200   case Intrinsic::aarch64_sve_clastb_n:
3201     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3202                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3203   case Intrinsic::aarch64_sve_lasta:
3204     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3205                        Op.getOperand(1), Op.getOperand(2));
3206   case Intrinsic::aarch64_sve_lastb:
3207     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3208                        Op.getOperand(1), Op.getOperand(2));
3209   case Intrinsic::aarch64_sve_rev:
3210     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3211                        Op.getOperand(1));
3212   case Intrinsic::aarch64_sve_tbl:
3213     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3214                        Op.getOperand(1), Op.getOperand(2));
3215   case Intrinsic::aarch64_sve_trn1:
3216     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3217                        Op.getOperand(1), Op.getOperand(2));
3218   case Intrinsic::aarch64_sve_trn2:
3219     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3220                        Op.getOperand(1), Op.getOperand(2));
3221   case Intrinsic::aarch64_sve_uzp1:
3222     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3223                        Op.getOperand(1), Op.getOperand(2));
3224   case Intrinsic::aarch64_sve_uzp2:
3225     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3226                        Op.getOperand(1), Op.getOperand(2));
3227   case Intrinsic::aarch64_sve_zip1:
3228     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3229                        Op.getOperand(1), Op.getOperand(2));
3230   case Intrinsic::aarch64_sve_zip2:
3231     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3232                        Op.getOperand(1), Op.getOperand(2));
3233   case Intrinsic::aarch64_sve_ptrue:
3234     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3235                        Op.getOperand(1));
3236   case Intrinsic::aarch64_sve_dupq_lane:
3237     return LowerDUPQLane(Op, DAG);
3238   case Intrinsic::aarch64_sve_convert_from_svbool:
3239     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3240                        Op.getOperand(1));
3241   case Intrinsic::aarch64_sve_convert_to_svbool: {
3242     EVT OutVT = Op.getValueType();
3243     EVT InVT = Op.getOperand(1).getValueType();
3244     // Return the operand if the cast isn't changing type,
3245     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3246     if (InVT == OutVT)
3247       return Op.getOperand(1);
3248     // Otherwise, zero the newly introduced lanes.
3249     SDValue Reinterpret =
3250         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3251     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3252     SDValue MaskReinterpret =
3253         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3254     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3255   }
3256 
3257   case Intrinsic::aarch64_sve_insr: {
3258     SDValue Scalar = Op.getOperand(2);
3259     EVT ScalarTy = Scalar.getValueType();
3260     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3261       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3262 
3263     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3264                        Op.getOperand(1), Scalar);
3265   }
3266 
3267   case Intrinsic::localaddress: {
3268     const auto &MF = DAG.getMachineFunction();
3269     const auto *RegInfo = Subtarget->getRegisterInfo();
3270     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3271     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3272                               Op.getSimpleValueType());
3273   }
3274 
3275   case Intrinsic::eh_recoverfp: {
3276     // FIXME: This needs to be implemented to correctly handle highly aligned
3277     // stack objects. For now we simply return the incoming FP. Refer D53541
3278     // for more details.
3279     SDValue FnOp = Op.getOperand(1);
3280     SDValue IncomingFPOp = Op.getOperand(2);
3281     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3282     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3283     if (!Fn)
3284       report_fatal_error(
3285           "llvm.eh.recoverfp must take a function as the first argument");
3286     return IncomingFPOp;
3287   }
3288 
3289   case Intrinsic::aarch64_neon_vsri:
3290   case Intrinsic::aarch64_neon_vsli: {
3291     EVT Ty = Op.getValueType();
3292 
3293     if (!Ty.isVector())
3294       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3295 
3296     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3297 
3298     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3299     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3300     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3301                        Op.getOperand(3));
3302   }
3303 
3304   case Intrinsic::aarch64_neon_srhadd:
3305   case Intrinsic::aarch64_neon_urhadd: {
3306     bool IsSignedAdd = IntNo == Intrinsic::aarch64_neon_srhadd;
3307     unsigned Opcode = IsSignedAdd ? AArch64ISD::SRHADD : AArch64ISD::URHADD;
3308     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3309                        Op.getOperand(2));
3310   }
3311   }
3312 }
3313 
3314 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3315   return ExtVal.getValueType().isScalableVector();
3316 }
3317 
3318 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3319 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3320                                         EVT VT, EVT MemVT,
3321                                         SelectionDAG &DAG) {
3322   assert(VT.isVector() && "VT should be a vector type");
3323   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3324 
3325   SDValue Value = ST->getValue();
3326 
3327   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3328   // the word lane which represent the v4i8 subvector.  It optimizes the store
3329   // to:
3330   //
3331   //   xtn  v0.8b, v0.8h
3332   //   str  s0, [x0]
3333 
3334   SDValue Undef = DAG.getUNDEF(MVT::i16);
3335   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3336                                         {Undef, Undef, Undef, Undef});
3337 
3338   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3339                                  Value, UndefVec);
3340   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3341 
3342   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3343   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3344                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3345 
3346   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3347                       ST->getBasePtr(), ST->getMemOperand());
3348 }
3349 
3350 // Custom lowering for any store, vector or scalar and/or default or with
3351 // a truncate operations.  Currently only custom lower truncate operation
3352 // from vector v4i16 to v4i8 or volatile stores of i128.
3353 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3354                                           SelectionDAG &DAG) const {
3355   SDLoc Dl(Op);
3356   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3357   assert (StoreNode && "Can only custom lower store nodes");
3358 
3359   SDValue Value = StoreNode->getValue();
3360 
3361   EVT VT = Value.getValueType();
3362   EVT MemVT = StoreNode->getMemoryVT();
3363 
3364   if (VT.isVector()) {
3365     if (useSVEForFixedLengthVectorVT(VT))
3366       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3367 
3368     unsigned AS = StoreNode->getAddressSpace();
3369     Align Alignment = StoreNode->getAlign();
3370     if (Alignment < MemVT.getStoreSize() &&
3371         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3372                                         StoreNode->getMemOperand()->getFlags(),
3373                                         nullptr)) {
3374       return scalarizeVectorStore(StoreNode, DAG);
3375     }
3376 
3377     if (StoreNode->isTruncatingStore()) {
3378       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3379     }
3380     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3381     // the custom lowering, as there are no un-paired non-temporal stores and
3382     // legalization will break up 256 bit inputs.
3383     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3384         MemVT.getVectorElementCount().Min % 2u == 0 &&
3385         ((MemVT.getScalarSizeInBits() == 8u ||
3386           MemVT.getScalarSizeInBits() == 16u ||
3387           MemVT.getScalarSizeInBits() == 32u ||
3388           MemVT.getScalarSizeInBits() == 64u))) {
3389       SDValue Lo =
3390           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3391                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3392                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3393       SDValue Hi = DAG.getNode(
3394           ISD::EXTRACT_SUBVECTOR, Dl,
3395           MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3396           StoreNode->getValue(),
3397           DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3398       SDValue Result = DAG.getMemIntrinsicNode(
3399           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3400           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3401           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3402       return Result;
3403     }
3404   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3405     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3406     SDValue Lo =
3407         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3408                     DAG.getConstant(0, Dl, MVT::i64));
3409     SDValue Hi =
3410         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3411                     DAG.getConstant(1, Dl, MVT::i64));
3412     SDValue Result = DAG.getMemIntrinsicNode(
3413         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3414         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3415         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3416     return Result;
3417   }
3418 
3419   return SDValue();
3420 }
3421 
3422 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3423                                               SelectionDAG &DAG) const {
3424   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3425   LLVM_DEBUG(Op.dump());
3426 
3427   switch (Op.getOpcode()) {
3428   default:
3429     llvm_unreachable("unimplemented operand");
3430     return SDValue();
3431   case ISD::BITCAST:
3432     return LowerBITCAST(Op, DAG);
3433   case ISD::GlobalAddress:
3434     return LowerGlobalAddress(Op, DAG);
3435   case ISD::GlobalTLSAddress:
3436     return LowerGlobalTLSAddress(Op, DAG);
3437   case ISD::SETCC:
3438   case ISD::STRICT_FSETCC:
3439   case ISD::STRICT_FSETCCS:
3440     return LowerSETCC(Op, DAG);
3441   case ISD::BR_CC:
3442     return LowerBR_CC(Op, DAG);
3443   case ISD::SELECT:
3444     return LowerSELECT(Op, DAG);
3445   case ISD::SELECT_CC:
3446     return LowerSELECT_CC(Op, DAG);
3447   case ISD::JumpTable:
3448     return LowerJumpTable(Op, DAG);
3449   case ISD::BR_JT:
3450     return LowerBR_JT(Op, DAG);
3451   case ISD::ConstantPool:
3452     return LowerConstantPool(Op, DAG);
3453   case ISD::BlockAddress:
3454     return LowerBlockAddress(Op, DAG);
3455   case ISD::VASTART:
3456     return LowerVASTART(Op, DAG);
3457   case ISD::VACOPY:
3458     return LowerVACOPY(Op, DAG);
3459   case ISD::VAARG:
3460     return LowerVAARG(Op, DAG);
3461   case ISD::ADDC:
3462   case ISD::ADDE:
3463   case ISD::SUBC:
3464   case ISD::SUBE:
3465     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3466   case ISD::SADDO:
3467   case ISD::UADDO:
3468   case ISD::SSUBO:
3469   case ISD::USUBO:
3470   case ISD::SMULO:
3471   case ISD::UMULO:
3472     return LowerXALUO(Op, DAG);
3473   case ISD::FADD:
3474     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3475       return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3476     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3477   case ISD::FSUB:
3478     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3479   case ISD::FMUL:
3480     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3481   case ISD::FMA:
3482     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3483   case ISD::FDIV:
3484     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3485   case ISD::FP_ROUND:
3486   case ISD::STRICT_FP_ROUND:
3487     return LowerFP_ROUND(Op, DAG);
3488   case ISD::FP_EXTEND:
3489     return LowerFP_EXTEND(Op, DAG);
3490   case ISD::FRAMEADDR:
3491     return LowerFRAMEADDR(Op, DAG);
3492   case ISD::SPONENTRY:
3493     return LowerSPONENTRY(Op, DAG);
3494   case ISD::RETURNADDR:
3495     return LowerRETURNADDR(Op, DAG);
3496   case ISD::ADDROFRETURNADDR:
3497     return LowerADDROFRETURNADDR(Op, DAG);
3498   case ISD::INSERT_VECTOR_ELT:
3499     return LowerINSERT_VECTOR_ELT(Op, DAG);
3500   case ISD::EXTRACT_VECTOR_ELT:
3501     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3502   case ISD::BUILD_VECTOR:
3503     return LowerBUILD_VECTOR(Op, DAG);
3504   case ISD::VECTOR_SHUFFLE:
3505     return LowerVECTOR_SHUFFLE(Op, DAG);
3506   case ISD::SPLAT_VECTOR:
3507     return LowerSPLAT_VECTOR(Op, DAG);
3508   case ISD::EXTRACT_SUBVECTOR:
3509     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3510   case ISD::INSERT_SUBVECTOR:
3511     return LowerINSERT_SUBVECTOR(Op, DAG);
3512   case ISD::SDIV:
3513     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SDIV_PRED);
3514   case ISD::UDIV:
3515     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UDIV_PRED);
3516   case ISD::SMIN:
3517     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_MERGE_OP1);
3518   case ISD::UMIN:
3519     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_MERGE_OP1);
3520   case ISD::SMAX:
3521     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_MERGE_OP1);
3522   case ISD::UMAX:
3523     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_MERGE_OP1);
3524   case ISD::SRA:
3525   case ISD::SRL:
3526   case ISD::SHL:
3527     return LowerVectorSRA_SRL_SHL(Op, DAG);
3528   case ISD::SHL_PARTS:
3529     return LowerShiftLeftParts(Op, DAG);
3530   case ISD::SRL_PARTS:
3531   case ISD::SRA_PARTS:
3532     return LowerShiftRightParts(Op, DAG);
3533   case ISD::CTPOP:
3534     return LowerCTPOP(Op, DAG);
3535   case ISD::FCOPYSIGN:
3536     return LowerFCOPYSIGN(Op, DAG);
3537   case ISD::OR:
3538     return LowerVectorOR(Op, DAG);
3539   case ISD::XOR:
3540     return LowerXOR(Op, DAG);
3541   case ISD::PREFETCH:
3542     return LowerPREFETCH(Op, DAG);
3543   case ISD::SINT_TO_FP:
3544   case ISD::UINT_TO_FP:
3545   case ISD::STRICT_SINT_TO_FP:
3546   case ISD::STRICT_UINT_TO_FP:
3547     return LowerINT_TO_FP(Op, DAG);
3548   case ISD::FP_TO_SINT:
3549   case ISD::FP_TO_UINT:
3550   case ISD::STRICT_FP_TO_SINT:
3551   case ISD::STRICT_FP_TO_UINT:
3552     return LowerFP_TO_INT(Op, DAG);
3553   case ISD::FSINCOS:
3554     return LowerFSINCOS(Op, DAG);
3555   case ISD::FLT_ROUNDS_:
3556     return LowerFLT_ROUNDS_(Op, DAG);
3557   case ISD::MUL:
3558     return LowerMUL(Op, DAG);
3559   case ISD::INTRINSIC_WO_CHAIN:
3560     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3561   case ISD::STORE:
3562     return LowerSTORE(Op, DAG);
3563   case ISD::VECREDUCE_ADD:
3564   case ISD::VECREDUCE_SMAX:
3565   case ISD::VECREDUCE_SMIN:
3566   case ISD::VECREDUCE_UMAX:
3567   case ISD::VECREDUCE_UMIN:
3568   case ISD::VECREDUCE_FMAX:
3569   case ISD::VECREDUCE_FMIN:
3570     return LowerVECREDUCE(Op, DAG);
3571   case ISD::ATOMIC_LOAD_SUB:
3572     return LowerATOMIC_LOAD_SUB(Op, DAG);
3573   case ISD::ATOMIC_LOAD_AND:
3574     return LowerATOMIC_LOAD_AND(Op, DAG);
3575   case ISD::DYNAMIC_STACKALLOC:
3576     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3577   case ISD::VSCALE:
3578     return LowerVSCALE(Op, DAG);
3579   case ISD::TRUNCATE:
3580     return LowerTRUNCATE(Op, DAG);
3581   case ISD::LOAD:
3582     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3583       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
3584     llvm_unreachable("Unexpected request to lower ISD::LOAD");
3585   case ISD::ADD:
3586     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3587       return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
3588     llvm_unreachable("Unexpected request to lower ISD::ADD");
3589   }
3590 }
3591 
3592 bool AArch64TargetLowering::useSVEForFixedLengthVectors() const {
3593   // Prefer NEON unless larger SVE registers are available.
3594   return Subtarget->hasSVE() && Subtarget->getMinSVEVectorSizeInBits() >= 256;
3595 }
3596 
3597 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(EVT VT) const {
3598   if (!useSVEForFixedLengthVectors())
3599     return false;
3600 
3601   if (!VT.isFixedLengthVector())
3602     return false;
3603 
3604   // Fixed length predicates should be promoted to i8.
3605   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
3606   if (VT.getVectorElementType() == MVT::i1)
3607     return false;
3608 
3609   // Don't use SVE for vectors we cannot scalarize if required.
3610   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
3611   default:
3612     return false;
3613   case MVT::i8:
3614   case MVT::i16:
3615   case MVT::i32:
3616   case MVT::i64:
3617   case MVT::f16:
3618   case MVT::f32:
3619   case MVT::f64:
3620     break;
3621   }
3622 
3623   // Ensure NEON MVTs only belong to a single register class.
3624   if (VT.getSizeInBits() <= 128)
3625     return false;
3626 
3627   // Don't use SVE for types that don't fit.
3628   if (VT.getSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
3629     return false;
3630 
3631   // TODO: Perhaps an artificial restriction, but worth having whilst getting
3632   // the base fixed length SVE support in place.
3633   if (!VT.isPow2VectorType())
3634     return false;
3635 
3636   return true;
3637 }
3638 
3639 //===----------------------------------------------------------------------===//
3640 //                      Calling Convention Implementation
3641 //===----------------------------------------------------------------------===//
3642 
3643 /// Selects the correct CCAssignFn for a given CallingConvention value.
3644 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3645                                                      bool IsVarArg) const {
3646   switch (CC) {
3647   default:
3648     report_fatal_error("Unsupported calling convention.");
3649   case CallingConv::WebKit_JS:
3650     return CC_AArch64_WebKit_JS;
3651   case CallingConv::GHC:
3652     return CC_AArch64_GHC;
3653   case CallingConv::C:
3654   case CallingConv::Fast:
3655   case CallingConv::PreserveMost:
3656   case CallingConv::CXX_FAST_TLS:
3657   case CallingConv::Swift:
3658     if (Subtarget->isTargetWindows() && IsVarArg)
3659       return CC_AArch64_Win64_VarArg;
3660     if (!Subtarget->isTargetDarwin())
3661       return CC_AArch64_AAPCS;
3662     if (!IsVarArg)
3663       return CC_AArch64_DarwinPCS;
3664     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3665                                       : CC_AArch64_DarwinPCS_VarArg;
3666    case CallingConv::Win64:
3667     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3668    case CallingConv::CFGuard_Check:
3669      return CC_AArch64_Win64_CFGuard_Check;
3670    case CallingConv::AArch64_VectorCall:
3671    case CallingConv::AArch64_SVE_VectorCall:
3672      return CC_AArch64_AAPCS;
3673   }
3674 }
3675 
3676 CCAssignFn *
3677 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3678   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3679                                       : RetCC_AArch64_AAPCS;
3680 }
3681 
3682 SDValue AArch64TargetLowering::LowerFormalArguments(
3683     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3684     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3685     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3686   MachineFunction &MF = DAG.getMachineFunction();
3687   MachineFrameInfo &MFI = MF.getFrameInfo();
3688   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3689 
3690   // Assign locations to all of the incoming arguments.
3691   SmallVector<CCValAssign, 16> ArgLocs;
3692   DenseMap<unsigned, SDValue> CopiedRegs;
3693   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3694                  *DAG.getContext());
3695 
3696   // At this point, Ins[].VT may already be promoted to i32. To correctly
3697   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3698   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3699   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3700   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3701   // LocVT.
3702   unsigned NumArgs = Ins.size();
3703   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3704   unsigned CurArgIdx = 0;
3705   for (unsigned i = 0; i != NumArgs; ++i) {
3706     MVT ValVT = Ins[i].VT;
3707     if (Ins[i].isOrigArg()) {
3708       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3709       CurArgIdx = Ins[i].getOrigArgIndex();
3710 
3711       // Get type of the original argument.
3712       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3713                                   /*AllowUnknown*/ true);
3714       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3715       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3716       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3717         ValVT = MVT::i8;
3718       else if (ActualMVT == MVT::i16)
3719         ValVT = MVT::i16;
3720     }
3721     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3722     bool Res =
3723         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3724     assert(!Res && "Call operand has unhandled type");
3725     (void)Res;
3726   }
3727   assert(ArgLocs.size() == Ins.size());
3728   SmallVector<SDValue, 16> ArgValues;
3729   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3730     CCValAssign &VA = ArgLocs[i];
3731 
3732     if (Ins[i].Flags.isByVal()) {
3733       // Byval is used for HFAs in the PCS, but the system should work in a
3734       // non-compliant manner for larger structs.
3735       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3736       int Size = Ins[i].Flags.getByValSize();
3737       unsigned NumRegs = (Size + 7) / 8;
3738 
3739       // FIXME: This works on big-endian for composite byvals, which are the common
3740       // case. It should also work for fundamental types too.
3741       unsigned FrameIdx =
3742         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3743       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3744       InVals.push_back(FrameIdxN);
3745 
3746       continue;
3747     }
3748 
3749     SDValue ArgValue;
3750     if (VA.isRegLoc()) {
3751       // Arguments stored in registers.
3752       EVT RegVT = VA.getLocVT();
3753       const TargetRegisterClass *RC;
3754 
3755       if (RegVT == MVT::i32)
3756         RC = &AArch64::GPR32RegClass;
3757       else if (RegVT == MVT::i64)
3758         RC = &AArch64::GPR64RegClass;
3759       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
3760         RC = &AArch64::FPR16RegClass;
3761       else if (RegVT == MVT::f32)
3762         RC = &AArch64::FPR32RegClass;
3763       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3764         RC = &AArch64::FPR64RegClass;
3765       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3766         RC = &AArch64::FPR128RegClass;
3767       else if (RegVT.isScalableVector() &&
3768                RegVT.getVectorElementType() == MVT::i1)
3769         RC = &AArch64::PPRRegClass;
3770       else if (RegVT.isScalableVector())
3771         RC = &AArch64::ZPRRegClass;
3772       else
3773         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3774 
3775       // Transform the arguments in physical registers into virtual ones.
3776       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3777       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3778 
3779       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3780       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3781       // truncate to the right size.
3782       switch (VA.getLocInfo()) {
3783       default:
3784         llvm_unreachable("Unknown loc info!");
3785       case CCValAssign::Full:
3786         break;
3787       case CCValAssign::Indirect:
3788         assert(VA.getValVT().isScalableVector() &&
3789                "Only scalable vectors can be passed indirectly");
3790         break;
3791       case CCValAssign::BCvt:
3792         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3793         break;
3794       case CCValAssign::AExt:
3795       case CCValAssign::SExt:
3796       case CCValAssign::ZExt:
3797         break;
3798       case CCValAssign::AExtUpper:
3799         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3800                                DAG.getConstant(32, DL, RegVT));
3801         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3802         break;
3803       }
3804     } else { // VA.isRegLoc()
3805       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3806       unsigned ArgOffset = VA.getLocMemOffset();
3807       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
3808                               ? VA.getLocVT().getSizeInBits()
3809                               : VA.getValVT().getSizeInBits()) / 8;
3810 
3811       uint32_t BEAlign = 0;
3812       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3813           !Ins[i].Flags.isInConsecutiveRegs())
3814         BEAlign = 8 - ArgSize;
3815 
3816       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3817 
3818       // Create load nodes to retrieve arguments from the stack.
3819       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3820 
3821       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3822       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3823       MVT MemVT = VA.getValVT();
3824 
3825       switch (VA.getLocInfo()) {
3826       default:
3827         break;
3828       case CCValAssign::Trunc:
3829       case CCValAssign::BCvt:
3830         MemVT = VA.getLocVT();
3831         break;
3832       case CCValAssign::Indirect:
3833         assert(VA.getValVT().isScalableVector() &&
3834                "Only scalable vectors can be passed indirectly");
3835         MemVT = VA.getLocVT();
3836         break;
3837       case CCValAssign::SExt:
3838         ExtType = ISD::SEXTLOAD;
3839         break;
3840       case CCValAssign::ZExt:
3841         ExtType = ISD::ZEXTLOAD;
3842         break;
3843       case CCValAssign::AExt:
3844         ExtType = ISD::EXTLOAD;
3845         break;
3846       }
3847 
3848       ArgValue = DAG.getExtLoad(
3849           ExtType, DL, VA.getLocVT(), Chain, FIN,
3850           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3851           MemVT);
3852 
3853     }
3854 
3855     if (VA.getLocInfo() == CCValAssign::Indirect) {
3856       assert(VA.getValVT().isScalableVector() &&
3857            "Only scalable vectors can be passed indirectly");
3858       // If value is passed via pointer - do a load.
3859       ArgValue =
3860           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
3861     }
3862 
3863     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3864       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3865                              ArgValue, DAG.getValueType(MVT::i32));
3866     InVals.push_back(ArgValue);
3867   }
3868 
3869   // varargs
3870   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3871   if (isVarArg) {
3872     if (!Subtarget->isTargetDarwin() || IsWin64) {
3873       // The AAPCS variadic function ABI is identical to the non-variadic
3874       // one. As a result there may be more arguments in registers and we should
3875       // save them for future reference.
3876       // Win64 variadic functions also pass arguments in registers, but all float
3877       // arguments are passed in integer registers.
3878       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3879     }
3880 
3881     // This will point to the next argument passed via stack.
3882     unsigned StackOffset = CCInfo.getNextStackOffset();
3883     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3884     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3885     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3886 
3887     if (MFI.hasMustTailInVarArgFunc()) {
3888       SmallVector<MVT, 2> RegParmTypes;
3889       RegParmTypes.push_back(MVT::i64);
3890       RegParmTypes.push_back(MVT::f128);
3891       // Compute the set of forwarded registers. The rest are scratch.
3892       SmallVectorImpl<ForwardedRegister> &Forwards =
3893                                        FuncInfo->getForwardedMustTailRegParms();
3894       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3895                                                CC_AArch64_AAPCS);
3896 
3897       // Conservatively forward X8, since it might be used for aggregate return.
3898       if (!CCInfo.isAllocated(AArch64::X8)) {
3899         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3900         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3901       }
3902     }
3903   }
3904 
3905   // On Windows, InReg pointers must be returned, so record the pointer in a
3906   // virtual register at the start of the function so it can be returned in the
3907   // epilogue.
3908   if (IsWin64) {
3909     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3910       if (Ins[I].Flags.isInReg()) {
3911         assert(!FuncInfo->getSRetReturnReg());
3912 
3913         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3914         Register Reg =
3915             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3916         FuncInfo->setSRetReturnReg(Reg);
3917 
3918         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3919         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3920         break;
3921       }
3922     }
3923   }
3924 
3925   unsigned StackArgSize = CCInfo.getNextStackOffset();
3926   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3927   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3928     // This is a non-standard ABI so by fiat I say we're allowed to make full
3929     // use of the stack area to be popped, which must be aligned to 16 bytes in
3930     // any case:
3931     StackArgSize = alignTo(StackArgSize, 16);
3932 
3933     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3934     // a multiple of 16.
3935     FuncInfo->setArgumentStackToRestore(StackArgSize);
3936 
3937     // This realignment carries over to the available bytes below. Our own
3938     // callers will guarantee the space is free by giving an aligned value to
3939     // CALLSEQ_START.
3940   }
3941   // Even if we're not expected to free up the space, it's useful to know how
3942   // much is there while considering tail calls (because we can reuse it).
3943   FuncInfo->setBytesInStackArgArea(StackArgSize);
3944 
3945   if (Subtarget->hasCustomCallingConv())
3946     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3947 
3948   return Chain;
3949 }
3950 
3951 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3952                                                 SelectionDAG &DAG,
3953                                                 const SDLoc &DL,
3954                                                 SDValue &Chain) const {
3955   MachineFunction &MF = DAG.getMachineFunction();
3956   MachineFrameInfo &MFI = MF.getFrameInfo();
3957   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3958   auto PtrVT = getPointerTy(DAG.getDataLayout());
3959   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3960 
3961   SmallVector<SDValue, 8> MemOps;
3962 
3963   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3964                                           AArch64::X3, AArch64::X4, AArch64::X5,
3965                                           AArch64::X6, AArch64::X7 };
3966   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3967   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3968 
3969   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3970   int GPRIdx = 0;
3971   if (GPRSaveSize != 0) {
3972     if (IsWin64) {
3973       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3974       if (GPRSaveSize & 15)
3975         // The extra size here, if triggered, will always be 8.
3976         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3977     } else
3978       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
3979 
3980     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3981 
3982     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3983       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3984       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3985       SDValue Store = DAG.getStore(
3986           Val.getValue(1), DL, Val, FIN,
3987           IsWin64
3988               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3989                                                   GPRIdx,
3990                                                   (i - FirstVariadicGPR) * 8)
3991               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3992       MemOps.push_back(Store);
3993       FIN =
3994           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3995     }
3996   }
3997   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3998   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3999 
4000   if (Subtarget->hasFPARMv8() && !IsWin64) {
4001     static const MCPhysReg FPRArgRegs[] = {
4002         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4003         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4004     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4005     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4006 
4007     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4008     int FPRIdx = 0;
4009     if (FPRSaveSize != 0) {
4010       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4011 
4012       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4013 
4014       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4015         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4016         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4017 
4018         SDValue Store = DAG.getStore(
4019             Val.getValue(1), DL, Val, FIN,
4020             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4021         MemOps.push_back(Store);
4022         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4023                           DAG.getConstant(16, DL, PtrVT));
4024       }
4025     }
4026     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4027     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4028   }
4029 
4030   if (!MemOps.empty()) {
4031     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4032   }
4033 }
4034 
4035 /// LowerCallResult - Lower the result values of a call into the
4036 /// appropriate copies out of appropriate physical registers.
4037 SDValue AArch64TargetLowering::LowerCallResult(
4038     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4039     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4040     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4041     SDValue ThisVal) const {
4042   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4043                           ? RetCC_AArch64_WebKit_JS
4044                           : RetCC_AArch64_AAPCS;
4045   // Assign locations to each value returned by this call.
4046   SmallVector<CCValAssign, 16> RVLocs;
4047   DenseMap<unsigned, SDValue> CopiedRegs;
4048   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4049                  *DAG.getContext());
4050   CCInfo.AnalyzeCallResult(Ins, RetCC);
4051 
4052   // Copy all of the result registers out of their specified physreg.
4053   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4054     CCValAssign VA = RVLocs[i];
4055 
4056     // Pass 'this' value directly from the argument to return value, to avoid
4057     // reg unit interference
4058     if (i == 0 && isThisReturn) {
4059       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4060              "unexpected return calling convention register assignment");
4061       InVals.push_back(ThisVal);
4062       continue;
4063     }
4064 
4065     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4066     // allows one use of a physreg per block.
4067     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4068     if (!Val) {
4069       Val =
4070           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4071       Chain = Val.getValue(1);
4072       InFlag = Val.getValue(2);
4073       CopiedRegs[VA.getLocReg()] = Val;
4074     }
4075 
4076     switch (VA.getLocInfo()) {
4077     default:
4078       llvm_unreachable("Unknown loc info!");
4079     case CCValAssign::Full:
4080       break;
4081     case CCValAssign::BCvt:
4082       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4083       break;
4084     case CCValAssign::AExtUpper:
4085       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4086                         DAG.getConstant(32, DL, VA.getLocVT()));
4087       LLVM_FALLTHROUGH;
4088     case CCValAssign::AExt:
4089       LLVM_FALLTHROUGH;
4090     case CCValAssign::ZExt:
4091       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4092       break;
4093     }
4094 
4095     InVals.push_back(Val);
4096   }
4097 
4098   return Chain;
4099 }
4100 
4101 /// Return true if the calling convention is one that we can guarantee TCO for.
4102 static bool canGuaranteeTCO(CallingConv::ID CC) {
4103   return CC == CallingConv::Fast;
4104 }
4105 
4106 /// Return true if we might ever do TCO for calls with this calling convention.
4107 static bool mayTailCallThisCC(CallingConv::ID CC) {
4108   switch (CC) {
4109   case CallingConv::C:
4110   case CallingConv::AArch64_SVE_VectorCall:
4111   case CallingConv::PreserveMost:
4112   case CallingConv::Swift:
4113     return true;
4114   default:
4115     return canGuaranteeTCO(CC);
4116   }
4117 }
4118 
4119 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4120     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4121     const SmallVectorImpl<ISD::OutputArg> &Outs,
4122     const SmallVectorImpl<SDValue> &OutVals,
4123     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4124   if (!mayTailCallThisCC(CalleeCC))
4125     return false;
4126 
4127   MachineFunction &MF = DAG.getMachineFunction();
4128   const Function &CallerF = MF.getFunction();
4129   CallingConv::ID CallerCC = CallerF.getCallingConv();
4130 
4131   // If this function uses the C calling convention but has an SVE signature,
4132   // then it preserves more registers and should assume the SVE_VectorCall CC.
4133   // The check for matching callee-saved regs will determine whether it is
4134   // eligible for TCO.
4135   if (CallerCC == CallingConv::C &&
4136       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
4137     CallerCC = CallingConv::AArch64_SVE_VectorCall;
4138 
4139   bool CCMatch = CallerCC == CalleeCC;
4140 
4141   // When using the Windows calling convention on a non-windows OS, we want
4142   // to back up and restore X18 in such functions; we can't do a tail call
4143   // from those functions.
4144   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4145       CalleeCC != CallingConv::Win64)
4146     return false;
4147 
4148   // Byval parameters hand the function a pointer directly into the stack area
4149   // we want to reuse during a tail call. Working around this *is* possible (see
4150   // X86) but less efficient and uglier in LowerCall.
4151   for (Function::const_arg_iterator i = CallerF.arg_begin(),
4152                                     e = CallerF.arg_end();
4153        i != e; ++i) {
4154     if (i->hasByValAttr())
4155       return false;
4156 
4157     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4158     // In this case, it is necessary to save/restore X0 in the callee. Tail
4159     // call opt interferes with this. So we disable tail call opt when the
4160     // caller has an argument with "inreg" attribute.
4161 
4162     // FIXME: Check whether the callee also has an "inreg" argument.
4163     if (i->hasInRegAttr())
4164       return false;
4165   }
4166 
4167   if (getTargetMachine().Options.GuaranteedTailCallOpt)
4168     return canGuaranteeTCO(CalleeCC) && CCMatch;
4169 
4170   // Externally-defined functions with weak linkage should not be
4171   // tail-called on AArch64 when the OS does not support dynamic
4172   // pre-emption of symbols, as the AAELF spec requires normal calls
4173   // to undefined weak functions to be replaced with a NOP or jump to the
4174   // next instruction. The behaviour of branch instructions in this
4175   // situation (as used for tail calls) is implementation-defined, so we
4176   // cannot rely on the linker replacing the tail call with a return.
4177   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4178     const GlobalValue *GV = G->getGlobal();
4179     const Triple &TT = getTargetMachine().getTargetTriple();
4180     if (GV->hasExternalWeakLinkage() &&
4181         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4182       return false;
4183   }
4184 
4185   // Now we search for cases where we can use a tail call without changing the
4186   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4187   // concept.
4188 
4189   // I want anyone implementing a new calling convention to think long and hard
4190   // about this assert.
4191   assert((!isVarArg || CalleeCC == CallingConv::C) &&
4192          "Unexpected variadic calling convention");
4193 
4194   LLVMContext &C = *DAG.getContext();
4195   if (isVarArg && !Outs.empty()) {
4196     // At least two cases here: if caller is fastcc then we can't have any
4197     // memory arguments (we'd be expected to clean up the stack afterwards). If
4198     // caller is C then we could potentially use its argument area.
4199 
4200     // FIXME: for now we take the most conservative of these in both cases:
4201     // disallow all variadic memory operands.
4202     SmallVector<CCValAssign, 16> ArgLocs;
4203     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4204 
4205     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4206     for (const CCValAssign &ArgLoc : ArgLocs)
4207       if (!ArgLoc.isRegLoc())
4208         return false;
4209   }
4210 
4211   // Check that the call results are passed in the same way.
4212   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4213                                   CCAssignFnForCall(CalleeCC, isVarArg),
4214                                   CCAssignFnForCall(CallerCC, isVarArg)))
4215     return false;
4216   // The callee has to preserve all registers the caller needs to preserve.
4217   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4218   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4219   if (!CCMatch) {
4220     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4221     if (Subtarget->hasCustomCallingConv()) {
4222       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4223       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4224     }
4225     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4226       return false;
4227   }
4228 
4229   // Nothing more to check if the callee is taking no arguments
4230   if (Outs.empty())
4231     return true;
4232 
4233   SmallVector<CCValAssign, 16> ArgLocs;
4234   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4235 
4236   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4237 
4238   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4239 
4240   // If any of the arguments is passed indirectly, it must be SVE, so the
4241   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4242   // allocate space on the stack. That is why we determine this explicitly here
4243   // the call cannot be a tailcall.
4244   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4245         assert((A.getLocInfo() != CCValAssign::Indirect ||
4246                 A.getValVT().isScalableVector()) &&
4247                "Expected value to be scalable");
4248         return A.getLocInfo() == CCValAssign::Indirect;
4249       }))
4250     return false;
4251 
4252   // If the stack arguments for this call do not fit into our own save area then
4253   // the call cannot be made tail.
4254   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4255     return false;
4256 
4257   const MachineRegisterInfo &MRI = MF.getRegInfo();
4258   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4259     return false;
4260 
4261   return true;
4262 }
4263 
4264 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4265                                                    SelectionDAG &DAG,
4266                                                    MachineFrameInfo &MFI,
4267                                                    int ClobberedFI) const {
4268   SmallVector<SDValue, 8> ArgChains;
4269   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4270   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4271 
4272   // Include the original chain at the beginning of the list. When this is
4273   // used by target LowerCall hooks, this helps legalize find the
4274   // CALLSEQ_BEGIN node.
4275   ArgChains.push_back(Chain);
4276 
4277   // Add a chain value for each stack argument corresponding
4278   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4279                             UE = DAG.getEntryNode().getNode()->use_end();
4280        U != UE; ++U)
4281     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4282       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4283         if (FI->getIndex() < 0) {
4284           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4285           int64_t InLastByte = InFirstByte;
4286           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4287 
4288           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4289               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4290             ArgChains.push_back(SDValue(L, 1));
4291         }
4292 
4293   // Build a tokenfactor for all the chains.
4294   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4295 }
4296 
4297 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4298                                                    bool TailCallOpt) const {
4299   return CallCC == CallingConv::Fast && TailCallOpt;
4300 }
4301 
4302 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4303 /// and add input and output parameter nodes.
4304 SDValue
4305 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4306                                  SmallVectorImpl<SDValue> &InVals) const {
4307   SelectionDAG &DAG = CLI.DAG;
4308   SDLoc &DL = CLI.DL;
4309   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4310   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4311   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4312   SDValue Chain = CLI.Chain;
4313   SDValue Callee = CLI.Callee;
4314   bool &IsTailCall = CLI.IsTailCall;
4315   CallingConv::ID CallConv = CLI.CallConv;
4316   bool IsVarArg = CLI.IsVarArg;
4317 
4318   MachineFunction &MF = DAG.getMachineFunction();
4319   MachineFunction::CallSiteInfo CSInfo;
4320   bool IsThisReturn = false;
4321 
4322   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4323   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4324   bool IsSibCall = false;
4325 
4326   // Check callee args/returns for SVE registers and set calling convention
4327   // accordingly.
4328   if (CallConv == CallingConv::C) {
4329     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4330       return Out.VT.isScalableVector();
4331     });
4332     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4333       return In.VT.isScalableVector();
4334     });
4335 
4336     if (CalleeInSVE || CalleeOutSVE)
4337       CallConv = CallingConv::AArch64_SVE_VectorCall;
4338   }
4339 
4340   if (IsTailCall) {
4341     // Check if it's really possible to do a tail call.
4342     IsTailCall = isEligibleForTailCallOptimization(
4343         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4344     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4345       report_fatal_error("failed to perform tail call elimination on a call "
4346                          "site marked musttail");
4347 
4348     // A sibling call is one where we're under the usual C ABI and not planning
4349     // to change that but can still do a tail call:
4350     if (!TailCallOpt && IsTailCall)
4351       IsSibCall = true;
4352 
4353     if (IsTailCall)
4354       ++NumTailCalls;
4355   }
4356 
4357   // Analyze operands of the call, assigning locations to each operand.
4358   SmallVector<CCValAssign, 16> ArgLocs;
4359   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4360                  *DAG.getContext());
4361 
4362   if (IsVarArg) {
4363     // Handle fixed and variable vector arguments differently.
4364     // Variable vector arguments always go into memory.
4365     unsigned NumArgs = Outs.size();
4366 
4367     for (unsigned i = 0; i != NumArgs; ++i) {
4368       MVT ArgVT = Outs[i].VT;
4369       if (!Outs[i].IsFixed && ArgVT.isScalableVector())
4370         report_fatal_error("Passing SVE types to variadic functions is "
4371                            "currently not supported");
4372 
4373       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4374       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4375                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4376       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4377       assert(!Res && "Call operand has unhandled type");
4378       (void)Res;
4379     }
4380   } else {
4381     // At this point, Outs[].VT may already be promoted to i32. To correctly
4382     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4383     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4384     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4385     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4386     // LocVT.
4387     unsigned NumArgs = Outs.size();
4388     for (unsigned i = 0; i != NumArgs; ++i) {
4389       MVT ValVT = Outs[i].VT;
4390       // Get type of the original argument.
4391       EVT ActualVT = getValueType(DAG.getDataLayout(),
4392                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4393                                   /*AllowUnknown*/ true);
4394       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4395       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4396       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4397       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4398         ValVT = MVT::i8;
4399       else if (ActualMVT == MVT::i16)
4400         ValVT = MVT::i16;
4401 
4402       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4403       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4404       assert(!Res && "Call operand has unhandled type");
4405       (void)Res;
4406     }
4407   }
4408 
4409   // Get a count of how many bytes are to be pushed on the stack.
4410   unsigned NumBytes = CCInfo.getNextStackOffset();
4411 
4412   if (IsSibCall) {
4413     // Since we're not changing the ABI to make this a tail call, the memory
4414     // operands are already available in the caller's incoming argument space.
4415     NumBytes = 0;
4416   }
4417 
4418   // FPDiff is the byte offset of the call's argument area from the callee's.
4419   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4420   // by this amount for a tail call. In a sibling call it must be 0 because the
4421   // caller will deallocate the entire stack and the callee still expects its
4422   // arguments to begin at SP+0. Completely unused for non-tail calls.
4423   int FPDiff = 0;
4424 
4425   if (IsTailCall && !IsSibCall) {
4426     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4427 
4428     // Since callee will pop argument stack as a tail call, we must keep the
4429     // popped size 16-byte aligned.
4430     NumBytes = alignTo(NumBytes, 16);
4431 
4432     // FPDiff will be negative if this tail call requires more space than we
4433     // would automatically have in our incoming argument space. Positive if we
4434     // can actually shrink the stack.
4435     FPDiff = NumReusableBytes - NumBytes;
4436 
4437     // The stack pointer must be 16-byte aligned at all times it's used for a
4438     // memory operation, which in practice means at *all* times and in
4439     // particular across call boundaries. Therefore our own arguments started at
4440     // a 16-byte aligned SP and the delta applied for the tail call should
4441     // satisfy the same constraint.
4442     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4443   }
4444 
4445   // Adjust the stack pointer for the new arguments...
4446   // These operations are automatically eliminated by the prolog/epilog pass
4447   if (!IsSibCall)
4448     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4449 
4450   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4451                                         getPointerTy(DAG.getDataLayout()));
4452 
4453   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4454   SmallSet<unsigned, 8> RegsUsed;
4455   SmallVector<SDValue, 8> MemOpChains;
4456   auto PtrVT = getPointerTy(DAG.getDataLayout());
4457 
4458   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4459     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4460     for (const auto &F : Forwards) {
4461       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4462        RegsToPass.emplace_back(F.PReg, Val);
4463     }
4464   }
4465 
4466   // Walk the register/memloc assignments, inserting copies/loads.
4467   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4468     CCValAssign &VA = ArgLocs[i];
4469     SDValue Arg = OutVals[i];
4470     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4471 
4472     // Promote the value if needed.
4473     switch (VA.getLocInfo()) {
4474     default:
4475       llvm_unreachable("Unknown loc info!");
4476     case CCValAssign::Full:
4477       break;
4478     case CCValAssign::SExt:
4479       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4480       break;
4481     case CCValAssign::ZExt:
4482       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4483       break;
4484     case CCValAssign::AExt:
4485       if (Outs[i].ArgVT == MVT::i1) {
4486         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4487         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4488         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4489       }
4490       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4491       break;
4492     case CCValAssign::AExtUpper:
4493       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4494       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4495       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4496                         DAG.getConstant(32, DL, VA.getLocVT()));
4497       break;
4498     case CCValAssign::BCvt:
4499       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4500       break;
4501     case CCValAssign::Trunc:
4502       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4503       break;
4504     case CCValAssign::FPExt:
4505       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4506       break;
4507     case CCValAssign::Indirect:
4508       assert(VA.getValVT().isScalableVector() &&
4509              "Only scalable vectors can be passed indirectly");
4510       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4511       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4512       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
4513       int FI = MFI.CreateStackObject(
4514           VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
4515       MFI.setStackID(FI, TargetStackID::SVEVector);
4516 
4517       SDValue SpillSlot = DAG.getFrameIndex(
4518           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4519       Chain = DAG.getStore(
4520           Chain, DL, Arg, SpillSlot,
4521           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4522       Arg = SpillSlot;
4523       break;
4524     }
4525 
4526     if (VA.isRegLoc()) {
4527       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4528           Outs[0].VT == MVT::i64) {
4529         assert(VA.getLocVT() == MVT::i64 &&
4530                "unexpected calling convention register assignment");
4531         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4532                "unexpected use of 'returned'");
4533         IsThisReturn = true;
4534       }
4535       if (RegsUsed.count(VA.getLocReg())) {
4536         // If this register has already been used then we're trying to pack
4537         // parts of an [N x i32] into an X-register. The extension type will
4538         // take care of putting the two halves in the right place but we have to
4539         // combine them.
4540         SDValue &Bits =
4541             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4542                          [=](const std::pair<unsigned, SDValue> &Elt) {
4543                            return Elt.first == VA.getLocReg();
4544                          })
4545                 ->second;
4546         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4547         // Call site info is used for function's parameter entry value
4548         // tracking. For now we track only simple cases when parameter
4549         // is transferred through whole register.
4550         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4551                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4552                                       return ArgReg.Reg == VA.getLocReg();
4553                                     }),
4554                      CSInfo.end());
4555       } else {
4556         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4557         RegsUsed.insert(VA.getLocReg());
4558         const TargetOptions &Options = DAG.getTarget().Options;
4559         if (Options.EmitCallSiteInfo)
4560           CSInfo.emplace_back(VA.getLocReg(), i);
4561       }
4562     } else {
4563       assert(VA.isMemLoc());
4564 
4565       SDValue DstAddr;
4566       MachinePointerInfo DstInfo;
4567 
4568       // FIXME: This works on big-endian for composite byvals, which are the
4569       // common case. It should also work for fundamental types too.
4570       uint32_t BEAlign = 0;
4571       unsigned OpSize;
4572       if (VA.getLocInfo() == CCValAssign::Indirect)
4573         OpSize = VA.getLocVT().getSizeInBits();
4574       else
4575         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4576                                  : VA.getValVT().getSizeInBits();
4577       OpSize = (OpSize + 7) / 8;
4578       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4579           !Flags.isInConsecutiveRegs()) {
4580         if (OpSize < 8)
4581           BEAlign = 8 - OpSize;
4582       }
4583       unsigned LocMemOffset = VA.getLocMemOffset();
4584       int32_t Offset = LocMemOffset + BEAlign;
4585       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4586       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4587 
4588       if (IsTailCall) {
4589         Offset = Offset + FPDiff;
4590         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4591 
4592         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4593         DstInfo =
4594             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4595 
4596         // Make sure any stack arguments overlapping with where we're storing
4597         // are loaded before this eventual operation. Otherwise they'll be
4598         // clobbered.
4599         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4600       } else {
4601         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4602 
4603         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4604         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4605                                                LocMemOffset);
4606       }
4607 
4608       if (Outs[i].Flags.isByVal()) {
4609         SDValue SizeNode =
4610             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4611         SDValue Cpy = DAG.getMemcpy(
4612             Chain, DL, DstAddr, Arg, SizeNode,
4613             Outs[i].Flags.getNonZeroByValAlign(),
4614             /*isVol = */ false, /*AlwaysInline = */ false,
4615             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4616 
4617         MemOpChains.push_back(Cpy);
4618       } else {
4619         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4620         // promoted to a legal register type i32, we should truncate Arg back to
4621         // i1/i8/i16.
4622         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4623             VA.getValVT() == MVT::i16)
4624           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4625 
4626         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4627         MemOpChains.push_back(Store);
4628       }
4629     }
4630   }
4631 
4632   if (!MemOpChains.empty())
4633     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4634 
4635   // Build a sequence of copy-to-reg nodes chained together with token chain
4636   // and flag operands which copy the outgoing args into the appropriate regs.
4637   SDValue InFlag;
4638   for (auto &RegToPass : RegsToPass) {
4639     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4640                              RegToPass.second, InFlag);
4641     InFlag = Chain.getValue(1);
4642   }
4643 
4644   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4645   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4646   // node so that legalize doesn't hack it.
4647   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4648     auto GV = G->getGlobal();
4649     unsigned OpFlags =
4650         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4651     if (OpFlags & AArch64II::MO_GOT) {
4652       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4653       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4654     } else {
4655       const GlobalValue *GV = G->getGlobal();
4656       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4657     }
4658   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4659     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4660         Subtarget->isTargetMachO()) {
4661       const char *Sym = S->getSymbol();
4662       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4663       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4664     } else {
4665       const char *Sym = S->getSymbol();
4666       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4667     }
4668   }
4669 
4670   // We don't usually want to end the call-sequence here because we would tidy
4671   // the frame up *after* the call, however in the ABI-changing tail-call case
4672   // we've carefully laid out the parameters so that when sp is reset they'll be
4673   // in the correct location.
4674   if (IsTailCall && !IsSibCall) {
4675     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4676                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4677     InFlag = Chain.getValue(1);
4678   }
4679 
4680   std::vector<SDValue> Ops;
4681   Ops.push_back(Chain);
4682   Ops.push_back(Callee);
4683 
4684   if (IsTailCall) {
4685     // Each tail call may have to adjust the stack by a different amount, so
4686     // this information must travel along with the operation for eventual
4687     // consumption by emitEpilogue.
4688     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4689   }
4690 
4691   // Add argument registers to the end of the list so that they are known live
4692   // into the call.
4693   for (auto &RegToPass : RegsToPass)
4694     Ops.push_back(DAG.getRegister(RegToPass.first,
4695                                   RegToPass.second.getValueType()));
4696 
4697   // Add a register mask operand representing the call-preserved registers.
4698   const uint32_t *Mask;
4699   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4700   if (IsThisReturn) {
4701     // For 'this' returns, use the X0-preserving mask if applicable
4702     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4703     if (!Mask) {
4704       IsThisReturn = false;
4705       Mask = TRI->getCallPreservedMask(MF, CallConv);
4706     }
4707   } else
4708     Mask = TRI->getCallPreservedMask(MF, CallConv);
4709 
4710   if (Subtarget->hasCustomCallingConv())
4711     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4712 
4713   if (TRI->isAnyArgRegReserved(MF))
4714     TRI->emitReservedArgRegCallError(MF);
4715 
4716   assert(Mask && "Missing call preserved mask for calling convention");
4717   Ops.push_back(DAG.getRegisterMask(Mask));
4718 
4719   if (InFlag.getNode())
4720     Ops.push_back(InFlag);
4721 
4722   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4723 
4724   // If we're doing a tall call, use a TC_RETURN here rather than an
4725   // actual call instruction.
4726   if (IsTailCall) {
4727     MF.getFrameInfo().setHasTailCall();
4728     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4729     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4730     return Ret;
4731   }
4732 
4733   // Returns a chain and a flag for retval copy to use.
4734   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4735   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4736   InFlag = Chain.getValue(1);
4737   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4738 
4739   uint64_t CalleePopBytes =
4740       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4741 
4742   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4743                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4744                              InFlag, DL);
4745   if (!Ins.empty())
4746     InFlag = Chain.getValue(1);
4747 
4748   // Handle result values, copying them out of physregs into vregs that we
4749   // return.
4750   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4751                          InVals, IsThisReturn,
4752                          IsThisReturn ? OutVals[0] : SDValue());
4753 }
4754 
4755 bool AArch64TargetLowering::CanLowerReturn(
4756     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4757     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4758   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4759                           ? RetCC_AArch64_WebKit_JS
4760                           : RetCC_AArch64_AAPCS;
4761   SmallVector<CCValAssign, 16> RVLocs;
4762   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4763   return CCInfo.CheckReturn(Outs, RetCC);
4764 }
4765 
4766 SDValue
4767 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4768                                    bool isVarArg,
4769                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4770                                    const SmallVectorImpl<SDValue> &OutVals,
4771                                    const SDLoc &DL, SelectionDAG &DAG) const {
4772   auto &MF = DAG.getMachineFunction();
4773   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4774 
4775   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4776                           ? RetCC_AArch64_WebKit_JS
4777                           : RetCC_AArch64_AAPCS;
4778   SmallVector<CCValAssign, 16> RVLocs;
4779   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4780                  *DAG.getContext());
4781   CCInfo.AnalyzeReturn(Outs, RetCC);
4782 
4783   // Copy the result values into the output registers.
4784   SDValue Flag;
4785   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4786   SmallSet<unsigned, 4> RegsUsed;
4787   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4788        ++i, ++realRVLocIdx) {
4789     CCValAssign &VA = RVLocs[i];
4790     assert(VA.isRegLoc() && "Can only return in registers!");
4791     SDValue Arg = OutVals[realRVLocIdx];
4792 
4793     switch (VA.getLocInfo()) {
4794     default:
4795       llvm_unreachable("Unknown loc info!");
4796     case CCValAssign::Full:
4797       if (Outs[i].ArgVT == MVT::i1) {
4798         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4799         // value. This is strictly redundant on Darwin (which uses "zeroext
4800         // i1"), but will be optimised out before ISel.
4801         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4802         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4803       }
4804       break;
4805     case CCValAssign::BCvt:
4806       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4807       break;
4808     case CCValAssign::AExt:
4809     case CCValAssign::ZExt:
4810       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4811       break;
4812     case CCValAssign::AExtUpper:
4813       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4814       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4815       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4816                         DAG.getConstant(32, DL, VA.getLocVT()));
4817       break;
4818     }
4819 
4820     if (RegsUsed.count(VA.getLocReg())) {
4821       SDValue &Bits =
4822           std::find_if(RetVals.begin(), RetVals.end(),
4823                        [=](const std::pair<unsigned, SDValue> &Elt) {
4824                          return Elt.first == VA.getLocReg();
4825                        })
4826               ->second;
4827       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4828     } else {
4829       RetVals.emplace_back(VA.getLocReg(), Arg);
4830       RegsUsed.insert(VA.getLocReg());
4831     }
4832   }
4833 
4834   SmallVector<SDValue, 4> RetOps(1, Chain);
4835   for (auto &RetVal : RetVals) {
4836     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4837     Flag = Chain.getValue(1);
4838     RetOps.push_back(
4839         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4840   }
4841 
4842   // Windows AArch64 ABIs require that for returning structs by value we copy
4843   // the sret argument into X0 for the return.
4844   // We saved the argument into a virtual register in the entry block,
4845   // so now we copy the value out and into X0.
4846   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4847     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4848                                      getPointerTy(MF.getDataLayout()));
4849 
4850     unsigned RetValReg = AArch64::X0;
4851     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4852     Flag = Chain.getValue(1);
4853 
4854     RetOps.push_back(
4855       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4856   }
4857 
4858   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4859   const MCPhysReg *I =
4860       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4861   if (I) {
4862     for (; *I; ++I) {
4863       if (AArch64::GPR64RegClass.contains(*I))
4864         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4865       else if (AArch64::FPR64RegClass.contains(*I))
4866         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4867       else
4868         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4869     }
4870   }
4871 
4872   RetOps[0] = Chain; // Update chain.
4873 
4874   // Add the flag if we have it.
4875   if (Flag.getNode())
4876     RetOps.push_back(Flag);
4877 
4878   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4879 }
4880 
4881 //===----------------------------------------------------------------------===//
4882 //  Other Lowering Code
4883 //===----------------------------------------------------------------------===//
4884 
4885 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4886                                              SelectionDAG &DAG,
4887                                              unsigned Flag) const {
4888   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4889                                     N->getOffset(), Flag);
4890 }
4891 
4892 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4893                                              SelectionDAG &DAG,
4894                                              unsigned Flag) const {
4895   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4896 }
4897 
4898 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4899                                              SelectionDAG &DAG,
4900                                              unsigned Flag) const {
4901   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
4902                                    N->getOffset(), Flag);
4903 }
4904 
4905 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4906                                              SelectionDAG &DAG,
4907                                              unsigned Flag) const {
4908   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4909 }
4910 
4911 // (loadGOT sym)
4912 template <class NodeTy>
4913 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4914                                       unsigned Flags) const {
4915   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4916   SDLoc DL(N);
4917   EVT Ty = getPointerTy(DAG.getDataLayout());
4918   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4919   // FIXME: Once remat is capable of dealing with instructions with register
4920   // operands, expand this into two nodes instead of using a wrapper node.
4921   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4922 }
4923 
4924 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4925 template <class NodeTy>
4926 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4927                                             unsigned Flags) const {
4928   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4929   SDLoc DL(N);
4930   EVT Ty = getPointerTy(DAG.getDataLayout());
4931   const unsigned char MO_NC = AArch64II::MO_NC;
4932   return DAG.getNode(
4933       AArch64ISD::WrapperLarge, DL, Ty,
4934       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4935       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4936       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4937       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4938 }
4939 
4940 // (addlow (adrp %hi(sym)) %lo(sym))
4941 template <class NodeTy>
4942 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4943                                        unsigned Flags) const {
4944   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4945   SDLoc DL(N);
4946   EVT Ty = getPointerTy(DAG.getDataLayout());
4947   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4948   SDValue Lo = getTargetNode(N, Ty, DAG,
4949                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4950   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4951   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4952 }
4953 
4954 // (adr sym)
4955 template <class NodeTy>
4956 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4957                                            unsigned Flags) const {
4958   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4959   SDLoc DL(N);
4960   EVT Ty = getPointerTy(DAG.getDataLayout());
4961   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4962   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4963 }
4964 
4965 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4966                                                   SelectionDAG &DAG) const {
4967   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4968   const GlobalValue *GV = GN->getGlobal();
4969   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4970 
4971   if (OpFlags != AArch64II::MO_NO_FLAG)
4972     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4973            "unexpected offset in global node");
4974 
4975   // This also catches the large code model case for Darwin, and tiny code
4976   // model with got relocations.
4977   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4978     return getGOT(GN, DAG, OpFlags);
4979   }
4980 
4981   SDValue Result;
4982   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4983     Result = getAddrLarge(GN, DAG, OpFlags);
4984   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4985     Result = getAddrTiny(GN, DAG, OpFlags);
4986   } else {
4987     Result = getAddr(GN, DAG, OpFlags);
4988   }
4989   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4990   SDLoc DL(GN);
4991   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4992     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4993                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4994   return Result;
4995 }
4996 
4997 /// Convert a TLS address reference into the correct sequence of loads
4998 /// and calls to compute the variable's address (for Darwin, currently) and
4999 /// return an SDValue containing the final node.
5000 
5001 /// Darwin only has one TLS scheme which must be capable of dealing with the
5002 /// fully general situation, in the worst case. This means:
5003 ///     + "extern __thread" declaration.
5004 ///     + Defined in a possibly unknown dynamic library.
5005 ///
5006 /// The general system is that each __thread variable has a [3 x i64] descriptor
5007 /// which contains information used by the runtime to calculate the address. The
5008 /// only part of this the compiler needs to know about is the first xword, which
5009 /// contains a function pointer that must be called with the address of the
5010 /// entire descriptor in "x0".
5011 ///
5012 /// Since this descriptor may be in a different unit, in general even the
5013 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5014 /// is:
5015 ///     adrp x0, _var@TLVPPAGE
5016 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5017 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5018 ///                                      ; the function pointer
5019 ///     blr x1                           ; Uses descriptor address in x0
5020 ///     ; Address of _var is now in x0.
5021 ///
5022 /// If the address of _var's descriptor *is* known to the linker, then it can
5023 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5024 /// a slight efficiency gain.
5025 SDValue
5026 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5027                                                    SelectionDAG &DAG) const {
5028   assert(Subtarget->isTargetDarwin() &&
5029          "This function expects a Darwin target");
5030 
5031   SDLoc DL(Op);
5032   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5033   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5034   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5035 
5036   SDValue TLVPAddr =
5037       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5038   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5039 
5040   // The first entry in the descriptor is a function pointer that we must call
5041   // to obtain the address of the variable.
5042   SDValue Chain = DAG.getEntryNode();
5043   SDValue FuncTLVGet = DAG.getLoad(
5044       PtrMemVT, DL, Chain, DescAddr,
5045       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5046       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
5047       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5048   Chain = FuncTLVGet.getValue(1);
5049 
5050   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5051   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5052 
5053   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5054   MFI.setAdjustsStack(true);
5055 
5056   // TLS calls preserve all registers except those that absolutely must be
5057   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5058   // silly).
5059   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5060   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5061   if (Subtarget->hasCustomCallingConv())
5062     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5063 
5064   // Finally, we can make the call. This is just a degenerate version of a
5065   // normal AArch64 call node: x0 takes the address of the descriptor, and
5066   // returns the address of the variable in this thread.
5067   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5068   Chain =
5069       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5070                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5071                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5072   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5073 }
5074 
5075 /// Convert a thread-local variable reference into a sequence of instructions to
5076 /// compute the variable's address for the local exec TLS model of ELF targets.
5077 /// The sequence depends on the maximum TLS area size.
5078 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5079                                                     SDValue ThreadBase,
5080                                                     const SDLoc &DL,
5081                                                     SelectionDAG &DAG) const {
5082   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5083   SDValue TPOff, Addr;
5084 
5085   switch (DAG.getTarget().Options.TLSSize) {
5086   default:
5087     llvm_unreachable("Unexpected TLS size");
5088 
5089   case 12: {
5090     // mrs   x0, TPIDR_EL0
5091     // add   x0, x0, :tprel_lo12:a
5092     SDValue Var = DAG.getTargetGlobalAddress(
5093         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5094     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5095                                       Var,
5096                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5097                    0);
5098   }
5099 
5100   case 24: {
5101     // mrs   x0, TPIDR_EL0
5102     // add   x0, x0, :tprel_hi12:a
5103     // add   x0, x0, :tprel_lo12_nc:a
5104     SDValue HiVar = DAG.getTargetGlobalAddress(
5105         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5106     SDValue LoVar = DAG.getTargetGlobalAddress(
5107         GV, DL, PtrVT, 0,
5108         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5109     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5110                                       HiVar,
5111                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5112                    0);
5113     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5114                                       LoVar,
5115                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5116                    0);
5117   }
5118 
5119   case 32: {
5120     // mrs   x1, TPIDR_EL0
5121     // movz  x0, #:tprel_g1:a
5122     // movk  x0, #:tprel_g0_nc:a
5123     // add   x0, x1, x0
5124     SDValue HiVar = DAG.getTargetGlobalAddress(
5125         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5126     SDValue LoVar = DAG.getTargetGlobalAddress(
5127         GV, DL, PtrVT, 0,
5128         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5129     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5130                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5131                     0);
5132     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5133                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5134                     0);
5135     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5136   }
5137 
5138   case 48: {
5139     // mrs   x1, TPIDR_EL0
5140     // movz  x0, #:tprel_g2:a
5141     // movk  x0, #:tprel_g1_nc:a
5142     // movk  x0, #:tprel_g0_nc:a
5143     // add   x0, x1, x0
5144     SDValue HiVar = DAG.getTargetGlobalAddress(
5145         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5146     SDValue MiVar = DAG.getTargetGlobalAddress(
5147         GV, DL, PtrVT, 0,
5148         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5149     SDValue LoVar = DAG.getTargetGlobalAddress(
5150         GV, DL, PtrVT, 0,
5151         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5152     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5153                                        DAG.getTargetConstant(32, DL, MVT::i32)),
5154                     0);
5155     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5156                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5157                     0);
5158     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5159                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5160                     0);
5161     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5162   }
5163   }
5164 }
5165 
5166 /// When accessing thread-local variables under either the general-dynamic or
5167 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5168 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5169 /// is a function pointer to carry out the resolution.
5170 ///
5171 /// The sequence is:
5172 ///    adrp  x0, :tlsdesc:var
5173 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
5174 ///    add   x0, x0, #:tlsdesc_lo12:var
5175 ///    .tlsdesccall var
5176 ///    blr   x1
5177 ///    (TPIDR_EL0 offset now in x0)
5178 ///
5179 ///  The above sequence must be produced unscheduled, to enable the linker to
5180 ///  optimize/relax this sequence.
5181 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5182 ///  above sequence, and expanded really late in the compilation flow, to ensure
5183 ///  the sequence is produced as per above.
5184 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5185                                                       const SDLoc &DL,
5186                                                       SelectionDAG &DAG) const {
5187   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5188 
5189   SDValue Chain = DAG.getEntryNode();
5190   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5191 
5192   Chain =
5193       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5194   SDValue Glue = Chain.getValue(1);
5195 
5196   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5197 }
5198 
5199 SDValue
5200 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5201                                                 SelectionDAG &DAG) const {
5202   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5203 
5204   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5205 
5206   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5207 
5208   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5209     if (Model == TLSModel::LocalDynamic)
5210       Model = TLSModel::GeneralDynamic;
5211   }
5212 
5213   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5214       Model != TLSModel::LocalExec)
5215     report_fatal_error("ELF TLS only supported in small memory model or "
5216                        "in local exec TLS model");
5217   // Different choices can be made for the maximum size of the TLS area for a
5218   // module. For the small address model, the default TLS size is 16MiB and the
5219   // maximum TLS size is 4GiB.
5220   // FIXME: add tiny and large code model support for TLS access models other
5221   // than local exec. We currently generate the same code as small for tiny,
5222   // which may be larger than needed.
5223 
5224   SDValue TPOff;
5225   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5226   SDLoc DL(Op);
5227   const GlobalValue *GV = GA->getGlobal();
5228 
5229   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5230 
5231   if (Model == TLSModel::LocalExec) {
5232     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5233   } else if (Model == TLSModel::InitialExec) {
5234     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5235     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5236   } else if (Model == TLSModel::LocalDynamic) {
5237     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5238     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5239     // the beginning of the module's TLS region, followed by a DTPREL offset
5240     // calculation.
5241 
5242     // These accesses will need deduplicating if there's more than one.
5243     AArch64FunctionInfo *MFI =
5244         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5245     MFI->incNumLocalDynamicTLSAccesses();
5246 
5247     // The call needs a relocation too for linker relaxation. It doesn't make
5248     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5249     // the address.
5250     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5251                                                   AArch64II::MO_TLS);
5252 
5253     // Now we can calculate the offset from TPIDR_EL0 to this module's
5254     // thread-local area.
5255     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5256 
5257     // Now use :dtprel_whatever: operations to calculate this variable's offset
5258     // in its thread-storage area.
5259     SDValue HiVar = DAG.getTargetGlobalAddress(
5260         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5261     SDValue LoVar = DAG.getTargetGlobalAddress(
5262         GV, DL, MVT::i64, 0,
5263         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5264 
5265     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5266                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5267                     0);
5268     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5269                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5270                     0);
5271   } else if (Model == TLSModel::GeneralDynamic) {
5272     // The call needs a relocation too for linker relaxation. It doesn't make
5273     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5274     // the address.
5275     SDValue SymAddr =
5276         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5277 
5278     // Finally we can make a call to calculate the offset from tpidr_el0.
5279     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5280   } else
5281     llvm_unreachable("Unsupported ELF TLS access model");
5282 
5283   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5284 }
5285 
5286 SDValue
5287 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5288                                                     SelectionDAG &DAG) const {
5289   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5290 
5291   SDValue Chain = DAG.getEntryNode();
5292   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5293   SDLoc DL(Op);
5294 
5295   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5296 
5297   // Load the ThreadLocalStoragePointer from the TEB
5298   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5299   SDValue TLSArray =
5300       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5301   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5302   Chain = TLSArray.getValue(1);
5303 
5304   // Load the TLS index from the C runtime;
5305   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5306   // This also does the same as LOADgot, but using a generic i32 load,
5307   // while LOADgot only loads i64.
5308   SDValue TLSIndexHi =
5309       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5310   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5311       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5312   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5313   SDValue TLSIndex =
5314       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5315   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5316   Chain = TLSIndex.getValue(1);
5317 
5318   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5319   // offset into the TLSArray.
5320   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5321   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5322                              DAG.getConstant(3, DL, PtrVT));
5323   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5324                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5325                             MachinePointerInfo());
5326   Chain = TLS.getValue(1);
5327 
5328   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5329   const GlobalValue *GV = GA->getGlobal();
5330   SDValue TGAHi = DAG.getTargetGlobalAddress(
5331       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5332   SDValue TGALo = DAG.getTargetGlobalAddress(
5333       GV, DL, PtrVT, 0,
5334       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5335 
5336   // Add the offset from the start of the .tls section (section base).
5337   SDValue Addr =
5338       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5339                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5340               0);
5341   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5342   return Addr;
5343 }
5344 
5345 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5346                                                      SelectionDAG &DAG) const {
5347   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5348   if (DAG.getTarget().useEmulatedTLS())
5349     return LowerToTLSEmulatedModel(GA, DAG);
5350 
5351   if (Subtarget->isTargetDarwin())
5352     return LowerDarwinGlobalTLSAddress(Op, DAG);
5353   if (Subtarget->isTargetELF())
5354     return LowerELFGlobalTLSAddress(Op, DAG);
5355   if (Subtarget->isTargetWindows())
5356     return LowerWindowsGlobalTLSAddress(Op, DAG);
5357 
5358   llvm_unreachable("Unexpected platform trying to use TLS");
5359 }
5360 
5361 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5362   SDValue Chain = Op.getOperand(0);
5363   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5364   SDValue LHS = Op.getOperand(2);
5365   SDValue RHS = Op.getOperand(3);
5366   SDValue Dest = Op.getOperand(4);
5367   SDLoc dl(Op);
5368 
5369   MachineFunction &MF = DAG.getMachineFunction();
5370   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5371   // will not be produced, as they are conditional branch instructions that do
5372   // not set flags.
5373   bool ProduceNonFlagSettingCondBr =
5374       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5375 
5376   // Handle f128 first, since lowering it will result in comparing the return
5377   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5378   // is expecting to deal with.
5379   if (LHS.getValueType() == MVT::f128) {
5380     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5381 
5382     // If softenSetCCOperands returned a scalar, we need to compare the result
5383     // against zero to select between true and false values.
5384     if (!RHS.getNode()) {
5385       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5386       CC = ISD::SETNE;
5387     }
5388   }
5389 
5390   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5391   // instruction.
5392   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5393       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5394     // Only lower legal XALUO ops.
5395     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5396       return SDValue();
5397 
5398     // The actual operation with overflow check.
5399     AArch64CC::CondCode OFCC;
5400     SDValue Value, Overflow;
5401     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5402 
5403     if (CC == ISD::SETNE)
5404       OFCC = getInvertedCondCode(OFCC);
5405     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5406 
5407     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5408                        Overflow);
5409   }
5410 
5411   if (LHS.getValueType().isInteger()) {
5412     assert((LHS.getValueType() == RHS.getValueType()) &&
5413            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5414 
5415     // If the RHS of the comparison is zero, we can potentially fold this
5416     // to a specialized branch.
5417     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5418     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5419       if (CC == ISD::SETEQ) {
5420         // See if we can use a TBZ to fold in an AND as well.
5421         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5422         // out of bounds, a late MI-layer pass rewrites branches.
5423         // 403.gcc is an example that hits this case.
5424         if (LHS.getOpcode() == ISD::AND &&
5425             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5426             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5427           SDValue Test = LHS.getOperand(0);
5428           uint64_t Mask = LHS.getConstantOperandVal(1);
5429           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5430                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5431                              Dest);
5432         }
5433 
5434         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5435       } else if (CC == ISD::SETNE) {
5436         // See if we can use a TBZ to fold in an AND as well.
5437         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5438         // out of bounds, a late MI-layer pass rewrites branches.
5439         // 403.gcc is an example that hits this case.
5440         if (LHS.getOpcode() == ISD::AND &&
5441             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5442             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5443           SDValue Test = LHS.getOperand(0);
5444           uint64_t Mask = LHS.getConstantOperandVal(1);
5445           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5446                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5447                              Dest);
5448         }
5449 
5450         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5451       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5452         // Don't combine AND since emitComparison converts the AND to an ANDS
5453         // (a.k.a. TST) and the test in the test bit and branch instruction
5454         // becomes redundant.  This would also increase register pressure.
5455         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5456         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5457                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5458       }
5459     }
5460     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5461         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5462       // Don't combine AND since emitComparison converts the AND to an ANDS
5463       // (a.k.a. TST) and the test in the test bit and branch instruction
5464       // becomes redundant.  This would also increase register pressure.
5465       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5466       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5467                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5468     }
5469 
5470     SDValue CCVal;
5471     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5472     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5473                        Cmp);
5474   }
5475 
5476   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
5477          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
5478 
5479   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5480   // clean.  Some of them require two branches to implement.
5481   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5482   AArch64CC::CondCode CC1, CC2;
5483   changeFPCCToAArch64CC(CC, CC1, CC2);
5484   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5485   SDValue BR1 =
5486       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5487   if (CC2 != AArch64CC::AL) {
5488     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5489     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5490                        Cmp);
5491   }
5492 
5493   return BR1;
5494 }
5495 
5496 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5497                                               SelectionDAG &DAG) const {
5498   EVT VT = Op.getValueType();
5499   SDLoc DL(Op);
5500 
5501   SDValue In1 = Op.getOperand(0);
5502   SDValue In2 = Op.getOperand(1);
5503   EVT SrcVT = In2.getValueType();
5504 
5505   if (SrcVT.bitsLT(VT))
5506     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5507   else if (SrcVT.bitsGT(VT))
5508     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5509 
5510   EVT VecVT;
5511   uint64_t EltMask;
5512   SDValue VecVal1, VecVal2;
5513 
5514   auto setVecVal = [&] (int Idx) {
5515     if (!VT.isVector()) {
5516       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5517                                           DAG.getUNDEF(VecVT), In1);
5518       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5519                                           DAG.getUNDEF(VecVT), In2);
5520     } else {
5521       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5522       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5523     }
5524   };
5525 
5526   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5527     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5528     EltMask = 0x80000000ULL;
5529     setVecVal(AArch64::ssub);
5530   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5531     VecVT = MVT::v2i64;
5532 
5533     // We want to materialize a mask with the high bit set, but the AdvSIMD
5534     // immediate moves cannot materialize that in a single instruction for
5535     // 64-bit elements. Instead, materialize zero and then negate it.
5536     EltMask = 0;
5537 
5538     setVecVal(AArch64::dsub);
5539   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5540     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5541     EltMask = 0x8000ULL;
5542     setVecVal(AArch64::hsub);
5543   } else {
5544     llvm_unreachable("Invalid type for copysign!");
5545   }
5546 
5547   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5548 
5549   // If we couldn't materialize the mask above, then the mask vector will be
5550   // the zero vector, and we need to negate it here.
5551   if (VT == MVT::f64 || VT == MVT::v2f64) {
5552     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5553     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5554     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5555   }
5556 
5557   SDValue Sel =
5558       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5559 
5560   if (VT == MVT::f16)
5561     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5562   if (VT == MVT::f32)
5563     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5564   else if (VT == MVT::f64)
5565     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5566   else
5567     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5568 }
5569 
5570 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5571   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5572           Attribute::NoImplicitFloat))
5573     return SDValue();
5574 
5575   if (!Subtarget->hasNEON())
5576     return SDValue();
5577 
5578   // While there is no integer popcount instruction, it can
5579   // be more efficiently lowered to the following sequence that uses
5580   // AdvSIMD registers/instructions as long as the copies to/from
5581   // the AdvSIMD registers are cheap.
5582   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5583   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5584   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5585   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5586   SDValue Val = Op.getOperand(0);
5587   SDLoc DL(Op);
5588   EVT VT = Op.getValueType();
5589 
5590   if (VT == MVT::i32 || VT == MVT::i64) {
5591     if (VT == MVT::i32)
5592       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5593     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5594 
5595     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5596     SDValue UaddLV = DAG.getNode(
5597         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5598         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5599 
5600     if (VT == MVT::i64)
5601       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5602     return UaddLV;
5603   } else if (VT == MVT::i128) {
5604     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
5605 
5606     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
5607     SDValue UaddLV = DAG.getNode(
5608         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5609         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5610 
5611     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
5612   }
5613 
5614   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5615           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5616          "Unexpected type for custom ctpop lowering");
5617 
5618   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5619   Val = DAG.getBitcast(VT8Bit, Val);
5620   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5621 
5622   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5623   unsigned EltSize = 8;
5624   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5625   while (EltSize != VT.getScalarSizeInBits()) {
5626     EltSize *= 2;
5627     NumElts /= 2;
5628     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5629     Val = DAG.getNode(
5630         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5631         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5632   }
5633 
5634   return Val;
5635 }
5636 
5637 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5638 
5639   if (Op.getValueType().isVector())
5640     return LowerVSETCC(Op, DAG);
5641 
5642   bool IsStrict = Op->isStrictFPOpcode();
5643   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5644   unsigned OpNo = IsStrict ? 1 : 0;
5645   SDValue Chain;
5646   if (IsStrict)
5647     Chain = Op.getOperand(0);
5648   SDValue LHS = Op.getOperand(OpNo + 0);
5649   SDValue RHS = Op.getOperand(OpNo + 1);
5650   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5651   SDLoc dl(Op);
5652 
5653   // We chose ZeroOrOneBooleanContents, so use zero and one.
5654   EVT VT = Op.getValueType();
5655   SDValue TVal = DAG.getConstant(1, dl, VT);
5656   SDValue FVal = DAG.getConstant(0, dl, VT);
5657 
5658   // Handle f128 first, since one possible outcome is a normal integer
5659   // comparison which gets picked up by the next if statement.
5660   if (LHS.getValueType() == MVT::f128) {
5661     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5662                         IsSignaling);
5663 
5664     // If softenSetCCOperands returned a scalar, use it.
5665     if (!RHS.getNode()) {
5666       assert(LHS.getValueType() == Op.getValueType() &&
5667              "Unexpected setcc expansion!");
5668       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5669     }
5670   }
5671 
5672   if (LHS.getValueType().isInteger()) {
5673     SDValue CCVal;
5674     SDValue Cmp = getAArch64Cmp(
5675         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5676 
5677     // Note that we inverted the condition above, so we reverse the order of
5678     // the true and false operands here.  This will allow the setcc to be
5679     // matched to a single CSINC instruction.
5680     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5681     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5682   }
5683 
5684   // Now we know we're dealing with FP values.
5685   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5686          LHS.getValueType() == MVT::f64);
5687 
5688   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5689   // and do the comparison.
5690   SDValue Cmp;
5691   if (IsStrict)
5692     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5693   else
5694     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5695 
5696   AArch64CC::CondCode CC1, CC2;
5697   changeFPCCToAArch64CC(CC, CC1, CC2);
5698   SDValue Res;
5699   if (CC2 == AArch64CC::AL) {
5700     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5701                           CC2);
5702     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5703 
5704     // Note that we inverted the condition above, so we reverse the order of
5705     // the true and false operands here.  This will allow the setcc to be
5706     // matched to a single CSINC instruction.
5707     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5708   } else {
5709     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5710     // totally clean.  Some of them require two CSELs to implement.  As is in
5711     // this case, we emit the first CSEL and then emit a second using the output
5712     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5713 
5714     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5715     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5716     SDValue CS1 =
5717         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5718 
5719     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5720     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5721   }
5722   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5723 }
5724 
5725 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5726                                               SDValue RHS, SDValue TVal,
5727                                               SDValue FVal, const SDLoc &dl,
5728                                               SelectionDAG &DAG) const {
5729   // Handle f128 first, because it will result in a comparison of some RTLIB
5730   // call result against zero.
5731   if (LHS.getValueType() == MVT::f128) {
5732     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5733 
5734     // If softenSetCCOperands returned a scalar, we need to compare the result
5735     // against zero to select between true and false values.
5736     if (!RHS.getNode()) {
5737       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5738       CC = ISD::SETNE;
5739     }
5740   }
5741 
5742   // Also handle f16, for which we need to do a f32 comparison.
5743   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5744     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5745     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5746   }
5747 
5748   // Next, handle integers.
5749   if (LHS.getValueType().isInteger()) {
5750     assert((LHS.getValueType() == RHS.getValueType()) &&
5751            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5752 
5753     unsigned Opcode = AArch64ISD::CSEL;
5754 
5755     // If both the TVal and the FVal are constants, see if we can swap them in
5756     // order to for a CSINV or CSINC out of them.
5757     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5758     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5759 
5760     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5761       std::swap(TVal, FVal);
5762       std::swap(CTVal, CFVal);
5763       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5764     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5765       std::swap(TVal, FVal);
5766       std::swap(CTVal, CFVal);
5767       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5768     } else if (TVal.getOpcode() == ISD::XOR) {
5769       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5770       // with a CSINV rather than a CSEL.
5771       if (isAllOnesConstant(TVal.getOperand(1))) {
5772         std::swap(TVal, FVal);
5773         std::swap(CTVal, CFVal);
5774         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5775       }
5776     } else if (TVal.getOpcode() == ISD::SUB) {
5777       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5778       // that we can match with a CSNEG rather than a CSEL.
5779       if (isNullConstant(TVal.getOperand(0))) {
5780         std::swap(TVal, FVal);
5781         std::swap(CTVal, CFVal);
5782         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5783       }
5784     } else if (CTVal && CFVal) {
5785       const int64_t TrueVal = CTVal->getSExtValue();
5786       const int64_t FalseVal = CFVal->getSExtValue();
5787       bool Swap = false;
5788 
5789       // If both TVal and FVal are constants, see if FVal is the
5790       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5791       // instead of a CSEL in that case.
5792       if (TrueVal == ~FalseVal) {
5793         Opcode = AArch64ISD::CSINV;
5794       } else if (TrueVal == -FalseVal) {
5795         Opcode = AArch64ISD::CSNEG;
5796       } else if (TVal.getValueType() == MVT::i32) {
5797         // If our operands are only 32-bit wide, make sure we use 32-bit
5798         // arithmetic for the check whether we can use CSINC. This ensures that
5799         // the addition in the check will wrap around properly in case there is
5800         // an overflow (which would not be the case if we do the check with
5801         // 64-bit arithmetic).
5802         const uint32_t TrueVal32 = CTVal->getZExtValue();
5803         const uint32_t FalseVal32 = CFVal->getZExtValue();
5804 
5805         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5806           Opcode = AArch64ISD::CSINC;
5807 
5808           if (TrueVal32 > FalseVal32) {
5809             Swap = true;
5810           }
5811         }
5812         // 64-bit check whether we can use CSINC.
5813       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5814         Opcode = AArch64ISD::CSINC;
5815 
5816         if (TrueVal > FalseVal) {
5817           Swap = true;
5818         }
5819       }
5820 
5821       // Swap TVal and FVal if necessary.
5822       if (Swap) {
5823         std::swap(TVal, FVal);
5824         std::swap(CTVal, CFVal);
5825         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5826       }
5827 
5828       if (Opcode != AArch64ISD::CSEL) {
5829         // Drop FVal since we can get its value by simply inverting/negating
5830         // TVal.
5831         FVal = TVal;
5832       }
5833     }
5834 
5835     // Avoid materializing a constant when possible by reusing a known value in
5836     // a register.  However, don't perform this optimization if the known value
5837     // is one, zero or negative one in the case of a CSEL.  We can always
5838     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5839     // FVal, respectively.
5840     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5841     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5842         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5843       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5844       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5845       // "a != C ? x : a" to avoid materializing C.
5846       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5847         TVal = LHS;
5848       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5849         FVal = LHS;
5850     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5851       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5852       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5853       // avoid materializing C.
5854       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5855       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5856         Opcode = AArch64ISD::CSINV;
5857         TVal = LHS;
5858         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5859       }
5860     }
5861 
5862     SDValue CCVal;
5863     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5864     EVT VT = TVal.getValueType();
5865     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5866   }
5867 
5868   // Now we know we're dealing with FP values.
5869   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5870          LHS.getValueType() == MVT::f64);
5871   assert(LHS.getValueType() == RHS.getValueType());
5872   EVT VT = TVal.getValueType();
5873   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5874 
5875   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5876   // clean.  Some of them require two CSELs to implement.
5877   AArch64CC::CondCode CC1, CC2;
5878   changeFPCCToAArch64CC(CC, CC1, CC2);
5879 
5880   if (DAG.getTarget().Options.UnsafeFPMath) {
5881     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5882     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5883     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5884     if (RHSVal && RHSVal->isZero()) {
5885       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5886       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5887 
5888       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5889           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5890         TVal = LHS;
5891       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5892                CFVal && CFVal->isZero() &&
5893                FVal.getValueType() == LHS.getValueType())
5894         FVal = LHS;
5895     }
5896   }
5897 
5898   // Emit first, and possibly only, CSEL.
5899   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5900   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5901 
5902   // If we need a second CSEL, emit it, using the output of the first as the
5903   // RHS.  We're effectively OR'ing the two CC's together.
5904   if (CC2 != AArch64CC::AL) {
5905     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5906     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5907   }
5908 
5909   // Otherwise, return the output of the first CSEL.
5910   return CS1;
5911 }
5912 
5913 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5914                                               SelectionDAG &DAG) const {
5915   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5916   SDValue LHS = Op.getOperand(0);
5917   SDValue RHS = Op.getOperand(1);
5918   SDValue TVal = Op.getOperand(2);
5919   SDValue FVal = Op.getOperand(3);
5920   SDLoc DL(Op);
5921   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5922 }
5923 
5924 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5925                                            SelectionDAG &DAG) const {
5926   SDValue CCVal = Op->getOperand(0);
5927   SDValue TVal = Op->getOperand(1);
5928   SDValue FVal = Op->getOperand(2);
5929   SDLoc DL(Op);
5930 
5931   EVT Ty = Op.getValueType();
5932   if (Ty.isScalableVector()) {
5933     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
5934     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
5935     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
5936     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
5937   }
5938 
5939   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5940   // instruction.
5941   if (ISD::isOverflowIntrOpRes(CCVal)) {
5942     // Only lower legal XALUO ops.
5943     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5944       return SDValue();
5945 
5946     AArch64CC::CondCode OFCC;
5947     SDValue Value, Overflow;
5948     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5949     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5950 
5951     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5952                        CCVal, Overflow);
5953   }
5954 
5955   // Lower it the same way as we would lower a SELECT_CC node.
5956   ISD::CondCode CC;
5957   SDValue LHS, RHS;
5958   if (CCVal.getOpcode() == ISD::SETCC) {
5959     LHS = CCVal.getOperand(0);
5960     RHS = CCVal.getOperand(1);
5961     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5962   } else {
5963     LHS = CCVal;
5964     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5965     CC = ISD::SETNE;
5966   }
5967   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5968 }
5969 
5970 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5971                                               SelectionDAG &DAG) const {
5972   // Jump table entries as PC relative offsets. No additional tweaking
5973   // is necessary here. Just get the address of the jump table.
5974   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5975 
5976   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5977       !Subtarget->isTargetMachO()) {
5978     return getAddrLarge(JT, DAG);
5979   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5980     return getAddrTiny(JT, DAG);
5981   }
5982   return getAddr(JT, DAG);
5983 }
5984 
5985 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5986                                           SelectionDAG &DAG) const {
5987   // Jump table entries as PC relative offsets. No additional tweaking
5988   // is necessary here. Just get the address of the jump table.
5989   SDLoc DL(Op);
5990   SDValue JT = Op.getOperand(1);
5991   SDValue Entry = Op.getOperand(2);
5992   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5993 
5994   SDNode *Dest =
5995       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5996                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5997   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5998                      SDValue(Dest, 0));
5999 }
6000 
6001 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
6002                                                  SelectionDAG &DAG) const {
6003   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6004 
6005   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6006     // Use the GOT for the large code model on iOS.
6007     if (Subtarget->isTargetMachO()) {
6008       return getGOT(CP, DAG);
6009     }
6010     return getAddrLarge(CP, DAG);
6011   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6012     return getAddrTiny(CP, DAG);
6013   } else {
6014     return getAddr(CP, DAG);
6015   }
6016 }
6017 
6018 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6019                                                SelectionDAG &DAG) const {
6020   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6021   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6022       !Subtarget->isTargetMachO()) {
6023     return getAddrLarge(BA, DAG);
6024   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6025     return getAddrTiny(BA, DAG);
6026   }
6027   return getAddr(BA, DAG);
6028 }
6029 
6030 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6031                                                  SelectionDAG &DAG) const {
6032   AArch64FunctionInfo *FuncInfo =
6033       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6034 
6035   SDLoc DL(Op);
6036   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6037                                  getPointerTy(DAG.getDataLayout()));
6038   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6039   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6040   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6041                       MachinePointerInfo(SV));
6042 }
6043 
6044 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6045                                                   SelectionDAG &DAG) const {
6046   AArch64FunctionInfo *FuncInfo =
6047       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6048 
6049   SDLoc DL(Op);
6050   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6051                                      ? FuncInfo->getVarArgsGPRIndex()
6052                                      : FuncInfo->getVarArgsStackIndex(),
6053                                  getPointerTy(DAG.getDataLayout()));
6054   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6055   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6056                       MachinePointerInfo(SV));
6057 }
6058 
6059 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6060                                                 SelectionDAG &DAG) const {
6061   // The layout of the va_list struct is specified in the AArch64 Procedure Call
6062   // Standard, section B.3.
6063   MachineFunction &MF = DAG.getMachineFunction();
6064   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6065   auto PtrVT = getPointerTy(DAG.getDataLayout());
6066   SDLoc DL(Op);
6067 
6068   SDValue Chain = Op.getOperand(0);
6069   SDValue VAList = Op.getOperand(1);
6070   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6071   SmallVector<SDValue, 4> MemOps;
6072 
6073   // void *__stack at offset 0
6074   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6075   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
6076                                 MachinePointerInfo(SV), /* Alignment = */ 8));
6077 
6078   // void *__gr_top at offset 8
6079   int GPRSize = FuncInfo->getVarArgsGPRSize();
6080   if (GPRSize > 0) {
6081     SDValue GRTop, GRTopAddr;
6082 
6083     GRTopAddr =
6084         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6085 
6086     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6087     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6088                         DAG.getConstant(GPRSize, DL, PtrVT));
6089 
6090     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6091                                   MachinePointerInfo(SV, 8),
6092                                   /* Alignment = */ 8));
6093   }
6094 
6095   // void *__vr_top at offset 16
6096   int FPRSize = FuncInfo->getVarArgsFPRSize();
6097   if (FPRSize > 0) {
6098     SDValue VRTop, VRTopAddr;
6099     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6100                             DAG.getConstant(16, DL, PtrVT));
6101 
6102     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6103     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6104                         DAG.getConstant(FPRSize, DL, PtrVT));
6105 
6106     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6107                                   MachinePointerInfo(SV, 16),
6108                                   /* Alignment = */ 8));
6109   }
6110 
6111   // int __gr_offs at offset 24
6112   SDValue GROffsAddr =
6113       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6114   MemOps.push_back(DAG.getStore(
6115       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
6116       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
6117 
6118   // int __vr_offs at offset 28
6119   SDValue VROffsAddr =
6120       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6121   MemOps.push_back(DAG.getStore(
6122       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
6123       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
6124 
6125   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6126 }
6127 
6128 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6129                                             SelectionDAG &DAG) const {
6130   MachineFunction &MF = DAG.getMachineFunction();
6131 
6132   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6133     return LowerWin64_VASTART(Op, DAG);
6134   else if (Subtarget->isTargetDarwin())
6135     return LowerDarwin_VASTART(Op, DAG);
6136   else
6137     return LowerAAPCS_VASTART(Op, DAG);
6138 }
6139 
6140 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6141                                            SelectionDAG &DAG) const {
6142   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6143   // pointer.
6144   SDLoc DL(Op);
6145   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6146   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6147                          Subtarget->isTargetWindows()) ? PtrSize : 32;
6148   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6149   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6150 
6151   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6152                        DAG.getConstant(VaListSize, DL, MVT::i32),
6153                        Align(PtrSize), false, false, false,
6154                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6155 }
6156 
6157 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6158   assert(Subtarget->isTargetDarwin() &&
6159          "automatic va_arg instruction only works on Darwin");
6160 
6161   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6162   EVT VT = Op.getValueType();
6163   SDLoc DL(Op);
6164   SDValue Chain = Op.getOperand(0);
6165   SDValue Addr = Op.getOperand(1);
6166   MaybeAlign Align(Op.getConstantOperandVal(3));
6167   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6168   auto PtrVT = getPointerTy(DAG.getDataLayout());
6169   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6170   SDValue VAList =
6171       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6172   Chain = VAList.getValue(1);
6173   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6174 
6175   if (VT.isScalableVector())
6176     report_fatal_error("Passing SVE types to variadic functions is "
6177                        "currently not supported");
6178 
6179   if (Align && *Align > MinSlotSize) {
6180     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6181                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
6182     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6183                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6184   }
6185 
6186   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6187   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6188 
6189   // Scalar integer and FP values smaller than 64 bits are implicitly extended
6190   // up to 64 bits.  At the very least, we have to increase the striding of the
6191   // vaargs list to match this, and for FP values we need to introduce
6192   // FP_ROUND nodes as well.
6193   if (VT.isInteger() && !VT.isVector())
6194     ArgSize = std::max(ArgSize, MinSlotSize);
6195   bool NeedFPTrunc = false;
6196   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6197     ArgSize = 8;
6198     NeedFPTrunc = true;
6199   }
6200 
6201   // Increment the pointer, VAList, to the next vaarg
6202   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6203                                DAG.getConstant(ArgSize, DL, PtrVT));
6204   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6205 
6206   // Store the incremented VAList to the legalized pointer
6207   SDValue APStore =
6208       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6209 
6210   // Load the actual argument out of the pointer VAList
6211   if (NeedFPTrunc) {
6212     // Load the value as an f64.
6213     SDValue WideFP =
6214         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6215     // Round the value down to an f32.
6216     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6217                                    DAG.getIntPtrConstant(1, DL));
6218     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6219     // Merge the rounded value with the chain output of the load.
6220     return DAG.getMergeValues(Ops, DL);
6221   }
6222 
6223   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6224 }
6225 
6226 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6227                                               SelectionDAG &DAG) const {
6228   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6229   MFI.setFrameAddressIsTaken(true);
6230 
6231   EVT VT = Op.getValueType();
6232   SDLoc DL(Op);
6233   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6234   SDValue FrameAddr =
6235       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6236   while (Depth--)
6237     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6238                             MachinePointerInfo());
6239 
6240   if (Subtarget->isTargetILP32())
6241     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6242                             DAG.getValueType(VT));
6243 
6244   return FrameAddr;
6245 }
6246 
6247 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6248                                               SelectionDAG &DAG) const {
6249   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6250 
6251   EVT VT = getPointerTy(DAG.getDataLayout());
6252   SDLoc DL(Op);
6253   int FI = MFI.CreateFixedObject(4, 0, false);
6254   return DAG.getFrameIndex(FI, VT);
6255 }
6256 
6257 #define GET_REGISTER_MATCHER
6258 #include "AArch64GenAsmMatcher.inc"
6259 
6260 // FIXME? Maybe this could be a TableGen attribute on some registers and
6261 // this table could be generated automatically from RegInfo.
6262 Register AArch64TargetLowering::
6263 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6264   Register Reg = MatchRegisterName(RegName);
6265   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6266     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6267     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6268     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6269       Reg = 0;
6270   }
6271   if (Reg)
6272     return Reg;
6273   report_fatal_error(Twine("Invalid register name \""
6274                               + StringRef(RegName)  + "\"."));
6275 }
6276 
6277 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6278                                                      SelectionDAG &DAG) const {
6279   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6280 
6281   EVT VT = Op.getValueType();
6282   SDLoc DL(Op);
6283 
6284   SDValue FrameAddr =
6285       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6286   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6287 
6288   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6289 }
6290 
6291 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6292                                                SelectionDAG &DAG) const {
6293   MachineFunction &MF = DAG.getMachineFunction();
6294   MachineFrameInfo &MFI = MF.getFrameInfo();
6295   MFI.setReturnAddressIsTaken(true);
6296 
6297   EVT VT = Op.getValueType();
6298   SDLoc DL(Op);
6299   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6300   if (Depth) {
6301     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6302     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6303     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
6304                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
6305                        MachinePointerInfo());
6306   }
6307 
6308   // Return LR, which contains the return address. Mark it an implicit live-in.
6309   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6310   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6311 }
6312 
6313 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6314 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6315 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6316                                                     SelectionDAG &DAG) const {
6317   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6318   EVT VT = Op.getValueType();
6319   unsigned VTBits = VT.getSizeInBits();
6320   SDLoc dl(Op);
6321   SDValue ShOpLo = Op.getOperand(0);
6322   SDValue ShOpHi = Op.getOperand(1);
6323   SDValue ShAmt = Op.getOperand(2);
6324   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6325 
6326   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6327 
6328   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6329                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6330   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6331 
6332   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6333   // is "undef". We wanted 0, so CSEL it directly.
6334   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6335                                ISD::SETEQ, dl, DAG);
6336   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6337   HiBitsForLo =
6338       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6339                   HiBitsForLo, CCVal, Cmp);
6340 
6341   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6342                                    DAG.getConstant(VTBits, dl, MVT::i64));
6343 
6344   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6345   SDValue LoForNormalShift =
6346       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6347 
6348   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6349                        dl, DAG);
6350   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6351   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6352   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6353                            LoForNormalShift, CCVal, Cmp);
6354 
6355   // AArch64 shifts larger than the register width are wrapped rather than
6356   // clamped, so we can't just emit "hi >> x".
6357   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6358   SDValue HiForBigShift =
6359       Opc == ISD::SRA
6360           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6361                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6362           : DAG.getConstant(0, dl, VT);
6363   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6364                            HiForNormalShift, CCVal, Cmp);
6365 
6366   SDValue Ops[2] = { Lo, Hi };
6367   return DAG.getMergeValues(Ops, dl);
6368 }
6369 
6370 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6371 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6372 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6373                                                    SelectionDAG &DAG) const {
6374   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6375   EVT VT = Op.getValueType();
6376   unsigned VTBits = VT.getSizeInBits();
6377   SDLoc dl(Op);
6378   SDValue ShOpLo = Op.getOperand(0);
6379   SDValue ShOpHi = Op.getOperand(1);
6380   SDValue ShAmt = Op.getOperand(2);
6381 
6382   assert(Op.getOpcode() == ISD::SHL_PARTS);
6383   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6384                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6385   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6386 
6387   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6388   // is "undef". We wanted 0, so CSEL it directly.
6389   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6390                                ISD::SETEQ, dl, DAG);
6391   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6392   LoBitsForHi =
6393       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6394                   LoBitsForHi, CCVal, Cmp);
6395 
6396   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6397                                    DAG.getConstant(VTBits, dl, MVT::i64));
6398   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6399   SDValue HiForNormalShift =
6400       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6401 
6402   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6403 
6404   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6405                        dl, DAG);
6406   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6407   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6408                            HiForNormalShift, CCVal, Cmp);
6409 
6410   // AArch64 shifts of larger than register sizes are wrapped rather than
6411   // clamped, so we can't just emit "lo << a" if a is too big.
6412   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6413   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6414   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6415                            LoForNormalShift, CCVal, Cmp);
6416 
6417   SDValue Ops[2] = { Lo, Hi };
6418   return DAG.getMergeValues(Ops, dl);
6419 }
6420 
6421 bool AArch64TargetLowering::isOffsetFoldingLegal(
6422     const GlobalAddressSDNode *GA) const {
6423   // Offsets are folded in the DAG combine rather than here so that we can
6424   // intelligently choose an offset based on the uses.
6425   return false;
6426 }
6427 
6428 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6429                                          bool OptForSize) const {
6430   bool IsLegal = false;
6431   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6432   // 16-bit case when target has full fp16 support.
6433   // FIXME: We should be able to handle f128 as well with a clever lowering.
6434   const APInt ImmInt = Imm.bitcastToAPInt();
6435   if (VT == MVT::f64)
6436     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6437   else if (VT == MVT::f32)
6438     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6439   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6440     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6441   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6442   //       generate that fmov.
6443 
6444   // If we can not materialize in immediate field for fmov, check if the
6445   // value can be encoded as the immediate operand of a logical instruction.
6446   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6447   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6448     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6449     // however the mov+fmov sequence is always better because of the reduced
6450     // cache pressure. The timings are still the same if you consider
6451     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6452     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6453     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6454     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6455 			      Insn);
6456     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6457     IsLegal = Insn.size() <= Limit;
6458   }
6459 
6460   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6461                     << " imm value: "; Imm.dump(););
6462   return IsLegal;
6463 }
6464 
6465 //===----------------------------------------------------------------------===//
6466 //                          AArch64 Optimization Hooks
6467 //===----------------------------------------------------------------------===//
6468 
6469 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6470                            SDValue Operand, SelectionDAG &DAG,
6471                            int &ExtraSteps) {
6472   EVT VT = Operand.getValueType();
6473   if (ST->hasNEON() &&
6474       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6475        VT == MVT::f32 || VT == MVT::v1f32 ||
6476        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6477     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6478       // For the reciprocal estimates, convergence is quadratic, so the number
6479       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6480       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6481       // the result for float (23 mantissa bits) is 2 and for double (52
6482       // mantissa bits) is 3.
6483       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6484 
6485     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6486   }
6487 
6488   return SDValue();
6489 }
6490 
6491 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6492                                                SelectionDAG &DAG, int Enabled,
6493                                                int &ExtraSteps,
6494                                                bool &UseOneConst,
6495                                                bool Reciprocal) const {
6496   if (Enabled == ReciprocalEstimate::Enabled ||
6497       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6498     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6499                                        DAG, ExtraSteps)) {
6500       SDLoc DL(Operand);
6501       EVT VT = Operand.getValueType();
6502 
6503       SDNodeFlags Flags;
6504       Flags.setAllowReassociation(true);
6505 
6506       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6507       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6508       for (int i = ExtraSteps; i > 0; --i) {
6509         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6510                                    Flags);
6511         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6512         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6513       }
6514       if (!Reciprocal) {
6515         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6516                                       VT);
6517         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6518         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6519 
6520         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6521         // Correct the result if the operand is 0.0.
6522         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6523                                VT, Eq, Operand, Estimate);
6524       }
6525 
6526       ExtraSteps = 0;
6527       return Estimate;
6528     }
6529 
6530   return SDValue();
6531 }
6532 
6533 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6534                                                 SelectionDAG &DAG, int Enabled,
6535                                                 int &ExtraSteps) const {
6536   if (Enabled == ReciprocalEstimate::Enabled)
6537     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6538                                        DAG, ExtraSteps)) {
6539       SDLoc DL(Operand);
6540       EVT VT = Operand.getValueType();
6541 
6542       SDNodeFlags Flags;
6543       Flags.setAllowReassociation(true);
6544 
6545       // Newton reciprocal iteration: E * (2 - X * E)
6546       // AArch64 reciprocal iteration instruction: (2 - M * N)
6547       for (int i = ExtraSteps; i > 0; --i) {
6548         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6549                                    Estimate, Flags);
6550         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6551       }
6552 
6553       ExtraSteps = 0;
6554       return Estimate;
6555     }
6556 
6557   return SDValue();
6558 }
6559 
6560 //===----------------------------------------------------------------------===//
6561 //                          AArch64 Inline Assembly Support
6562 //===----------------------------------------------------------------------===//
6563 
6564 // Table of Constraints
6565 // TODO: This is the current set of constraints supported by ARM for the
6566 // compiler, not all of them may make sense.
6567 //
6568 // r - A general register
6569 // w - An FP/SIMD register of some size in the range v0-v31
6570 // x - An FP/SIMD register of some size in the range v0-v15
6571 // I - Constant that can be used with an ADD instruction
6572 // J - Constant that can be used with a SUB instruction
6573 // K - Constant that can be used with a 32-bit logical instruction
6574 // L - Constant that can be used with a 64-bit logical instruction
6575 // M - Constant that can be used as a 32-bit MOV immediate
6576 // N - Constant that can be used as a 64-bit MOV immediate
6577 // Q - A memory reference with base register and no offset
6578 // S - A symbolic address
6579 // Y - Floating point constant zero
6580 // Z - Integer constant zero
6581 //
6582 //   Note that general register operands will be output using their 64-bit x
6583 // register name, whatever the size of the variable, unless the asm operand
6584 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6585 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6586 // %q modifier.
6587 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6588   // At this point, we have to lower this constraint to something else, so we
6589   // lower it to an "r" or "w". However, by doing this we will force the result
6590   // to be in register, while the X constraint is much more permissive.
6591   //
6592   // Although we are correct (we are free to emit anything, without
6593   // constraints), we might break use cases that would expect us to be more
6594   // efficient and emit something else.
6595   if (!Subtarget->hasFPARMv8())
6596     return "r";
6597 
6598   if (ConstraintVT.isFloatingPoint())
6599     return "w";
6600 
6601   if (ConstraintVT.isVector() &&
6602      (ConstraintVT.getSizeInBits() == 64 ||
6603       ConstraintVT.getSizeInBits() == 128))
6604     return "w";
6605 
6606   return "r";
6607 }
6608 
6609 enum PredicateConstraint {
6610   Upl,
6611   Upa,
6612   Invalid
6613 };
6614 
6615 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6616   PredicateConstraint P = PredicateConstraint::Invalid;
6617   if (Constraint == "Upa")
6618     P = PredicateConstraint::Upa;
6619   if (Constraint == "Upl")
6620     P = PredicateConstraint::Upl;
6621   return P;
6622 }
6623 
6624 /// getConstraintType - Given a constraint letter, return the type of
6625 /// constraint it is for this target.
6626 AArch64TargetLowering::ConstraintType
6627 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6628   if (Constraint.size() == 1) {
6629     switch (Constraint[0]) {
6630     default:
6631       break;
6632     case 'x':
6633     case 'w':
6634     case 'y':
6635       return C_RegisterClass;
6636     // An address with a single base register. Due to the way we
6637     // currently handle addresses it is the same as 'r'.
6638     case 'Q':
6639       return C_Memory;
6640     case 'I':
6641     case 'J':
6642     case 'K':
6643     case 'L':
6644     case 'M':
6645     case 'N':
6646     case 'Y':
6647     case 'Z':
6648       return C_Immediate;
6649     case 'z':
6650     case 'S': // A symbolic address
6651       return C_Other;
6652     }
6653   } else if (parsePredicateConstraint(Constraint) !=
6654              PredicateConstraint::Invalid)
6655       return C_RegisterClass;
6656   return TargetLowering::getConstraintType(Constraint);
6657 }
6658 
6659 /// Examine constraint type and operand type and determine a weight value.
6660 /// This object must already have been set up with the operand type
6661 /// and the current alternative constraint selected.
6662 TargetLowering::ConstraintWeight
6663 AArch64TargetLowering::getSingleConstraintMatchWeight(
6664     AsmOperandInfo &info, const char *constraint) const {
6665   ConstraintWeight weight = CW_Invalid;
6666   Value *CallOperandVal = info.CallOperandVal;
6667   // If we don't have a value, we can't do a match,
6668   // but allow it at the lowest weight.
6669   if (!CallOperandVal)
6670     return CW_Default;
6671   Type *type = CallOperandVal->getType();
6672   // Look at the constraint type.
6673   switch (*constraint) {
6674   default:
6675     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6676     break;
6677   case 'x':
6678   case 'w':
6679   case 'y':
6680     if (type->isFloatingPointTy() || type->isVectorTy())
6681       weight = CW_Register;
6682     break;
6683   case 'z':
6684     weight = CW_Constant;
6685     break;
6686   case 'U':
6687     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6688       weight = CW_Register;
6689     break;
6690   }
6691   return weight;
6692 }
6693 
6694 std::pair<unsigned, const TargetRegisterClass *>
6695 AArch64TargetLowering::getRegForInlineAsmConstraint(
6696     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6697   if (Constraint.size() == 1) {
6698     switch (Constraint[0]) {
6699     case 'r':
6700       if (VT.getSizeInBits() == 64)
6701         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6702       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6703     case 'w':
6704       if (!Subtarget->hasFPARMv8())
6705         break;
6706       if (VT.isScalableVector())
6707         return std::make_pair(0U, &AArch64::ZPRRegClass);
6708       if (VT.getSizeInBits() == 16)
6709         return std::make_pair(0U, &AArch64::FPR16RegClass);
6710       if (VT.getSizeInBits() == 32)
6711         return std::make_pair(0U, &AArch64::FPR32RegClass);
6712       if (VT.getSizeInBits() == 64)
6713         return std::make_pair(0U, &AArch64::FPR64RegClass);
6714       if (VT.getSizeInBits() == 128)
6715         return std::make_pair(0U, &AArch64::FPR128RegClass);
6716       break;
6717     // The instructions that this constraint is designed for can
6718     // only take 128-bit registers so just use that regclass.
6719     case 'x':
6720       if (!Subtarget->hasFPARMv8())
6721         break;
6722       if (VT.isScalableVector())
6723         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6724       if (VT.getSizeInBits() == 128)
6725         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6726       break;
6727     case 'y':
6728       if (!Subtarget->hasFPARMv8())
6729         break;
6730       if (VT.isScalableVector())
6731         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6732       break;
6733     }
6734   } else {
6735     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6736     if (PC != PredicateConstraint::Invalid) {
6737       assert(VT.isScalableVector());
6738       bool restricted = (PC == PredicateConstraint::Upl);
6739       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6740                           : std::make_pair(0U, &AArch64::PPRRegClass);
6741     }
6742   }
6743   if (StringRef("{cc}").equals_lower(Constraint))
6744     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6745 
6746   // Use the default implementation in TargetLowering to convert the register
6747   // constraint into a member of a register class.
6748   std::pair<unsigned, const TargetRegisterClass *> Res;
6749   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6750 
6751   // Not found as a standard register?
6752   if (!Res.second) {
6753     unsigned Size = Constraint.size();
6754     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6755         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6756       int RegNo;
6757       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6758       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6759         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6760         // By default we'll emit v0-v31 for this unless there's a modifier where
6761         // we'll emit the correct register as well.
6762         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6763           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6764           Res.second = &AArch64::FPR64RegClass;
6765         } else {
6766           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6767           Res.second = &AArch64::FPR128RegClass;
6768         }
6769       }
6770     }
6771   }
6772 
6773   if (Res.second && !Subtarget->hasFPARMv8() &&
6774       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6775       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6776     return std::make_pair(0U, nullptr);
6777 
6778   return Res;
6779 }
6780 
6781 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6782 /// vector.  If it is invalid, don't add anything to Ops.
6783 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6784     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6785     SelectionDAG &DAG) const {
6786   SDValue Result;
6787 
6788   // Currently only support length 1 constraints.
6789   if (Constraint.length() != 1)
6790     return;
6791 
6792   char ConstraintLetter = Constraint[0];
6793   switch (ConstraintLetter) {
6794   default:
6795     break;
6796 
6797   // This set of constraints deal with valid constants for various instructions.
6798   // Validate and return a target constant for them if we can.
6799   case 'z': {
6800     // 'z' maps to xzr or wzr so it needs an input of 0.
6801     if (!isNullConstant(Op))
6802       return;
6803 
6804     if (Op.getValueType() == MVT::i64)
6805       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6806     else
6807       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6808     break;
6809   }
6810   case 'S': {
6811     // An absolute symbolic address or label reference.
6812     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6813       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6814                                           GA->getValueType(0));
6815     } else if (const BlockAddressSDNode *BA =
6816                    dyn_cast<BlockAddressSDNode>(Op)) {
6817       Result =
6818           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6819     } else if (const ExternalSymbolSDNode *ES =
6820                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6821       Result =
6822           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6823     } else
6824       return;
6825     break;
6826   }
6827 
6828   case 'I':
6829   case 'J':
6830   case 'K':
6831   case 'L':
6832   case 'M':
6833   case 'N':
6834     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6835     if (!C)
6836       return;
6837 
6838     // Grab the value and do some validation.
6839     uint64_t CVal = C->getZExtValue();
6840     switch (ConstraintLetter) {
6841     // The I constraint applies only to simple ADD or SUB immediate operands:
6842     // i.e. 0 to 4095 with optional shift by 12
6843     // The J constraint applies only to ADD or SUB immediates that would be
6844     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6845     // instruction [or vice versa], in other words -1 to -4095 with optional
6846     // left shift by 12.
6847     case 'I':
6848       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6849         break;
6850       return;
6851     case 'J': {
6852       uint64_t NVal = -C->getSExtValue();
6853       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6854         CVal = C->getSExtValue();
6855         break;
6856       }
6857       return;
6858     }
6859     // The K and L constraints apply *only* to logical immediates, including
6860     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6861     // been removed and MOV should be used). So these constraints have to
6862     // distinguish between bit patterns that are valid 32-bit or 64-bit
6863     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6864     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6865     // versa.
6866     case 'K':
6867       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6868         break;
6869       return;
6870     case 'L':
6871       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6872         break;
6873       return;
6874     // The M and N constraints are a superset of K and L respectively, for use
6875     // with the MOV (immediate) alias. As well as the logical immediates they
6876     // also match 32 or 64-bit immediates that can be loaded either using a
6877     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6878     // (M) or 64-bit 0x1234000000000000 (N) etc.
6879     // As a note some of this code is liberally stolen from the asm parser.
6880     case 'M': {
6881       if (!isUInt<32>(CVal))
6882         return;
6883       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6884         break;
6885       if ((CVal & 0xFFFF) == CVal)
6886         break;
6887       if ((CVal & 0xFFFF0000ULL) == CVal)
6888         break;
6889       uint64_t NCVal = ~(uint32_t)CVal;
6890       if ((NCVal & 0xFFFFULL) == NCVal)
6891         break;
6892       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6893         break;
6894       return;
6895     }
6896     case 'N': {
6897       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6898         break;
6899       if ((CVal & 0xFFFFULL) == CVal)
6900         break;
6901       if ((CVal & 0xFFFF0000ULL) == CVal)
6902         break;
6903       if ((CVal & 0xFFFF00000000ULL) == CVal)
6904         break;
6905       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6906         break;
6907       uint64_t NCVal = ~CVal;
6908       if ((NCVal & 0xFFFFULL) == NCVal)
6909         break;
6910       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6911         break;
6912       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6913         break;
6914       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6915         break;
6916       return;
6917     }
6918     default:
6919       return;
6920     }
6921 
6922     // All assembler immediates are 64-bit integers.
6923     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6924     break;
6925   }
6926 
6927   if (Result.getNode()) {
6928     Ops.push_back(Result);
6929     return;
6930   }
6931 
6932   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6933 }
6934 
6935 //===----------------------------------------------------------------------===//
6936 //                     AArch64 Advanced SIMD Support
6937 //===----------------------------------------------------------------------===//
6938 
6939 /// WidenVector - Given a value in the V64 register class, produce the
6940 /// equivalent value in the V128 register class.
6941 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6942   EVT VT = V64Reg.getValueType();
6943   unsigned NarrowSize = VT.getVectorNumElements();
6944   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6945   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6946   SDLoc DL(V64Reg);
6947 
6948   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6949                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6950 }
6951 
6952 /// getExtFactor - Determine the adjustment factor for the position when
6953 /// generating an "extract from vector registers" instruction.
6954 static unsigned getExtFactor(SDValue &V) {
6955   EVT EltType = V.getValueType().getVectorElementType();
6956   return EltType.getSizeInBits() / 8;
6957 }
6958 
6959 /// NarrowVector - Given a value in the V128 register class, produce the
6960 /// equivalent value in the V64 register class.
6961 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6962   EVT VT = V128Reg.getValueType();
6963   unsigned WideSize = VT.getVectorNumElements();
6964   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6965   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6966   SDLoc DL(V128Reg);
6967 
6968   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6969 }
6970 
6971 // Gather data to see if the operation can be modelled as a
6972 // shuffle in combination with VEXTs.
6973 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6974                                                   SelectionDAG &DAG) const {
6975   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6976   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6977   SDLoc dl(Op);
6978   EVT VT = Op.getValueType();
6979   unsigned NumElts = VT.getVectorNumElements();
6980 
6981   struct ShuffleSourceInfo {
6982     SDValue Vec;
6983     unsigned MinElt;
6984     unsigned MaxElt;
6985 
6986     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6987     // be compatible with the shuffle we intend to construct. As a result
6988     // ShuffleVec will be some sliding window into the original Vec.
6989     SDValue ShuffleVec;
6990 
6991     // Code should guarantee that element i in Vec starts at element "WindowBase
6992     // + i * WindowScale in ShuffleVec".
6993     int WindowBase;
6994     int WindowScale;
6995 
6996     ShuffleSourceInfo(SDValue Vec)
6997       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6998           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6999 
7000     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7001   };
7002 
7003   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7004   // node.
7005   SmallVector<ShuffleSourceInfo, 2> Sources;
7006   for (unsigned i = 0; i < NumElts; ++i) {
7007     SDValue V = Op.getOperand(i);
7008     if (V.isUndef())
7009       continue;
7010     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7011              !isa<ConstantSDNode>(V.getOperand(1))) {
7012       LLVM_DEBUG(
7013           dbgs() << "Reshuffle failed: "
7014                     "a shuffle can only come from building a vector from "
7015                     "various elements of other vectors, provided their "
7016                     "indices are constant\n");
7017       return SDValue();
7018     }
7019 
7020     // Add this element source to the list if it's not already there.
7021     SDValue SourceVec = V.getOperand(0);
7022     auto Source = find(Sources, SourceVec);
7023     if (Source == Sources.end())
7024       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7025 
7026     // Update the minimum and maximum lane number seen.
7027     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7028     Source->MinElt = std::min(Source->MinElt, EltNo);
7029     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7030   }
7031 
7032   if (Sources.size() > 2) {
7033     LLVM_DEBUG(
7034         dbgs() << "Reshuffle failed: currently only do something sane when at "
7035                   "most two source vectors are involved\n");
7036     return SDValue();
7037   }
7038 
7039   // Find out the smallest element size among result and two sources, and use
7040   // it as element size to build the shuffle_vector.
7041   EVT SmallestEltTy = VT.getVectorElementType();
7042   for (auto &Source : Sources) {
7043     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7044     if (SrcEltTy.bitsLT(SmallestEltTy)) {
7045       SmallestEltTy = SrcEltTy;
7046     }
7047   }
7048   unsigned ResMultiplier =
7049       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7050   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7051   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7052 
7053   // If the source vector is too wide or too narrow, we may nevertheless be able
7054   // to construct a compatible shuffle either by concatenating it with UNDEF or
7055   // extracting a suitable range of elements.
7056   for (auto &Src : Sources) {
7057     EVT SrcVT = Src.ShuffleVec.getValueType();
7058 
7059     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7060       continue;
7061 
7062     // This stage of the search produces a source with the same element type as
7063     // the original, but with a total width matching the BUILD_VECTOR output.
7064     EVT EltVT = SrcVT.getVectorElementType();
7065     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7066     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7067 
7068     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7069       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
7070       // We can pad out the smaller vector for free, so if it's part of a
7071       // shuffle...
7072       Src.ShuffleVec =
7073           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7074                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7075       continue;
7076     }
7077 
7078     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
7079 
7080     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7081       LLVM_DEBUG(
7082           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7083       return SDValue();
7084     }
7085 
7086     if (Src.MinElt >= NumSrcElts) {
7087       // The extraction can just take the second half
7088       Src.ShuffleVec =
7089           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7090                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7091       Src.WindowBase = -NumSrcElts;
7092     } else if (Src.MaxElt < NumSrcElts) {
7093       // The extraction can just take the first half
7094       Src.ShuffleVec =
7095           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7096                       DAG.getConstant(0, dl, MVT::i64));
7097     } else {
7098       // An actual VEXT is needed
7099       SDValue VEXTSrc1 =
7100           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7101                       DAG.getConstant(0, dl, MVT::i64));
7102       SDValue VEXTSrc2 =
7103           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7104                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7105       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7106 
7107       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7108                                    VEXTSrc2,
7109                                    DAG.getConstant(Imm, dl, MVT::i32));
7110       Src.WindowBase = -Src.MinElt;
7111     }
7112   }
7113 
7114   // Another possible incompatibility occurs from the vector element types. We
7115   // can fix this by bitcasting the source vectors to the same type we intend
7116   // for the shuffle.
7117   for (auto &Src : Sources) {
7118     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7119     if (SrcEltTy == SmallestEltTy)
7120       continue;
7121     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7122     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7123     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7124     Src.WindowBase *= Src.WindowScale;
7125   }
7126 
7127   // Final sanity check before we try to actually produce a shuffle.
7128   LLVM_DEBUG(for (auto Src
7129                   : Sources)
7130                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7131 
7132   // The stars all align, our next step is to produce the mask for the shuffle.
7133   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7134   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7135   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7136     SDValue Entry = Op.getOperand(i);
7137     if (Entry.isUndef())
7138       continue;
7139 
7140     auto Src = find(Sources, Entry.getOperand(0));
7141     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7142 
7143     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7144     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7145     // segment.
7146     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7147     int BitsDefined =
7148         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
7149     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7150 
7151     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7152     // starting at the appropriate offset.
7153     int *LaneMask = &Mask[i * ResMultiplier];
7154 
7155     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7156     ExtractBase += NumElts * (Src - Sources.begin());
7157     for (int j = 0; j < LanesDefined; ++j)
7158       LaneMask[j] = ExtractBase + j;
7159   }
7160 
7161   // Final check before we try to produce nonsense...
7162   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7163     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7164     return SDValue();
7165   }
7166 
7167   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7168   for (unsigned i = 0; i < Sources.size(); ++i)
7169     ShuffleOps[i] = Sources[i].ShuffleVec;
7170 
7171   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7172                                          ShuffleOps[1], Mask);
7173   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7174 
7175   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7176              dbgs() << "Reshuffle, creating node: "; V.dump(););
7177 
7178   return V;
7179 }
7180 
7181 // check if an EXT instruction can handle the shuffle mask when the
7182 // vector sources of the shuffle are the same.
7183 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7184   unsigned NumElts = VT.getVectorNumElements();
7185 
7186   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7187   if (M[0] < 0)
7188     return false;
7189 
7190   Imm = M[0];
7191 
7192   // If this is a VEXT shuffle, the immediate value is the index of the first
7193   // element.  The other shuffle indices must be the successive elements after
7194   // the first one.
7195   unsigned ExpectedElt = Imm;
7196   for (unsigned i = 1; i < NumElts; ++i) {
7197     // Increment the expected index.  If it wraps around, just follow it
7198     // back to index zero and keep going.
7199     ++ExpectedElt;
7200     if (ExpectedElt == NumElts)
7201       ExpectedElt = 0;
7202 
7203     if (M[i] < 0)
7204       continue; // ignore UNDEF indices
7205     if (ExpectedElt != static_cast<unsigned>(M[i]))
7206       return false;
7207   }
7208 
7209   return true;
7210 }
7211 
7212 // check if an EXT instruction can handle the shuffle mask when the
7213 // vector sources of the shuffle are different.
7214 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7215                       unsigned &Imm) {
7216   // Look for the first non-undef element.
7217   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7218 
7219   // Benefit form APInt to handle overflow when calculating expected element.
7220   unsigned NumElts = VT.getVectorNumElements();
7221   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7222   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7223   // The following shuffle indices must be the successive elements after the
7224   // first real element.
7225   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7226       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7227   if (FirstWrongElt != M.end())
7228     return false;
7229 
7230   // The index of an EXT is the first element if it is not UNDEF.
7231   // Watch out for the beginning UNDEFs. The EXT index should be the expected
7232   // value of the first element.  E.g.
7233   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7234   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7235   // ExpectedElt is the last mask index plus 1.
7236   Imm = ExpectedElt.getZExtValue();
7237 
7238   // There are two difference cases requiring to reverse input vectors.
7239   // For example, for vector <4 x i32> we have the following cases,
7240   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7241   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7242   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7243   // to reverse two input vectors.
7244   if (Imm < NumElts)
7245     ReverseEXT = true;
7246   else
7247     Imm -= NumElts;
7248 
7249   return true;
7250 }
7251 
7252 /// isREVMask - Check if a vector shuffle corresponds to a REV
7253 /// instruction with the specified blocksize.  (The order of the elements
7254 /// within each block of the vector is reversed.)
7255 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7256   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7257          "Only possible block sizes for REV are: 16, 32, 64");
7258 
7259   unsigned EltSz = VT.getScalarSizeInBits();
7260   if (EltSz == 64)
7261     return false;
7262 
7263   unsigned NumElts = VT.getVectorNumElements();
7264   unsigned BlockElts = M[0] + 1;
7265   // If the first shuffle index is UNDEF, be optimistic.
7266   if (M[0] < 0)
7267     BlockElts = BlockSize / EltSz;
7268 
7269   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7270     return false;
7271 
7272   for (unsigned i = 0; i < NumElts; ++i) {
7273     if (M[i] < 0)
7274       continue; // ignore UNDEF indices
7275     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7276       return false;
7277   }
7278 
7279   return true;
7280 }
7281 
7282 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7283   unsigned NumElts = VT.getVectorNumElements();
7284   if (NumElts % 2 != 0)
7285     return false;
7286   WhichResult = (M[0] == 0 ? 0 : 1);
7287   unsigned Idx = WhichResult * NumElts / 2;
7288   for (unsigned i = 0; i != NumElts; i += 2) {
7289     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7290         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7291       return false;
7292     Idx += 1;
7293   }
7294 
7295   return true;
7296 }
7297 
7298 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7299   unsigned NumElts = VT.getVectorNumElements();
7300   WhichResult = (M[0] == 0 ? 0 : 1);
7301   for (unsigned i = 0; i != NumElts; ++i) {
7302     if (M[i] < 0)
7303       continue; // ignore UNDEF indices
7304     if ((unsigned)M[i] != 2 * i + WhichResult)
7305       return false;
7306   }
7307 
7308   return true;
7309 }
7310 
7311 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7312   unsigned NumElts = VT.getVectorNumElements();
7313   if (NumElts % 2 != 0)
7314     return false;
7315   WhichResult = (M[0] == 0 ? 0 : 1);
7316   for (unsigned i = 0; i < NumElts; i += 2) {
7317     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7318         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7319       return false;
7320   }
7321   return true;
7322 }
7323 
7324 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7325 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7326 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7327 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7328   unsigned NumElts = VT.getVectorNumElements();
7329   if (NumElts % 2 != 0)
7330     return false;
7331   WhichResult = (M[0] == 0 ? 0 : 1);
7332   unsigned Idx = WhichResult * NumElts / 2;
7333   for (unsigned i = 0; i != NumElts; i += 2) {
7334     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7335         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7336       return false;
7337     Idx += 1;
7338   }
7339 
7340   return true;
7341 }
7342 
7343 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7344 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7345 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7346 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7347   unsigned Half = VT.getVectorNumElements() / 2;
7348   WhichResult = (M[0] == 0 ? 0 : 1);
7349   for (unsigned j = 0; j != 2; ++j) {
7350     unsigned Idx = WhichResult;
7351     for (unsigned i = 0; i != Half; ++i) {
7352       int MIdx = M[i + j * Half];
7353       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7354         return false;
7355       Idx += 2;
7356     }
7357   }
7358 
7359   return true;
7360 }
7361 
7362 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7363 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7364 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7365 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7366   unsigned NumElts = VT.getVectorNumElements();
7367   if (NumElts % 2 != 0)
7368     return false;
7369   WhichResult = (M[0] == 0 ? 0 : 1);
7370   for (unsigned i = 0; i < NumElts; i += 2) {
7371     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7372         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7373       return false;
7374   }
7375   return true;
7376 }
7377 
7378 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7379                       bool &DstIsLeft, int &Anomaly) {
7380   if (M.size() != static_cast<size_t>(NumInputElements))
7381     return false;
7382 
7383   int NumLHSMatch = 0, NumRHSMatch = 0;
7384   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7385 
7386   for (int i = 0; i < NumInputElements; ++i) {
7387     if (M[i] == -1) {
7388       ++NumLHSMatch;
7389       ++NumRHSMatch;
7390       continue;
7391     }
7392 
7393     if (M[i] == i)
7394       ++NumLHSMatch;
7395     else
7396       LastLHSMismatch = i;
7397 
7398     if (M[i] == i + NumInputElements)
7399       ++NumRHSMatch;
7400     else
7401       LastRHSMismatch = i;
7402   }
7403 
7404   if (NumLHSMatch == NumInputElements - 1) {
7405     DstIsLeft = true;
7406     Anomaly = LastLHSMismatch;
7407     return true;
7408   } else if (NumRHSMatch == NumInputElements - 1) {
7409     DstIsLeft = false;
7410     Anomaly = LastRHSMismatch;
7411     return true;
7412   }
7413 
7414   return false;
7415 }
7416 
7417 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7418   if (VT.getSizeInBits() != 128)
7419     return false;
7420 
7421   unsigned NumElts = VT.getVectorNumElements();
7422 
7423   for (int I = 0, E = NumElts / 2; I != E; I++) {
7424     if (Mask[I] != I)
7425       return false;
7426   }
7427 
7428   int Offset = NumElts / 2;
7429   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7430     if (Mask[I] != I + SplitLHS * Offset)
7431       return false;
7432   }
7433 
7434   return true;
7435 }
7436 
7437 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7438   SDLoc DL(Op);
7439   EVT VT = Op.getValueType();
7440   SDValue V0 = Op.getOperand(0);
7441   SDValue V1 = Op.getOperand(1);
7442   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7443 
7444   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7445       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7446     return SDValue();
7447 
7448   bool SplitV0 = V0.getValueSizeInBits() == 128;
7449 
7450   if (!isConcatMask(Mask, VT, SplitV0))
7451     return SDValue();
7452 
7453   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7454   if (SplitV0) {
7455     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7456                      DAG.getConstant(0, DL, MVT::i64));
7457   }
7458   if (V1.getValueSizeInBits() == 128) {
7459     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7460                      DAG.getConstant(0, DL, MVT::i64));
7461   }
7462   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7463 }
7464 
7465 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7466 /// the specified operations to build the shuffle.
7467 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7468                                       SDValue RHS, SelectionDAG &DAG,
7469                                       const SDLoc &dl) {
7470   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7471   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7472   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7473 
7474   enum {
7475     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7476     OP_VREV,
7477     OP_VDUP0,
7478     OP_VDUP1,
7479     OP_VDUP2,
7480     OP_VDUP3,
7481     OP_VEXT1,
7482     OP_VEXT2,
7483     OP_VEXT3,
7484     OP_VUZPL, // VUZP, left result
7485     OP_VUZPR, // VUZP, right result
7486     OP_VZIPL, // VZIP, left result
7487     OP_VZIPR, // VZIP, right result
7488     OP_VTRNL, // VTRN, left result
7489     OP_VTRNR  // VTRN, right result
7490   };
7491 
7492   if (OpNum == OP_COPY) {
7493     if (LHSID == (1 * 9 + 2) * 9 + 3)
7494       return LHS;
7495     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7496     return RHS;
7497   }
7498 
7499   SDValue OpLHS, OpRHS;
7500   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7501   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7502   EVT VT = OpLHS.getValueType();
7503 
7504   switch (OpNum) {
7505   default:
7506     llvm_unreachable("Unknown shuffle opcode!");
7507   case OP_VREV:
7508     // VREV divides the vector in half and swaps within the half.
7509     if (VT.getVectorElementType() == MVT::i32 ||
7510         VT.getVectorElementType() == MVT::f32)
7511       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7512     // vrev <4 x i16> -> REV32
7513     if (VT.getVectorElementType() == MVT::i16 ||
7514         VT.getVectorElementType() == MVT::f16 ||
7515         VT.getVectorElementType() == MVT::bf16)
7516       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7517     // vrev <4 x i8> -> REV16
7518     assert(VT.getVectorElementType() == MVT::i8);
7519     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7520   case OP_VDUP0:
7521   case OP_VDUP1:
7522   case OP_VDUP2:
7523   case OP_VDUP3: {
7524     EVT EltTy = VT.getVectorElementType();
7525     unsigned Opcode;
7526     if (EltTy == MVT::i8)
7527       Opcode = AArch64ISD::DUPLANE8;
7528     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
7529       Opcode = AArch64ISD::DUPLANE16;
7530     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7531       Opcode = AArch64ISD::DUPLANE32;
7532     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7533       Opcode = AArch64ISD::DUPLANE64;
7534     else
7535       llvm_unreachable("Invalid vector element type?");
7536 
7537     if (VT.getSizeInBits() == 64)
7538       OpLHS = WidenVector(OpLHS, DAG);
7539     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7540     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7541   }
7542   case OP_VEXT1:
7543   case OP_VEXT2:
7544   case OP_VEXT3: {
7545     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7546     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7547                        DAG.getConstant(Imm, dl, MVT::i32));
7548   }
7549   case OP_VUZPL:
7550     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7551                        OpRHS);
7552   case OP_VUZPR:
7553     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7554                        OpRHS);
7555   case OP_VZIPL:
7556     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7557                        OpRHS);
7558   case OP_VZIPR:
7559     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7560                        OpRHS);
7561   case OP_VTRNL:
7562     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7563                        OpRHS);
7564   case OP_VTRNR:
7565     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7566                        OpRHS);
7567   }
7568 }
7569 
7570 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7571                            SelectionDAG &DAG) {
7572   // Check to see if we can use the TBL instruction.
7573   SDValue V1 = Op.getOperand(0);
7574   SDValue V2 = Op.getOperand(1);
7575   SDLoc DL(Op);
7576 
7577   EVT EltVT = Op.getValueType().getVectorElementType();
7578   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7579 
7580   SmallVector<SDValue, 8> TBLMask;
7581   for (int Val : ShuffleMask) {
7582     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7583       unsigned Offset = Byte + Val * BytesPerElt;
7584       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7585     }
7586   }
7587 
7588   MVT IndexVT = MVT::v8i8;
7589   unsigned IndexLen = 8;
7590   if (Op.getValueSizeInBits() == 128) {
7591     IndexVT = MVT::v16i8;
7592     IndexLen = 16;
7593   }
7594 
7595   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7596   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7597 
7598   SDValue Shuffle;
7599   if (V2.getNode()->isUndef()) {
7600     if (IndexLen == 8)
7601       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7602     Shuffle = DAG.getNode(
7603         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7604         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7605         DAG.getBuildVector(IndexVT, DL,
7606                            makeArrayRef(TBLMask.data(), IndexLen)));
7607   } else {
7608     if (IndexLen == 8) {
7609       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7610       Shuffle = DAG.getNode(
7611           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7612           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7613           DAG.getBuildVector(IndexVT, DL,
7614                              makeArrayRef(TBLMask.data(), IndexLen)));
7615     } else {
7616       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7617       // cannot currently represent the register constraints on the input
7618       // table registers.
7619       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7620       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7621       //                   IndexLen));
7622       Shuffle = DAG.getNode(
7623           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7624           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7625           V2Cst, DAG.getBuildVector(IndexVT, DL,
7626                                     makeArrayRef(TBLMask.data(), IndexLen)));
7627     }
7628   }
7629   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7630 }
7631 
7632 static unsigned getDUPLANEOp(EVT EltType) {
7633   if (EltType == MVT::i8)
7634     return AArch64ISD::DUPLANE8;
7635   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
7636     return AArch64ISD::DUPLANE16;
7637   if (EltType == MVT::i32 || EltType == MVT::f32)
7638     return AArch64ISD::DUPLANE32;
7639   if (EltType == MVT::i64 || EltType == MVT::f64)
7640     return AArch64ISD::DUPLANE64;
7641 
7642   llvm_unreachable("Invalid vector element type?");
7643 }
7644 
7645 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7646                                                    SelectionDAG &DAG) const {
7647   SDLoc dl(Op);
7648   EVT VT = Op.getValueType();
7649 
7650   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7651 
7652   // Convert shuffles that are directly supported on NEON to target-specific
7653   // DAG nodes, instead of keeping them as shuffles and matching them again
7654   // during code selection.  This is more efficient and avoids the possibility
7655   // of inconsistencies between legalization and selection.
7656   ArrayRef<int> ShuffleMask = SVN->getMask();
7657 
7658   SDValue V1 = Op.getOperand(0);
7659   SDValue V2 = Op.getOperand(1);
7660 
7661   if (SVN->isSplat()) {
7662     int Lane = SVN->getSplatIndex();
7663     // If this is undef splat, generate it via "just" vdup, if possible.
7664     if (Lane == -1)
7665       Lane = 0;
7666 
7667     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7668       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7669                          V1.getOperand(0));
7670     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7671     // constant. If so, we can just reference the lane's definition directly.
7672     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7673         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7674       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7675 
7676     // Otherwise, duplicate from the lane of the input vector.
7677     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7678 
7679     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7680     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7681       // Match: dup (bitcast (extract_subv X, C)), LaneC
7682       if (BitCast.getOpcode() != ISD::BITCAST ||
7683           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7684         return false;
7685 
7686       // The extract index must align in the destination type. That may not
7687       // happen if the bitcast is from narrow to wide type.
7688       SDValue Extract = BitCast.getOperand(0);
7689       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7690       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7691       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7692       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7693       if (ExtIdxInBits % CastedEltBitWidth != 0)
7694         return false;
7695 
7696       // Update the lane value by offsetting with the scaled extract index.
7697       LaneC += ExtIdxInBits / CastedEltBitWidth;
7698 
7699       // Determine the casted vector type of the wide vector input.
7700       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7701       // Examples:
7702       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7703       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7704       unsigned SrcVecNumElts =
7705           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7706       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7707                                 SrcVecNumElts);
7708       return true;
7709     };
7710     MVT CastVT;
7711     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7712       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7713     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7714       // The lane is incremented by the index of the extract.
7715       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7716       Lane += V1.getConstantOperandVal(1);
7717       V1 = V1.getOperand(0);
7718     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7719       // The lane is decremented if we are splatting from the 2nd operand.
7720       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7721       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7722       Lane -= Idx * VT.getVectorNumElements() / 2;
7723       V1 = WidenVector(V1.getOperand(Idx), DAG);
7724     } else if (VT.getSizeInBits() == 64) {
7725       // Widen the operand to 128-bit register with undef.
7726       V1 = WidenVector(V1, DAG);
7727     }
7728     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7729   }
7730 
7731   if (isREVMask(ShuffleMask, VT, 64))
7732     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7733   if (isREVMask(ShuffleMask, VT, 32))
7734     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7735   if (isREVMask(ShuffleMask, VT, 16))
7736     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7737 
7738   bool ReverseEXT = false;
7739   unsigned Imm;
7740   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7741     if (ReverseEXT)
7742       std::swap(V1, V2);
7743     Imm *= getExtFactor(V1);
7744     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7745                        DAG.getConstant(Imm, dl, MVT::i32));
7746   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7747     Imm *= getExtFactor(V1);
7748     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7749                        DAG.getConstant(Imm, dl, MVT::i32));
7750   }
7751 
7752   unsigned WhichResult;
7753   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7754     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7755     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7756   }
7757   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7758     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7759     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7760   }
7761   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7762     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7763     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7764   }
7765 
7766   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7767     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7768     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7769   }
7770   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7771     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7772     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7773   }
7774   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7775     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7776     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7777   }
7778 
7779   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7780     return Concat;
7781 
7782   bool DstIsLeft;
7783   int Anomaly;
7784   int NumInputElements = V1.getValueType().getVectorNumElements();
7785   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7786     SDValue DstVec = DstIsLeft ? V1 : V2;
7787     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7788 
7789     SDValue SrcVec = V1;
7790     int SrcLane = ShuffleMask[Anomaly];
7791     if (SrcLane >= NumInputElements) {
7792       SrcVec = V2;
7793       SrcLane -= VT.getVectorNumElements();
7794     }
7795     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7796 
7797     EVT ScalarVT = VT.getVectorElementType();
7798 
7799     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7800       ScalarVT = MVT::i32;
7801 
7802     return DAG.getNode(
7803         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7804         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7805         DstLaneV);
7806   }
7807 
7808   // If the shuffle is not directly supported and it has 4 elements, use
7809   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7810   unsigned NumElts = VT.getVectorNumElements();
7811   if (NumElts == 4) {
7812     unsigned PFIndexes[4];
7813     for (unsigned i = 0; i != 4; ++i) {
7814       if (ShuffleMask[i] < 0)
7815         PFIndexes[i] = 8;
7816       else
7817         PFIndexes[i] = ShuffleMask[i];
7818     }
7819 
7820     // Compute the index in the perfect shuffle table.
7821     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7822                             PFIndexes[2] * 9 + PFIndexes[3];
7823     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7824     unsigned Cost = (PFEntry >> 30);
7825 
7826     if (Cost <= 4)
7827       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7828   }
7829 
7830   return GenerateTBL(Op, ShuffleMask, DAG);
7831 }
7832 
7833 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7834                                                  SelectionDAG &DAG) const {
7835   SDLoc dl(Op);
7836   EVT VT = Op.getValueType();
7837   EVT ElemVT = VT.getScalarType();
7838 
7839   SDValue SplatVal = Op.getOperand(0);
7840 
7841   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7842   // FPRs don't have this restriction.
7843   switch (ElemVT.getSimpleVT().SimpleTy) {
7844   case MVT::i1: {
7845     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
7846     // lowering code.
7847     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
7848       if (ConstVal->isOne())
7849         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
7850       // TODO: Add special case for constant false
7851     }
7852     // The general case of i1.  There isn't any natural way to do this,
7853     // so we use some trickery with whilelo.
7854     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7855     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7856                            DAG.getValueType(MVT::i1));
7857     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7858                                        MVT::i64);
7859     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7860                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
7861   }
7862   case MVT::i8:
7863   case MVT::i16:
7864   case MVT::i32:
7865     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7866     break;
7867   case MVT::i64:
7868     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7869     break;
7870   case MVT::f16:
7871   case MVT::bf16:
7872   case MVT::f32:
7873   case MVT::f64:
7874     // Fine as is
7875     break;
7876   default:
7877     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7878   }
7879 
7880   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7881 }
7882 
7883 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
7884                                              SelectionDAG &DAG) const {
7885   SDLoc DL(Op);
7886 
7887   EVT VT = Op.getValueType();
7888   if (!isTypeLegal(VT) || !VT.isScalableVector())
7889     return SDValue();
7890 
7891   // Current lowering only supports the SVE-ACLE types.
7892   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
7893     return SDValue();
7894 
7895   // The DUPQ operation is indepedent of element type so normalise to i64s.
7896   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
7897   SDValue Idx128 = Op.getOperand(2);
7898 
7899   // DUPQ can be used when idx is in range.
7900   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
7901   if (CIdx && (CIdx->getZExtValue() <= 3)) {
7902     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
7903     SDNode *DUPQ =
7904         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
7905     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
7906   }
7907 
7908   // The ACLE says this must produce the same result as:
7909   //   svtbl(data, svadd_x(svptrue_b64(),
7910   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
7911   //                       index * 2))
7912   SDValue One = DAG.getConstant(1, DL, MVT::i64);
7913   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
7914 
7915   // create the vector 0,1,0,1,...
7916   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
7917   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
7918                            DL, MVT::nxv2i64, Zero, One);
7919   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
7920 
7921   // create the vector idx64,idx64+1,idx64,idx64+1,...
7922   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
7923   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
7924   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
7925 
7926   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
7927   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
7928   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
7929 }
7930 
7931 
7932 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7933                                APInt &UndefBits) {
7934   EVT VT = BVN->getValueType(0);
7935   APInt SplatBits, SplatUndef;
7936   unsigned SplatBitSize;
7937   bool HasAnyUndefs;
7938   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7939     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7940 
7941     for (unsigned i = 0; i < NumSplats; ++i) {
7942       CnstBits <<= SplatBitSize;
7943       UndefBits <<= SplatBitSize;
7944       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7945       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7946     }
7947 
7948     return true;
7949   }
7950 
7951   return false;
7952 }
7953 
7954 // Try 64-bit splatted SIMD immediate.
7955 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7956                                  const APInt &Bits) {
7957   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7958     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7959     EVT VT = Op.getValueType();
7960     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7961 
7962     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7963       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7964 
7965       SDLoc dl(Op);
7966       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7967                                 DAG.getConstant(Value, dl, MVT::i32));
7968       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7969     }
7970   }
7971 
7972   return SDValue();
7973 }
7974 
7975 // Try 32-bit splatted SIMD immediate.
7976 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7977                                   const APInt &Bits,
7978                                   const SDValue *LHS = nullptr) {
7979   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7980     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7981     EVT VT = Op.getValueType();
7982     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7983     bool isAdvSIMDModImm = false;
7984     uint64_t Shift;
7985 
7986     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7987       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7988       Shift = 0;
7989     }
7990     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7991       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7992       Shift = 8;
7993     }
7994     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7995       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7996       Shift = 16;
7997     }
7998     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7999       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
8000       Shift = 24;
8001     }
8002 
8003     if (isAdvSIMDModImm) {
8004       SDLoc dl(Op);
8005       SDValue Mov;
8006 
8007       if (LHS)
8008         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8009                           DAG.getConstant(Value, dl, MVT::i32),
8010                           DAG.getConstant(Shift, dl, MVT::i32));
8011       else
8012         Mov = DAG.getNode(NewOp, dl, MovTy,
8013                           DAG.getConstant(Value, dl, MVT::i32),
8014                           DAG.getConstant(Shift, dl, MVT::i32));
8015 
8016       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8017     }
8018   }
8019 
8020   return SDValue();
8021 }
8022 
8023 // Try 16-bit splatted SIMD immediate.
8024 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8025                                   const APInt &Bits,
8026                                   const SDValue *LHS = nullptr) {
8027   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8028     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8029     EVT VT = Op.getValueType();
8030     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8031     bool isAdvSIMDModImm = false;
8032     uint64_t Shift;
8033 
8034     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8035       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8036       Shift = 0;
8037     }
8038     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8039       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8040       Shift = 8;
8041     }
8042 
8043     if (isAdvSIMDModImm) {
8044       SDLoc dl(Op);
8045       SDValue Mov;
8046 
8047       if (LHS)
8048         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8049                           DAG.getConstant(Value, dl, MVT::i32),
8050                           DAG.getConstant(Shift, dl, MVT::i32));
8051       else
8052         Mov = DAG.getNode(NewOp, dl, MovTy,
8053                           DAG.getConstant(Value, dl, MVT::i32),
8054                           DAG.getConstant(Shift, dl, MVT::i32));
8055 
8056       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8057     }
8058   }
8059 
8060   return SDValue();
8061 }
8062 
8063 // Try 32-bit splatted SIMD immediate with shifted ones.
8064 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8065                                     SelectionDAG &DAG, const APInt &Bits) {
8066   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8067     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8068     EVT VT = Op.getValueType();
8069     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8070     bool isAdvSIMDModImm = false;
8071     uint64_t Shift;
8072 
8073     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8074       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8075       Shift = 264;
8076     }
8077     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8078       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8079       Shift = 272;
8080     }
8081 
8082     if (isAdvSIMDModImm) {
8083       SDLoc dl(Op);
8084       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8085                                 DAG.getConstant(Value, dl, MVT::i32),
8086                                 DAG.getConstant(Shift, dl, MVT::i32));
8087       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8088     }
8089   }
8090 
8091   return SDValue();
8092 }
8093 
8094 // Try 8-bit splatted SIMD immediate.
8095 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8096                                  const APInt &Bits) {
8097   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8098     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8099     EVT VT = Op.getValueType();
8100     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8101 
8102     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8103       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8104 
8105       SDLoc dl(Op);
8106       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8107                                 DAG.getConstant(Value, dl, MVT::i32));
8108       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8109     }
8110   }
8111 
8112   return SDValue();
8113 }
8114 
8115 // Try FP splatted SIMD immediate.
8116 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8117                                   const APInt &Bits) {
8118   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8119     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8120     EVT VT = Op.getValueType();
8121     bool isWide = (VT.getSizeInBits() == 128);
8122     MVT MovTy;
8123     bool isAdvSIMDModImm = false;
8124 
8125     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8126       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8127       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8128     }
8129     else if (isWide &&
8130              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8131       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8132       MovTy = MVT::v2f64;
8133     }
8134 
8135     if (isAdvSIMDModImm) {
8136       SDLoc dl(Op);
8137       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8138                                 DAG.getConstant(Value, dl, MVT::i32));
8139       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8140     }
8141   }
8142 
8143   return SDValue();
8144 }
8145 
8146 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8147 // consists of only the same constant int value, returned in reference arg
8148 // ConstVal
8149 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8150                                      uint64_t &ConstVal) {
8151   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8152   if (!Bvec)
8153     return false;
8154   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8155   if (!FirstElt)
8156     return false;
8157   EVT VT = Bvec->getValueType(0);
8158   unsigned NumElts = VT.getVectorNumElements();
8159   for (unsigned i = 1; i < NumElts; ++i)
8160     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8161       return false;
8162   ConstVal = FirstElt->getZExtValue();
8163   return true;
8164 }
8165 
8166 static unsigned getIntrinsicID(const SDNode *N) {
8167   unsigned Opcode = N->getOpcode();
8168   switch (Opcode) {
8169   default:
8170     return Intrinsic::not_intrinsic;
8171   case ISD::INTRINSIC_WO_CHAIN: {
8172     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8173     if (IID < Intrinsic::num_intrinsics)
8174       return IID;
8175     return Intrinsic::not_intrinsic;
8176   }
8177   }
8178 }
8179 
8180 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8181 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8182 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8183 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8184 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8185 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
8186 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8187   EVT VT = N->getValueType(0);
8188 
8189   if (!VT.isVector())
8190     return SDValue();
8191 
8192   SDLoc DL(N);
8193 
8194   SDValue And;
8195   SDValue Shift;
8196 
8197   SDValue FirstOp = N->getOperand(0);
8198   unsigned FirstOpc = FirstOp.getOpcode();
8199   SDValue SecondOp = N->getOperand(1);
8200   unsigned SecondOpc = SecondOp.getOpcode();
8201 
8202   // Is one of the operands an AND or a BICi? The AND may have been optimised to
8203   // a BICi in order to use an immediate instead of a register.
8204   // Is the other operand an shl or lshr? This will have been turned into:
8205   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8206   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8207       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8208     And = FirstOp;
8209     Shift = SecondOp;
8210 
8211   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8212              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8213     And = SecondOp;
8214     Shift = FirstOp;
8215   } else
8216     return SDValue();
8217 
8218   bool IsAnd = And.getOpcode() == ISD::AND;
8219   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8220 
8221   // Is the shift amount constant?
8222   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8223   if (!C2node)
8224     return SDValue();
8225 
8226   uint64_t C1;
8227   if (IsAnd) {
8228     // Is the and mask vector all constant?
8229     if (!isAllConstantBuildVector(And.getOperand(1), C1))
8230       return SDValue();
8231   } else {
8232     // Reconstruct the corresponding AND immediate from the two BICi immediates.
8233     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8234     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8235     assert(C1nodeImm && C1nodeShift);
8236     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8237   }
8238 
8239   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8240   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8241   // how much one can shift elements of a particular size?
8242   uint64_t C2 = C2node->getZExtValue();
8243   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8244   if (C2 > ElemSizeInBits)
8245     return SDValue();
8246 
8247   APInt C1AsAPInt(ElemSizeInBits, C1);
8248   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8249                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
8250   if (C1AsAPInt != RequiredC1)
8251     return SDValue();
8252 
8253   SDValue X = And.getOperand(0);
8254   SDValue Y = Shift.getOperand(0);
8255 
8256   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8257   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8258 
8259   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8260   LLVM_DEBUG(N->dump(&DAG));
8261   LLVM_DEBUG(dbgs() << "into: \n");
8262   LLVM_DEBUG(ResultSLI->dump(&DAG));
8263 
8264   ++NumShiftInserts;
8265   return ResultSLI;
8266 }
8267 
8268 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8269                                              SelectionDAG &DAG) const {
8270   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8271   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8272     return Res;
8273 
8274   EVT VT = Op.getValueType();
8275 
8276   SDValue LHS = Op.getOperand(0);
8277   BuildVectorSDNode *BVN =
8278       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8279   if (!BVN) {
8280     // OR commutes, so try swapping the operands.
8281     LHS = Op.getOperand(1);
8282     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8283   }
8284   if (!BVN)
8285     return Op;
8286 
8287   APInt DefBits(VT.getSizeInBits(), 0);
8288   APInt UndefBits(VT.getSizeInBits(), 0);
8289   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8290     SDValue NewOp;
8291 
8292     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8293                                     DefBits, &LHS)) ||
8294         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8295                                     DefBits, &LHS)))
8296       return NewOp;
8297 
8298     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8299                                     UndefBits, &LHS)) ||
8300         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8301                                     UndefBits, &LHS)))
8302       return NewOp;
8303   }
8304 
8305   // We can always fall back to a non-immediate OR.
8306   return Op;
8307 }
8308 
8309 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8310 // be truncated to fit element width.
8311 static SDValue NormalizeBuildVector(SDValue Op,
8312                                     SelectionDAG &DAG) {
8313   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8314   SDLoc dl(Op);
8315   EVT VT = Op.getValueType();
8316   EVT EltTy= VT.getVectorElementType();
8317 
8318   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8319     return Op;
8320 
8321   SmallVector<SDValue, 16> Ops;
8322   for (SDValue Lane : Op->ops()) {
8323     // For integer vectors, type legalization would have promoted the
8324     // operands already. Otherwise, if Op is a floating-point splat
8325     // (with operands cast to integers), then the only possibilities
8326     // are constants and UNDEFs.
8327     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8328       APInt LowBits(EltTy.getSizeInBits(),
8329                     CstLane->getZExtValue());
8330       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8331     } else if (Lane.getNode()->isUndef()) {
8332       Lane = DAG.getUNDEF(MVT::i32);
8333     } else {
8334       assert(Lane.getValueType() == MVT::i32 &&
8335              "Unexpected BUILD_VECTOR operand type");
8336     }
8337     Ops.push_back(Lane);
8338   }
8339   return DAG.getBuildVector(VT, dl, Ops);
8340 }
8341 
8342 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8343   EVT VT = Op.getValueType();
8344 
8345   APInt DefBits(VT.getSizeInBits(), 0);
8346   APInt UndefBits(VT.getSizeInBits(), 0);
8347   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8348   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8349     SDValue NewOp;
8350     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8351         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8352         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8353         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8354         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8355         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8356       return NewOp;
8357 
8358     DefBits = ~DefBits;
8359     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8360         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8361         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8362       return NewOp;
8363 
8364     DefBits = UndefBits;
8365     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8366         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8367         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8368         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8369         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8370         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8371       return NewOp;
8372 
8373     DefBits = ~UndefBits;
8374     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8375         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8376         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8377       return NewOp;
8378   }
8379 
8380   return SDValue();
8381 }
8382 
8383 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8384                                                  SelectionDAG &DAG) const {
8385   EVT VT = Op.getValueType();
8386 
8387   // Try to build a simple constant vector.
8388   Op = NormalizeBuildVector(Op, DAG);
8389   if (VT.isInteger()) {
8390     // Certain vector constants, used to express things like logical NOT and
8391     // arithmetic NEG, are passed through unmodified.  This allows special
8392     // patterns for these operations to match, which will lower these constants
8393     // to whatever is proven necessary.
8394     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8395     if (BVN->isConstant())
8396       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8397         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8398         APInt Val(BitSize,
8399                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8400         if (Val.isNullValue() || Val.isAllOnesValue())
8401           return Op;
8402       }
8403   }
8404 
8405   if (SDValue V = ConstantBuildVector(Op, DAG))
8406     return V;
8407 
8408   // Scan through the operands to find some interesting properties we can
8409   // exploit:
8410   //   1) If only one value is used, we can use a DUP, or
8411   //   2) if only the low element is not undef, we can just insert that, or
8412   //   3) if only one constant value is used (w/ some non-constant lanes),
8413   //      we can splat the constant value into the whole vector then fill
8414   //      in the non-constant lanes.
8415   //   4) FIXME: If different constant values are used, but we can intelligently
8416   //             select the values we'll be overwriting for the non-constant
8417   //             lanes such that we can directly materialize the vector
8418   //             some other way (MOVI, e.g.), we can be sneaky.
8419   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8420   SDLoc dl(Op);
8421   unsigned NumElts = VT.getVectorNumElements();
8422   bool isOnlyLowElement = true;
8423   bool usesOnlyOneValue = true;
8424   bool usesOnlyOneConstantValue = true;
8425   bool isConstant = true;
8426   bool AllLanesExtractElt = true;
8427   unsigned NumConstantLanes = 0;
8428   SDValue Value;
8429   SDValue ConstantValue;
8430   for (unsigned i = 0; i < NumElts; ++i) {
8431     SDValue V = Op.getOperand(i);
8432     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8433       AllLanesExtractElt = false;
8434     if (V.isUndef())
8435       continue;
8436     if (i > 0)
8437       isOnlyLowElement = false;
8438     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8439       isConstant = false;
8440 
8441     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8442       ++NumConstantLanes;
8443       if (!ConstantValue.getNode())
8444         ConstantValue = V;
8445       else if (ConstantValue != V)
8446         usesOnlyOneConstantValue = false;
8447     }
8448 
8449     if (!Value.getNode())
8450       Value = V;
8451     else if (V != Value)
8452       usesOnlyOneValue = false;
8453   }
8454 
8455   if (!Value.getNode()) {
8456     LLVM_DEBUG(
8457         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
8458     return DAG.getUNDEF(VT);
8459   }
8460 
8461   // Convert BUILD_VECTOR where all elements but the lowest are undef into
8462   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
8463   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
8464   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
8465     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
8466                          "SCALAR_TO_VECTOR node\n");
8467     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8468   }
8469 
8470   if (AllLanesExtractElt) {
8471     SDNode *Vector = nullptr;
8472     bool Even = false;
8473     bool Odd = false;
8474     // Check whether the extract elements match the Even pattern <0,2,4,...> or
8475     // the Odd pattern <1,3,5,...>.
8476     for (unsigned i = 0; i < NumElts; ++i) {
8477       SDValue V = Op.getOperand(i);
8478       const SDNode *N = V.getNode();
8479       if (!isa<ConstantSDNode>(N->getOperand(1)))
8480         break;
8481       SDValue N0 = N->getOperand(0);
8482 
8483       // All elements are extracted from the same vector.
8484       if (!Vector) {
8485         Vector = N0.getNode();
8486         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8487         // BUILD_VECTOR.
8488         if (VT.getVectorElementType() !=
8489             N0.getValueType().getVectorElementType())
8490           break;
8491       } else if (Vector != N0.getNode()) {
8492         Odd = false;
8493         Even = false;
8494         break;
8495       }
8496 
8497       // Extracted values are either at Even indices <0,2,4,...> or at Odd
8498       // indices <1,3,5,...>.
8499       uint64_t Val = N->getConstantOperandVal(1);
8500       if (Val == 2 * i) {
8501         Even = true;
8502         continue;
8503       }
8504       if (Val - 1 == 2 * i) {
8505         Odd = true;
8506         continue;
8507       }
8508 
8509       // Something does not match: abort.
8510       Odd = false;
8511       Even = false;
8512       break;
8513     }
8514     if (Even || Odd) {
8515       SDValue LHS =
8516           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8517                       DAG.getConstant(0, dl, MVT::i64));
8518       SDValue RHS =
8519           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8520                       DAG.getConstant(NumElts, dl, MVT::i64));
8521 
8522       if (Even && !Odd)
8523         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8524                            RHS);
8525       if (Odd && !Even)
8526         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8527                            RHS);
8528     }
8529   }
8530 
8531   // Use DUP for non-constant splats. For f32 constant splats, reduce to
8532   // i32 and try again.
8533   if (usesOnlyOneValue) {
8534     if (!isConstant) {
8535       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8536           Value.getValueType() != VT) {
8537         LLVM_DEBUG(
8538             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8539         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8540       }
8541 
8542       // This is actually a DUPLANExx operation, which keeps everything vectory.
8543 
8544       SDValue Lane = Value.getOperand(1);
8545       Value = Value.getOperand(0);
8546       if (Value.getValueSizeInBits() == 64) {
8547         LLVM_DEBUG(
8548             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8549                       "widening it\n");
8550         Value = WidenVector(Value, DAG);
8551       }
8552 
8553       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8554       return DAG.getNode(Opcode, dl, VT, Value, Lane);
8555     }
8556 
8557     if (VT.getVectorElementType().isFloatingPoint()) {
8558       SmallVector<SDValue, 8> Ops;
8559       EVT EltTy = VT.getVectorElementType();
8560       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
8561                EltTy == MVT::f64) && "Unsupported floating-point vector type");
8562       LLVM_DEBUG(
8563           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8564                     "BITCASTS, and try again\n");
8565       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8566       for (unsigned i = 0; i < NumElts; ++i)
8567         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8568       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8569       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8570       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8571                  Val.dump(););
8572       Val = LowerBUILD_VECTOR(Val, DAG);
8573       if (Val.getNode())
8574         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8575     }
8576   }
8577 
8578   // If there was only one constant value used and for more than one lane,
8579   // start by splatting that value, then replace the non-constant lanes. This
8580   // is better than the default, which will perform a separate initialization
8581   // for each lane.
8582   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8583     // Firstly, try to materialize the splat constant.
8584     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8585             Val = ConstantBuildVector(Vec, DAG);
8586     if (!Val) {
8587       // Otherwise, materialize the constant and splat it.
8588       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8589       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8590     }
8591 
8592     // Now insert the non-constant lanes.
8593     for (unsigned i = 0; i < NumElts; ++i) {
8594       SDValue V = Op.getOperand(i);
8595       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8596       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8597         // Note that type legalization likely mucked about with the VT of the
8598         // source operand, so we may have to convert it here before inserting.
8599         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8600     }
8601     return Val;
8602   }
8603 
8604   // This will generate a load from the constant pool.
8605   if (isConstant) {
8606     LLVM_DEBUG(
8607         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8608                   "expansion\n");
8609     return SDValue();
8610   }
8611 
8612   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8613   if (NumElts >= 4) {
8614     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8615       return shuffle;
8616   }
8617 
8618   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8619   // know the default expansion would otherwise fall back on something even
8620   // worse. For a vector with one or two non-undef values, that's
8621   // scalar_to_vector for the elements followed by a shuffle (provided the
8622   // shuffle is valid for the target) and materialization element by element
8623   // on the stack followed by a load for everything else.
8624   if (!isConstant && !usesOnlyOneValue) {
8625     LLVM_DEBUG(
8626         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8627                   "of INSERT_VECTOR_ELT\n");
8628 
8629     SDValue Vec = DAG.getUNDEF(VT);
8630     SDValue Op0 = Op.getOperand(0);
8631     unsigned i = 0;
8632 
8633     // Use SCALAR_TO_VECTOR for lane zero to
8634     // a) Avoid a RMW dependency on the full vector register, and
8635     // b) Allow the register coalescer to fold away the copy if the
8636     //    value is already in an S or D register, and we're forced to emit an
8637     //    INSERT_SUBREG that we can't fold anywhere.
8638     //
8639     // We also allow types like i8 and i16 which are illegal scalar but legal
8640     // vector element types. After type-legalization the inserted value is
8641     // extended (i32) and it is safe to cast them to the vector type by ignoring
8642     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8643     if (!Op0.isUndef()) {
8644       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8645       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8646       ++i;
8647     }
8648     LLVM_DEBUG(if (i < NumElts) dbgs()
8649                    << "Creating nodes for the other vector elements:\n";);
8650     for (; i < NumElts; ++i) {
8651       SDValue V = Op.getOperand(i);
8652       if (V.isUndef())
8653         continue;
8654       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8655       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8656     }
8657     return Vec;
8658   }
8659 
8660   LLVM_DEBUG(
8661       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8662                 "better alternative\n");
8663   return SDValue();
8664 }
8665 
8666 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8667                                                       SelectionDAG &DAG) const {
8668   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8669 
8670   // Check for non-constant or out of range lane.
8671   EVT VT = Op.getOperand(0).getValueType();
8672   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8673   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8674     return SDValue();
8675 
8676 
8677   // Insertion/extraction are legal for V128 types.
8678   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8679       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8680       VT == MVT::v8f16 || VT == MVT::v8bf16)
8681     return Op;
8682 
8683   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8684       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8685       VT != MVT::v4bf16)
8686     return SDValue();
8687 
8688   // For V64 types, we perform insertion by expanding the value
8689   // to a V128 type and perform the insertion on that.
8690   SDLoc DL(Op);
8691   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8692   EVT WideTy = WideVec.getValueType();
8693 
8694   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8695                              Op.getOperand(1), Op.getOperand(2));
8696   // Re-narrow the resultant vector.
8697   return NarrowVector(Node, DAG);
8698 }
8699 
8700 SDValue
8701 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8702                                                SelectionDAG &DAG) const {
8703   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8704 
8705   // Check for non-constant or out of range lane.
8706   EVT VT = Op.getOperand(0).getValueType();
8707   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8708   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8709     return SDValue();
8710 
8711 
8712   // Insertion/extraction are legal for V128 types.
8713   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8714       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8715       VT == MVT::v8f16 || VT == MVT::v8bf16)
8716     return Op;
8717 
8718   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8719       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8720       VT != MVT::v4bf16)
8721     return SDValue();
8722 
8723   // For V64 types, we perform extraction by expanding the value
8724   // to a V128 type and perform the extraction on that.
8725   SDLoc DL(Op);
8726   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8727   EVT WideTy = WideVec.getValueType();
8728 
8729   EVT ExtrTy = WideTy.getVectorElementType();
8730   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8731     ExtrTy = MVT::i32;
8732 
8733   // For extractions, we just return the result directly.
8734   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8735                      Op.getOperand(1));
8736 }
8737 
8738 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8739                                                       SelectionDAG &DAG) const {
8740   assert(Op.getValueType().isFixedLengthVector() &&
8741          "Only cases that extract a fixed length vector are supported!");
8742 
8743   EVT InVT = Op.getOperand(0).getValueType();
8744   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8745   unsigned Size = Op.getValueSizeInBits();
8746 
8747   if (InVT.isScalableVector()) {
8748     // This will be matched by custom code during ISelDAGToDAG.
8749     if (Idx == 0 && isPackedVectorType(InVT, DAG))
8750       return Op;
8751 
8752     return SDValue();
8753   }
8754 
8755   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8756   if (Idx == 0 && InVT.getSizeInBits() <= 128)
8757     return Op;
8758 
8759   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8760   // that directly.
8761   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64)
8762     return Op;
8763 
8764   return SDValue();
8765 }
8766 
8767 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
8768                                                      SelectionDAG &DAG) const {
8769   assert(Op.getValueType().isScalableVector() &&
8770          "Only expect to lower inserts into scalable vectors!");
8771 
8772   EVT InVT = Op.getOperand(1).getValueType();
8773   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8774 
8775   // We don't have any patterns for scalable vector yet.
8776   if (InVT.isScalableVector() || !useSVEForFixedLengthVectorVT(InVT))
8777     return SDValue();
8778 
8779   // This will be matched by custom code during ISelDAGToDAG.
8780   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
8781     return Op;
8782 
8783   return SDValue();
8784 }
8785 
8786 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8787   // Currently no fixed length shuffles that require SVE are legal.
8788   if (useSVEForFixedLengthVectorVT(VT))
8789     return false;
8790 
8791   if (VT.getVectorNumElements() == 4 &&
8792       (VT.is128BitVector() || VT.is64BitVector())) {
8793     unsigned PFIndexes[4];
8794     for (unsigned i = 0; i != 4; ++i) {
8795       if (M[i] < 0)
8796         PFIndexes[i] = 8;
8797       else
8798         PFIndexes[i] = M[i];
8799     }
8800 
8801     // Compute the index in the perfect shuffle table.
8802     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8803                             PFIndexes[2] * 9 + PFIndexes[3];
8804     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8805     unsigned Cost = (PFEntry >> 30);
8806 
8807     if (Cost <= 4)
8808       return true;
8809   }
8810 
8811   bool DummyBool;
8812   int DummyInt;
8813   unsigned DummyUnsigned;
8814 
8815   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8816           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8817           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8818           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8819           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8820           isZIPMask(M, VT, DummyUnsigned) ||
8821           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8822           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8823           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8824           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8825           isConcatMask(M, VT, VT.getSizeInBits() == 128));
8826 }
8827 
8828 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8829 /// operand of a vector shift operation, where all the elements of the
8830 /// build_vector must have the same constant integer value.
8831 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8832   // Ignore bit_converts.
8833   while (Op.getOpcode() == ISD::BITCAST)
8834     Op = Op.getOperand(0);
8835   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8836   APInt SplatBits, SplatUndef;
8837   unsigned SplatBitSize;
8838   bool HasAnyUndefs;
8839   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8840                                     HasAnyUndefs, ElementBits) ||
8841       SplatBitSize > ElementBits)
8842     return false;
8843   Cnt = SplatBits.getSExtValue();
8844   return true;
8845 }
8846 
8847 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8848 /// operand of a vector shift left operation.  That value must be in the range:
8849 ///   0 <= Value < ElementBits for a left shift; or
8850 ///   0 <= Value <= ElementBits for a long left shift.
8851 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8852   assert(VT.isVector() && "vector shift count is not a vector type");
8853   int64_t ElementBits = VT.getScalarSizeInBits();
8854   if (!getVShiftImm(Op, ElementBits, Cnt))
8855     return false;
8856   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8857 }
8858 
8859 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8860 /// operand of a vector shift right operation. The value must be in the range:
8861 ///   1 <= Value <= ElementBits for a right shift; or
8862 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8863   assert(VT.isVector() && "vector shift count is not a vector type");
8864   int64_t ElementBits = VT.getScalarSizeInBits();
8865   if (!getVShiftImm(Op, ElementBits, Cnt))
8866     return false;
8867   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8868 }
8869 
8870 // Attempt to form urhadd(OpA, OpB) from
8871 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1)).
8872 // The original form of this expression is
8873 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and before this function
8874 // is called the srl will have been lowered to AArch64ISD::VLSHR and the
8875 // ((OpA + OpB + 1) >> 1) expression will have been changed to (OpB - (~OpA)).
8876 // This pass can also recognize a variant of this pattern that uses sign
8877 // extension instead of zero extension and form a srhadd(OpA, OpB) from it.
8878 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
8879                                              SelectionDAG &DAG) const {
8880   EVT VT = Op.getValueType();
8881 
8882   if (VT.getScalarType() == MVT::i1) {
8883     // Lower i1 truncate to `(x & 1) != 0`.
8884     SDLoc dl(Op);
8885     EVT OpVT = Op.getOperand(0).getValueType();
8886     SDValue Zero = DAG.getConstant(0, dl, OpVT);
8887     SDValue One = DAG.getConstant(1, dl, OpVT);
8888     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
8889     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
8890   }
8891 
8892   if (!VT.isVector() || VT.isScalableVector())
8893     return Op;
8894 
8895   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
8896     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
8897 
8898   // Since we are looking for a right shift by a constant value of 1 and we are
8899   // operating on types at least 16 bits in length (sign/zero extended OpA and
8900   // OpB, which are at least 8 bits), it follows that the truncate will always
8901   // discard the shifted-in bit and therefore the right shift will be logical
8902   // regardless of the signedness of OpA and OpB.
8903   SDValue Shift = Op.getOperand(0);
8904   if (Shift.getOpcode() != AArch64ISD::VLSHR)
8905     return Op;
8906 
8907   // Is the right shift using an immediate value of 1?
8908   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
8909   if (ShiftAmount != 1)
8910     return Op;
8911 
8912   SDValue Sub = Shift->getOperand(0);
8913   if (Sub.getOpcode() != ISD::SUB)
8914     return Op;
8915 
8916   SDValue Xor = Sub.getOperand(1);
8917   if (Xor.getOpcode() != ISD::XOR)
8918     return Op;
8919 
8920   SDValue ExtendOpA = Xor.getOperand(0);
8921   SDValue ExtendOpB = Sub.getOperand(0);
8922   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
8923   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
8924   if (!(ExtendOpAOpc == ExtendOpBOpc &&
8925         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
8926     return Op;
8927 
8928   // Is the result of the right shift being truncated to the same value type as
8929   // the original operands, OpA and OpB?
8930   SDValue OpA = ExtendOpA.getOperand(0);
8931   SDValue OpB = ExtendOpB.getOperand(0);
8932   EVT OpAVT = OpA.getValueType();
8933   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
8934   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
8935     return Op;
8936 
8937   // Is the XOR using a constant amount of all ones in the right hand side?
8938   uint64_t C;
8939   if (!isAllConstantBuildVector(Xor.getOperand(1), C))
8940     return Op;
8941 
8942   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8943   APInt CAsAPInt(ElemSizeInBits, C);
8944   if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
8945     return Op;
8946 
8947   SDLoc DL(Op);
8948   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
8949   unsigned RHADDOpc = IsSignExtend ? AArch64ISD::SRHADD : AArch64ISD::URHADD;
8950   SDValue ResultURHADD = DAG.getNode(RHADDOpc, DL, VT, OpA, OpB);
8951 
8952   return ResultURHADD;
8953 }
8954 
8955 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8956                                                       SelectionDAG &DAG) const {
8957   EVT VT = Op.getValueType();
8958   SDLoc DL(Op);
8959   int64_t Cnt;
8960 
8961   if (!Op.getOperand(1).getValueType().isVector())
8962     return Op;
8963   unsigned EltSize = VT.getScalarSizeInBits();
8964 
8965   switch (Op.getOpcode()) {
8966   default:
8967     llvm_unreachable("unexpected shift opcode");
8968 
8969   case ISD::SHL:
8970     if (VT.isScalableVector())
8971       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_MERGE_OP1);
8972 
8973     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8974       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8975                          DAG.getConstant(Cnt, DL, MVT::i32));
8976     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8977                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8978                                        MVT::i32),
8979                        Op.getOperand(0), Op.getOperand(1));
8980   case ISD::SRA:
8981   case ISD::SRL:
8982     if (VT.isScalableVector()) {
8983       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_MERGE_OP1
8984                                                 : AArch64ISD::SRL_MERGE_OP1;
8985       return LowerToPredicatedOp(Op, DAG, Opc);
8986     }
8987 
8988     // Right shift immediate
8989     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8990       unsigned Opc =
8991           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8992       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8993                          DAG.getConstant(Cnt, DL, MVT::i32));
8994     }
8995 
8996     // Right shift register.  Note, there is not a shift right register
8997     // instruction, but the shift left register instruction takes a signed
8998     // value, where negative numbers specify a right shift.
8999     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
9000                                                 : Intrinsic::aarch64_neon_ushl;
9001     // negate the shift amount
9002     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
9003     SDValue NegShiftLeft =
9004         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9005                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
9006                     NegShift);
9007     return NegShiftLeft;
9008   }
9009 
9010   return SDValue();
9011 }
9012 
9013 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
9014                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
9015                                     const SDLoc &dl, SelectionDAG &DAG) {
9016   EVT SrcVT = LHS.getValueType();
9017   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
9018          "function only supposed to emit natural comparisons");
9019 
9020   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9021   APInt CnstBits(VT.getSizeInBits(), 0);
9022   APInt UndefBits(VT.getSizeInBits(), 0);
9023   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
9024   bool IsZero = IsCnst && (CnstBits == 0);
9025 
9026   if (SrcVT.getVectorElementType().isFloatingPoint()) {
9027     switch (CC) {
9028     default:
9029       return SDValue();
9030     case AArch64CC::NE: {
9031       SDValue Fcmeq;
9032       if (IsZero)
9033         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9034       else
9035         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9036       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
9037     }
9038     case AArch64CC::EQ:
9039       if (IsZero)
9040         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9041       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9042     case AArch64CC::GE:
9043       if (IsZero)
9044         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9045       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9046     case AArch64CC::GT:
9047       if (IsZero)
9048         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9049       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9050     case AArch64CC::LS:
9051       if (IsZero)
9052         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9053       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9054     case AArch64CC::LT:
9055       if (!NoNans)
9056         return SDValue();
9057       // If we ignore NaNs then we can use to the MI implementation.
9058       LLVM_FALLTHROUGH;
9059     case AArch64CC::MI:
9060       if (IsZero)
9061         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9062       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9063     }
9064   }
9065 
9066   switch (CC) {
9067   default:
9068     return SDValue();
9069   case AArch64CC::NE: {
9070     SDValue Cmeq;
9071     if (IsZero)
9072       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9073     else
9074       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9075     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
9076   }
9077   case AArch64CC::EQ:
9078     if (IsZero)
9079       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9080     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9081   case AArch64CC::GE:
9082     if (IsZero)
9083       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9084     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9085   case AArch64CC::GT:
9086     if (IsZero)
9087       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9088     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9089   case AArch64CC::LE:
9090     if (IsZero)
9091       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9092     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9093   case AArch64CC::LS:
9094     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9095   case AArch64CC::LO:
9096     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9097   case AArch64CC::LT:
9098     if (IsZero)
9099       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9100     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9101   case AArch64CC::HI:
9102     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9103   case AArch64CC::HS:
9104     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9105   }
9106 }
9107 
9108 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9109                                            SelectionDAG &DAG) const {
9110   if (Op.getValueType().isScalableVector()) {
9111     if (Op.getOperand(0).getValueType().isFloatingPoint())
9112       return Op;
9113     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9114   }
9115 
9116   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9117   SDValue LHS = Op.getOperand(0);
9118   SDValue RHS = Op.getOperand(1);
9119   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9120   SDLoc dl(Op);
9121 
9122   if (LHS.getValueType().getVectorElementType().isInteger()) {
9123     assert(LHS.getValueType() == RHS.getValueType());
9124     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9125     SDValue Cmp =
9126         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9127     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9128   }
9129 
9130   const bool FullFP16 =
9131     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9132 
9133   // Make v4f16 (only) fcmp operations utilise vector instructions
9134   // v8f16 support will be a litle more complicated
9135   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9136     if (LHS.getValueType().getVectorNumElements() == 4) {
9137       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9138       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9139       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9140       DAG.ReplaceAllUsesWith(Op, NewSetcc);
9141       CmpVT = MVT::v4i32;
9142     } else
9143       return SDValue();
9144   }
9145 
9146   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9147           LHS.getValueType().getVectorElementType() != MVT::f128);
9148 
9149   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9150   // clean.  Some of them require two branches to implement.
9151   AArch64CC::CondCode CC1, CC2;
9152   bool ShouldInvert;
9153   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9154 
9155   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9156   SDValue Cmp =
9157       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9158   if (!Cmp.getNode())
9159     return SDValue();
9160 
9161   if (CC2 != AArch64CC::AL) {
9162     SDValue Cmp2 =
9163         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9164     if (!Cmp2.getNode())
9165       return SDValue();
9166 
9167     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9168   }
9169 
9170   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9171 
9172   if (ShouldInvert)
9173     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9174 
9175   return Cmp;
9176 }
9177 
9178 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9179                                   SelectionDAG &DAG) {
9180   SDValue VecOp = ScalarOp.getOperand(0);
9181   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9182   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9183                      DAG.getConstant(0, DL, MVT::i64));
9184 }
9185 
9186 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9187                                               SelectionDAG &DAG) const {
9188   SDLoc dl(Op);
9189   switch (Op.getOpcode()) {
9190   case ISD::VECREDUCE_ADD:
9191     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9192   case ISD::VECREDUCE_SMAX:
9193     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9194   case ISD::VECREDUCE_SMIN:
9195     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9196   case ISD::VECREDUCE_UMAX:
9197     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9198   case ISD::VECREDUCE_UMIN:
9199     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9200   case ISD::VECREDUCE_FMAX: {
9201     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
9202     return DAG.getNode(
9203         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9204         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9205         Op.getOperand(0));
9206   }
9207   case ISD::VECREDUCE_FMIN: {
9208     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
9209     return DAG.getNode(
9210         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9211         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
9212         Op.getOperand(0));
9213   }
9214   default:
9215     llvm_unreachable("Unhandled reduction");
9216   }
9217 }
9218 
9219 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
9220                                                     SelectionDAG &DAG) const {
9221   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9222   if (!Subtarget.hasLSE())
9223     return SDValue();
9224 
9225   // LSE has an atomic load-add instruction, but not a load-sub.
9226   SDLoc dl(Op);
9227   MVT VT = Op.getSimpleValueType();
9228   SDValue RHS = Op.getOperand(2);
9229   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9230   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
9231   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
9232                        Op.getOperand(0), Op.getOperand(1), RHS,
9233                        AN->getMemOperand());
9234 }
9235 
9236 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
9237                                                     SelectionDAG &DAG) const {
9238   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9239   if (!Subtarget.hasLSE())
9240     return SDValue();
9241 
9242   // LSE has an atomic load-clear instruction, but not a load-and.
9243   SDLoc dl(Op);
9244   MVT VT = Op.getSimpleValueType();
9245   SDValue RHS = Op.getOperand(2);
9246   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9247   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
9248   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
9249                        Op.getOperand(0), Op.getOperand(1), RHS,
9250                        AN->getMemOperand());
9251 }
9252 
9253 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
9254     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
9255   SDLoc dl(Op);
9256   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9257   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
9258 
9259   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
9260   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
9261   if (Subtarget->hasCustomCallingConv())
9262     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
9263 
9264   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
9265                      DAG.getConstant(4, dl, MVT::i64));
9266   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
9267   Chain =
9268       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
9269                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
9270                   DAG.getRegisterMask(Mask), Chain.getValue(1));
9271   // To match the actual intent better, we should read the output from X15 here
9272   // again (instead of potentially spilling it to the stack), but rereading Size
9273   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
9274   // here.
9275 
9276   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
9277                      DAG.getConstant(4, dl, MVT::i64));
9278   return Chain;
9279 }
9280 
9281 SDValue
9282 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9283                                                SelectionDAG &DAG) const {
9284   assert(Subtarget->isTargetWindows() &&
9285          "Only Windows alloca probing supported");
9286   SDLoc dl(Op);
9287   // Get the inputs.
9288   SDNode *Node = Op.getNode();
9289   SDValue Chain = Op.getOperand(0);
9290   SDValue Size = Op.getOperand(1);
9291   MaybeAlign Align =
9292       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
9293   EVT VT = Node->getValueType(0);
9294 
9295   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
9296           "no-stack-arg-probe")) {
9297     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9298     Chain = SP.getValue(1);
9299     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9300     if (Align)
9301       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9302                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9303     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9304     SDValue Ops[2] = {SP, Chain};
9305     return DAG.getMergeValues(Ops, dl);
9306   }
9307 
9308   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
9309 
9310   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
9311 
9312   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9313   Chain = SP.getValue(1);
9314   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9315   if (Align)
9316     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9317                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9318   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9319 
9320   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
9321                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
9322 
9323   SDValue Ops[2] = {SP, Chain};
9324   return DAG.getMergeValues(Ops, dl);
9325 }
9326 
9327 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
9328                                            SelectionDAG &DAG) const {
9329   EVT VT = Op.getValueType();
9330   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
9331 
9332   SDLoc DL(Op);
9333   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
9334   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
9335                             DL, VT);
9336 }
9337 
9338 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
9339 template <unsigned NumVecs>
9340 static bool setInfoSVEStN(AArch64TargetLowering::IntrinsicInfo &Info,
9341                           const CallInst &CI) {
9342   Info.opc = ISD::INTRINSIC_VOID;
9343   // Retrieve EC from first vector argument.
9344   const EVT VT = EVT::getEVT(CI.getArgOperand(0)->getType());
9345   ElementCount EC = VT.getVectorElementCount();
9346 #ifndef NDEBUG
9347   // Check the assumption that all input vectors are the same type.
9348   for (unsigned I = 0; I < NumVecs; ++I)
9349     assert(VT == EVT::getEVT(CI.getArgOperand(I)->getType()) &&
9350            "Invalid type.");
9351 #endif
9352   // memVT is `NumVecs * VT`.
9353   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
9354                                 EC * NumVecs);
9355   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
9356   Info.offset = 0;
9357   Info.align.reset();
9358   Info.flags = MachineMemOperand::MOStore;
9359   return true;
9360 }
9361 
9362 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9363 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9364 /// specified in the intrinsic calls.
9365 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9366                                                const CallInst &I,
9367                                                MachineFunction &MF,
9368                                                unsigned Intrinsic) const {
9369   auto &DL = I.getModule()->getDataLayout();
9370   switch (Intrinsic) {
9371   case Intrinsic::aarch64_sve_st2:
9372     return setInfoSVEStN<2>(Info, I);
9373   case Intrinsic::aarch64_sve_st3:
9374     return setInfoSVEStN<3>(Info, I);
9375   case Intrinsic::aarch64_sve_st4:
9376     return setInfoSVEStN<4>(Info, I);
9377   case Intrinsic::aarch64_neon_ld2:
9378   case Intrinsic::aarch64_neon_ld3:
9379   case Intrinsic::aarch64_neon_ld4:
9380   case Intrinsic::aarch64_neon_ld1x2:
9381   case Intrinsic::aarch64_neon_ld1x3:
9382   case Intrinsic::aarch64_neon_ld1x4:
9383   case Intrinsic::aarch64_neon_ld2lane:
9384   case Intrinsic::aarch64_neon_ld3lane:
9385   case Intrinsic::aarch64_neon_ld4lane:
9386   case Intrinsic::aarch64_neon_ld2r:
9387   case Intrinsic::aarch64_neon_ld3r:
9388   case Intrinsic::aarch64_neon_ld4r: {
9389     Info.opc = ISD::INTRINSIC_W_CHAIN;
9390     // Conservatively set memVT to the entire set of vectors loaded.
9391     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
9392     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9393     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9394     Info.offset = 0;
9395     Info.align.reset();
9396     // volatile loads with NEON intrinsics not supported
9397     Info.flags = MachineMemOperand::MOLoad;
9398     return true;
9399   }
9400   case Intrinsic::aarch64_neon_st2:
9401   case Intrinsic::aarch64_neon_st3:
9402   case Intrinsic::aarch64_neon_st4:
9403   case Intrinsic::aarch64_neon_st1x2:
9404   case Intrinsic::aarch64_neon_st1x3:
9405   case Intrinsic::aarch64_neon_st1x4:
9406   case Intrinsic::aarch64_neon_st2lane:
9407   case Intrinsic::aarch64_neon_st3lane:
9408   case Intrinsic::aarch64_neon_st4lane: {
9409     Info.opc = ISD::INTRINSIC_VOID;
9410     // Conservatively set memVT to the entire set of vectors stored.
9411     unsigned NumElts = 0;
9412     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9413       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9414       if (!ArgTy->isVectorTy())
9415         break;
9416       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
9417     }
9418     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9419     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9420     Info.offset = 0;
9421     Info.align.reset();
9422     // volatile stores with NEON intrinsics not supported
9423     Info.flags = MachineMemOperand::MOStore;
9424     return true;
9425   }
9426   case Intrinsic::aarch64_ldaxr:
9427   case Intrinsic::aarch64_ldxr: {
9428     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
9429     Info.opc = ISD::INTRINSIC_W_CHAIN;
9430     Info.memVT = MVT::getVT(PtrTy->getElementType());
9431     Info.ptrVal = I.getArgOperand(0);
9432     Info.offset = 0;
9433     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9434     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9435     return true;
9436   }
9437   case Intrinsic::aarch64_stlxr:
9438   case Intrinsic::aarch64_stxr: {
9439     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9440     Info.opc = ISD::INTRINSIC_W_CHAIN;
9441     Info.memVT = MVT::getVT(PtrTy->getElementType());
9442     Info.ptrVal = I.getArgOperand(1);
9443     Info.offset = 0;
9444     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9445     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9446     return true;
9447   }
9448   case Intrinsic::aarch64_ldaxp:
9449   case Intrinsic::aarch64_ldxp:
9450     Info.opc = ISD::INTRINSIC_W_CHAIN;
9451     Info.memVT = MVT::i128;
9452     Info.ptrVal = I.getArgOperand(0);
9453     Info.offset = 0;
9454     Info.align = Align(16);
9455     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9456     return true;
9457   case Intrinsic::aarch64_stlxp:
9458   case Intrinsic::aarch64_stxp:
9459     Info.opc = ISD::INTRINSIC_W_CHAIN;
9460     Info.memVT = MVT::i128;
9461     Info.ptrVal = I.getArgOperand(2);
9462     Info.offset = 0;
9463     Info.align = Align(16);
9464     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9465     return true;
9466   case Intrinsic::aarch64_sve_ldnt1: {
9467     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9468     Info.opc = ISD::INTRINSIC_W_CHAIN;
9469     Info.memVT = MVT::getVT(I.getType());
9470     Info.ptrVal = I.getArgOperand(1);
9471     Info.offset = 0;
9472     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9473     Info.flags = MachineMemOperand::MOLoad;
9474     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
9475       Info.flags |= MachineMemOperand::MONonTemporal;
9476     return true;
9477   }
9478   case Intrinsic::aarch64_sve_stnt1: {
9479     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
9480     Info.opc = ISD::INTRINSIC_W_CHAIN;
9481     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
9482     Info.ptrVal = I.getArgOperand(2);
9483     Info.offset = 0;
9484     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9485     Info.flags = MachineMemOperand::MOStore;
9486     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
9487       Info.flags |= MachineMemOperand::MONonTemporal;
9488     return true;
9489   }
9490   default:
9491     break;
9492   }
9493 
9494   return false;
9495 }
9496 
9497 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
9498                                                   ISD::LoadExtType ExtTy,
9499                                                   EVT NewVT) const {
9500   // TODO: This may be worth removing. Check regression tests for diffs.
9501   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
9502     return false;
9503 
9504   // If we're reducing the load width in order to avoid having to use an extra
9505   // instruction to do extension then it's probably a good idea.
9506   if (ExtTy != ISD::NON_EXTLOAD)
9507     return true;
9508   // Don't reduce load width if it would prevent us from combining a shift into
9509   // the offset.
9510   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
9511   assert(Mem);
9512   const SDValue &Base = Mem->getBasePtr();
9513   if (Base.getOpcode() == ISD::ADD &&
9514       Base.getOperand(1).getOpcode() == ISD::SHL &&
9515       Base.getOperand(1).hasOneUse() &&
9516       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
9517     // The shift can be combined if it matches the size of the value being
9518     // loaded (and so reducing the width would make it not match).
9519     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
9520     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
9521     if (ShiftAmount == Log2_32(LoadBytes))
9522       return false;
9523   }
9524   // We have no reason to disallow reducing the load width, so allow it.
9525   return true;
9526 }
9527 
9528 // Truncations from 64-bit GPR to 32-bit GPR is free.
9529 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9530   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9531     return false;
9532   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9533   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9534   return NumBits1 > NumBits2;
9535 }
9536 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9537   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9538     return false;
9539   unsigned NumBits1 = VT1.getSizeInBits();
9540   unsigned NumBits2 = VT2.getSizeInBits();
9541   return NumBits1 > NumBits2;
9542 }
9543 
9544 /// Check if it is profitable to hoist instruction in then/else to if.
9545 /// Not profitable if I and it's user can form a FMA instruction
9546 /// because we prefer FMSUB/FMADD.
9547 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
9548   if (I->getOpcode() != Instruction::FMul)
9549     return true;
9550 
9551   if (!I->hasOneUse())
9552     return true;
9553 
9554   Instruction *User = I->user_back();
9555 
9556   if (User &&
9557       !(User->getOpcode() == Instruction::FSub ||
9558         User->getOpcode() == Instruction::FAdd))
9559     return true;
9560 
9561   const TargetOptions &Options = getTargetMachine().Options;
9562   const Function *F = I->getFunction();
9563   const DataLayout &DL = F->getParent()->getDataLayout();
9564   Type *Ty = User->getOperand(0)->getType();
9565 
9566   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
9567            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
9568            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9569             Options.UnsafeFPMath));
9570 }
9571 
9572 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
9573 // 64-bit GPR.
9574 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9575   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9576     return false;
9577   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9578   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9579   return NumBits1 == 32 && NumBits2 == 64;
9580 }
9581 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9582   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9583     return false;
9584   unsigned NumBits1 = VT1.getSizeInBits();
9585   unsigned NumBits2 = VT2.getSizeInBits();
9586   return NumBits1 == 32 && NumBits2 == 64;
9587 }
9588 
9589 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9590   EVT VT1 = Val.getValueType();
9591   if (isZExtFree(VT1, VT2)) {
9592     return true;
9593   }
9594 
9595   if (Val.getOpcode() != ISD::LOAD)
9596     return false;
9597 
9598   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
9599   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
9600           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
9601           VT1.getSizeInBits() <= 32);
9602 }
9603 
9604 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
9605   if (isa<FPExtInst>(Ext))
9606     return false;
9607 
9608   // Vector types are not free.
9609   if (Ext->getType()->isVectorTy())
9610     return false;
9611 
9612   for (const Use &U : Ext->uses()) {
9613     // The extension is free if we can fold it with a left shift in an
9614     // addressing mode or an arithmetic operation: add, sub, and cmp.
9615 
9616     // Is there a shift?
9617     const Instruction *Instr = cast<Instruction>(U.getUser());
9618 
9619     // Is this a constant shift?
9620     switch (Instr->getOpcode()) {
9621     case Instruction::Shl:
9622       if (!isa<ConstantInt>(Instr->getOperand(1)))
9623         return false;
9624       break;
9625     case Instruction::GetElementPtr: {
9626       gep_type_iterator GTI = gep_type_begin(Instr);
9627       auto &DL = Ext->getModule()->getDataLayout();
9628       std::advance(GTI, U.getOperandNo()-1);
9629       Type *IdxTy = GTI.getIndexedType();
9630       // This extension will end up with a shift because of the scaling factor.
9631       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
9632       // Get the shift amount based on the scaling factor:
9633       // log2(sizeof(IdxTy)) - log2(8).
9634       uint64_t ShiftAmt =
9635         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9636       // Is the constant foldable in the shift of the addressing mode?
9637       // I.e., shift amount is between 1 and 4 inclusive.
9638       if (ShiftAmt == 0 || ShiftAmt > 4)
9639         return false;
9640       break;
9641     }
9642     case Instruction::Trunc:
9643       // Check if this is a noop.
9644       // trunc(sext ty1 to ty2) to ty1.
9645       if (Instr->getType() == Ext->getOperand(0)->getType())
9646         continue;
9647       LLVM_FALLTHROUGH;
9648     default:
9649       return false;
9650     }
9651 
9652     // At this point we can use the bfm family, so this extension is free
9653     // for that use.
9654   }
9655   return true;
9656 }
9657 
9658 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9659 /// or upper half of the vector elements.
9660 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9661   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9662     auto *FullTy = FullV->getType();
9663     auto *HalfTy = HalfV->getType();
9664     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
9665            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
9666   };
9667 
9668   auto extractHalf = [](Value *FullV, Value *HalfV) {
9669     auto *FullVT = cast<FixedVectorType>(FullV->getType());
9670     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
9671     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9672   };
9673 
9674   ArrayRef<int> M1, M2;
9675   Value *S1Op1, *S2Op1;
9676   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
9677       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
9678     return false;
9679 
9680   // Check that the operands are half as wide as the result and we extract
9681   // half of the elements of the input vectors.
9682   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9683       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9684     return false;
9685 
9686   // Check the mask extracts either the lower or upper half of vector
9687   // elements.
9688   int M1Start = -1;
9689   int M2Start = -1;
9690   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
9691   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9692       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9693       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9694     return false;
9695 
9696   return true;
9697 }
9698 
9699 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9700 /// of the vector elements.
9701 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9702   auto areExtDoubled = [](Instruction *Ext) {
9703     return Ext->getType()->getScalarSizeInBits() ==
9704            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9705   };
9706 
9707   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9708       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9709       !areExtDoubled(cast<Instruction>(Ext1)) ||
9710       !areExtDoubled(cast<Instruction>(Ext2)))
9711     return false;
9712 
9713   return true;
9714 }
9715 
9716 /// Check if Op could be used with vmull_high_p64 intrinsic.
9717 static bool isOperandOfVmullHighP64(Value *Op) {
9718   Value *VectorOperand = nullptr;
9719   ConstantInt *ElementIndex = nullptr;
9720   return match(Op, m_ExtractElt(m_Value(VectorOperand),
9721                                 m_ConstantInt(ElementIndex))) &&
9722          ElementIndex->getValue() == 1 &&
9723          isa<FixedVectorType>(VectorOperand->getType()) &&
9724          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
9725 }
9726 
9727 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
9728 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
9729   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
9730 }
9731 
9732 /// Check if sinking \p I's operands to I's basic block is profitable, because
9733 /// the operands can be folded into a target instruction, e.g.
9734 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9735 bool AArch64TargetLowering::shouldSinkOperands(
9736     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9737   if (!I->getType()->isVectorTy())
9738     return false;
9739 
9740   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9741     switch (II->getIntrinsicID()) {
9742     case Intrinsic::aarch64_neon_umull:
9743       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9744         return false;
9745       Ops.push_back(&II->getOperandUse(0));
9746       Ops.push_back(&II->getOperandUse(1));
9747       return true;
9748 
9749     case Intrinsic::aarch64_neon_pmull64:
9750       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
9751                                      II->getArgOperand(1)))
9752         return false;
9753       Ops.push_back(&II->getArgOperandUse(0));
9754       Ops.push_back(&II->getArgOperandUse(1));
9755       return true;
9756 
9757     default:
9758       return false;
9759     }
9760   }
9761 
9762   switch (I->getOpcode()) {
9763   case Instruction::Sub:
9764   case Instruction::Add: {
9765     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9766       return false;
9767 
9768     // If the exts' operands extract either the lower or upper elements, we
9769     // can sink them too.
9770     auto Ext1 = cast<Instruction>(I->getOperand(0));
9771     auto Ext2 = cast<Instruction>(I->getOperand(1));
9772     if (areExtractShuffleVectors(Ext1, Ext2)) {
9773       Ops.push_back(&Ext1->getOperandUse(0));
9774       Ops.push_back(&Ext2->getOperandUse(0));
9775     }
9776 
9777     Ops.push_back(&I->getOperandUse(0));
9778     Ops.push_back(&I->getOperandUse(1));
9779 
9780     return true;
9781   }
9782   default:
9783     return false;
9784   }
9785   return false;
9786 }
9787 
9788 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9789                                           Align &RequiredAligment) const {
9790   if (!LoadedType.isSimple() ||
9791       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9792     return false;
9793   // Cyclone supports unaligned accesses.
9794   RequiredAligment = Align(1);
9795   unsigned NumBits = LoadedType.getSizeInBits();
9796   return NumBits == 32 || NumBits == 64;
9797 }
9798 
9799 /// A helper function for determining the number of interleaved accesses we
9800 /// will generate when lowering accesses of the given type.
9801 unsigned
9802 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9803                                                  const DataLayout &DL) const {
9804   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9805 }
9806 
9807 MachineMemOperand::Flags
9808 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9809   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9810       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9811     return MOStridedAccess;
9812   return MachineMemOperand::MONone;
9813 }
9814 
9815 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9816     VectorType *VecTy, const DataLayout &DL) const {
9817 
9818   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9819   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9820 
9821   // Ensure the number of vector elements is greater than 1.
9822   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
9823     return false;
9824 
9825   // Ensure the element type is legal.
9826   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9827     return false;
9828 
9829   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9830   // 128 will be split into multiple interleaved accesses.
9831   return VecSize == 64 || VecSize % 128 == 0;
9832 }
9833 
9834 /// Lower an interleaved load into a ldN intrinsic.
9835 ///
9836 /// E.g. Lower an interleaved load (Factor = 2):
9837 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9838 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9839 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9840 ///
9841 ///      Into:
9842 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9843 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9844 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9845 bool AArch64TargetLowering::lowerInterleavedLoad(
9846     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9847     ArrayRef<unsigned> Indices, unsigned Factor) const {
9848   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9849          "Invalid interleave factor");
9850   assert(!Shuffles.empty() && "Empty shufflevector input");
9851   assert(Shuffles.size() == Indices.size() &&
9852          "Unmatched number of shufflevectors and indices");
9853 
9854   const DataLayout &DL = LI->getModule()->getDataLayout();
9855 
9856   VectorType *VTy = Shuffles[0]->getType();
9857 
9858   // Skip if we do not have NEON and skip illegal vector types. We can
9859   // "legalize" wide vector types into multiple interleaved accesses as long as
9860   // the vector types are divisible by 128.
9861   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
9862     return false;
9863 
9864   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
9865 
9866   auto *FVTy = cast<FixedVectorType>(VTy);
9867 
9868   // A pointer vector can not be the return type of the ldN intrinsics. Need to
9869   // load integer vectors first and then convert to pointer vectors.
9870   Type *EltTy = FVTy->getElementType();
9871   if (EltTy->isPointerTy())
9872     FVTy =
9873         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
9874 
9875   IRBuilder<> Builder(LI);
9876 
9877   // The base address of the load.
9878   Value *BaseAddr = LI->getPointerOperand();
9879 
9880   if (NumLoads > 1) {
9881     // If we're going to generate more than one load, reset the sub-vector type
9882     // to something legal.
9883     FVTy = FixedVectorType::get(FVTy->getElementType(),
9884                                 FVTy->getNumElements() / NumLoads);
9885 
9886     // We will compute the pointer operand of each load from the original base
9887     // address using GEPs. Cast the base address to a pointer to the scalar
9888     // element type.
9889     BaseAddr = Builder.CreateBitCast(
9890         BaseAddr,
9891         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
9892   }
9893 
9894   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
9895   Type *Tys[2] = {FVTy, PtrTy};
9896   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9897                                             Intrinsic::aarch64_neon_ld3,
9898                                             Intrinsic::aarch64_neon_ld4};
9899   Function *LdNFunc =
9900       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9901 
9902   // Holds sub-vectors extracted from the load intrinsic return values. The
9903   // sub-vectors are associated with the shufflevector instructions they will
9904   // replace.
9905   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9906 
9907   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9908 
9909     // If we're generating more than one load, compute the base address of
9910     // subsequent loads as an offset from the previous.
9911     if (LoadCount > 0)
9912       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
9913                                             FVTy->getNumElements() * Factor);
9914 
9915     CallInst *LdN = Builder.CreateCall(
9916         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9917 
9918     // Extract and store the sub-vectors returned by the load intrinsic.
9919     for (unsigned i = 0; i < Shuffles.size(); i++) {
9920       ShuffleVectorInst *SVI = Shuffles[i];
9921       unsigned Index = Indices[i];
9922 
9923       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9924 
9925       // Convert the integer vector to pointer vector if the element is pointer.
9926       if (EltTy->isPointerTy())
9927         SubVec = Builder.CreateIntToPtr(
9928             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
9929                                          FVTy->getNumElements()));
9930       SubVecs[SVI].push_back(SubVec);
9931     }
9932   }
9933 
9934   // Replace uses of the shufflevector instructions with the sub-vectors
9935   // returned by the load intrinsic. If a shufflevector instruction is
9936   // associated with more than one sub-vector, those sub-vectors will be
9937   // concatenated into a single wide vector.
9938   for (ShuffleVectorInst *SVI : Shuffles) {
9939     auto &SubVec = SubVecs[SVI];
9940     auto *WideVec =
9941         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9942     SVI->replaceAllUsesWith(WideVec);
9943   }
9944 
9945   return true;
9946 }
9947 
9948 /// Lower an interleaved store into a stN intrinsic.
9949 ///
9950 /// E.g. Lower an interleaved store (Factor = 3):
9951 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9952 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9953 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9954 ///
9955 ///      Into:
9956 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9957 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9958 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9959 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9960 ///
9961 /// Note that the new shufflevectors will be removed and we'll only generate one
9962 /// st3 instruction in CodeGen.
9963 ///
9964 /// Example for a more general valid mask (Factor 3). Lower:
9965 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9966 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9967 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9968 ///
9969 ///      Into:
9970 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9971 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9972 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9973 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9974 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9975                                                   ShuffleVectorInst *SVI,
9976                                                   unsigned Factor) const {
9977   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9978          "Invalid interleave factor");
9979 
9980   auto *VecTy = cast<FixedVectorType>(SVI->getType());
9981   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
9982 
9983   unsigned LaneLen = VecTy->getNumElements() / Factor;
9984   Type *EltTy = VecTy->getElementType();
9985   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
9986 
9987   const DataLayout &DL = SI->getModule()->getDataLayout();
9988 
9989   // Skip if we do not have NEON and skip illegal vector types. We can
9990   // "legalize" wide vector types into multiple interleaved accesses as long as
9991   // the vector types are divisible by 128.
9992   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9993     return false;
9994 
9995   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9996 
9997   Value *Op0 = SVI->getOperand(0);
9998   Value *Op1 = SVI->getOperand(1);
9999   IRBuilder<> Builder(SI);
10000 
10001   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
10002   // vectors to integer vectors.
10003   if (EltTy->isPointerTy()) {
10004     Type *IntTy = DL.getIntPtrType(EltTy);
10005     unsigned NumOpElts =
10006         cast<FixedVectorType>(Op0->getType())->getNumElements();
10007 
10008     // Convert to the corresponding integer vector.
10009     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
10010     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
10011     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
10012 
10013     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
10014   }
10015 
10016   // The base address of the store.
10017   Value *BaseAddr = SI->getPointerOperand();
10018 
10019   if (NumStores > 1) {
10020     // If we're going to generate more than one store, reset the lane length
10021     // and sub-vector type to something legal.
10022     LaneLen /= NumStores;
10023     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
10024 
10025     // We will compute the pointer operand of each store from the original base
10026     // address using GEPs. Cast the base address to a pointer to the scalar
10027     // element type.
10028     BaseAddr = Builder.CreateBitCast(
10029         BaseAddr,
10030         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10031   }
10032 
10033   auto Mask = SVI->getShuffleMask();
10034 
10035   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10036   Type *Tys[2] = {SubVecTy, PtrTy};
10037   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10038                                              Intrinsic::aarch64_neon_st3,
10039                                              Intrinsic::aarch64_neon_st4};
10040   Function *StNFunc =
10041       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10042 
10043   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10044 
10045     SmallVector<Value *, 5> Ops;
10046 
10047     // Split the shufflevector operands into sub vectors for the new stN call.
10048     for (unsigned i = 0; i < Factor; i++) {
10049       unsigned IdxI = StoreCount * LaneLen * Factor + i;
10050       if (Mask[IdxI] >= 0) {
10051         Ops.push_back(Builder.CreateShuffleVector(
10052             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10053       } else {
10054         unsigned StartMask = 0;
10055         for (unsigned j = 1; j < LaneLen; j++) {
10056           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10057           if (Mask[IdxJ * Factor + IdxI] >= 0) {
10058             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10059             break;
10060           }
10061         }
10062         // Note: Filling undef gaps with random elements is ok, since
10063         // those elements were being written anyway (with undefs).
10064         // In the case of all undefs we're defaulting to using elems from 0
10065         // Note: StartMask cannot be negative, it's checked in
10066         // isReInterleaveMask
10067         Ops.push_back(Builder.CreateShuffleVector(
10068             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10069       }
10070     }
10071 
10072     // If we generating more than one store, we compute the base address of
10073     // subsequent stores as an offset from the previous.
10074     if (StoreCount > 0)
10075       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10076                                             BaseAddr, LaneLen * Factor);
10077 
10078     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10079     Builder.CreateCall(StNFunc, Ops);
10080   }
10081   return true;
10082 }
10083 
10084 // Lower an SVE structured load intrinsic returning a tuple type to target
10085 // specific intrinsic taking the same input but returning a multi-result value
10086 // of the split tuple type.
10087 //
10088 // E.g. Lowering an LD3:
10089 //
10090 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10091 //                                                    <vscale x 4 x i1> %pred,
10092 //                                                    <vscale x 4 x i32>* %addr)
10093 //
10094 //  Output DAG:
10095 //
10096 //    t0: ch = EntryToken
10097 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10098 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
10099 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10100 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10101 //
10102 // This is called pre-legalization to avoid widening/splitting issues with
10103 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
10104 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10105                                                   ArrayRef<SDValue> LoadOps,
10106                                                   EVT VT, SelectionDAG &DAG,
10107                                                   const SDLoc &DL) const {
10108   assert(VT.isScalableVector() && "Can only lower scalable vectors");
10109 
10110   unsigned N, Opcode;
10111   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10112       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10113       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10114       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10115 
10116   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10117   assert(VT.getVectorElementCount().Min % N == 0 &&
10118          "invalid tuple vector type!");
10119 
10120   EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10121                                  VT.getVectorElementCount() / N);
10122   assert(isTypeLegal(SplitVT));
10123 
10124   SmallVector<EVT, 5> VTs(N, SplitVT);
10125   VTs.push_back(MVT::Other); // Chain
10126   SDVTList NodeTys = DAG.getVTList(VTs);
10127 
10128   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10129   SmallVector<SDValue, 4> PseudoLoadOps;
10130   for (unsigned I = 0; I < N; ++I)
10131     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10132   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10133 }
10134 
10135 EVT AArch64TargetLowering::getOptimalMemOpType(
10136     const MemOp &Op, const AttributeList &FuncAttributes) const {
10137   bool CanImplicitFloat =
10138       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10139   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10140   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10141   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10142   // taken one instruction to materialize the v2i64 zero and one store (with
10143   // restrictive addressing mode). Just do i64 stores.
10144   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10145   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10146     if (Op.isAligned(AlignCheck))
10147       return true;
10148     bool Fast;
10149     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10150                                           &Fast) &&
10151            Fast;
10152   };
10153 
10154   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10155       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10156     return MVT::v2i64;
10157   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10158     return MVT::f128;
10159   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10160     return MVT::i64;
10161   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10162     return MVT::i32;
10163   return MVT::Other;
10164 }
10165 
10166 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10167     const MemOp &Op, const AttributeList &FuncAttributes) const {
10168   bool CanImplicitFloat =
10169       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10170   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10171   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10172   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10173   // taken one instruction to materialize the v2i64 zero and one store (with
10174   // restrictive addressing mode). Just do i64 stores.
10175   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10176   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10177     if (Op.isAligned(AlignCheck))
10178       return true;
10179     bool Fast;
10180     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10181                                           &Fast) &&
10182            Fast;
10183   };
10184 
10185   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10186       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10187     return LLT::vector(2, 64);
10188   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10189     return LLT::scalar(128);
10190   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10191     return LLT::scalar(64);
10192   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10193     return LLT::scalar(32);
10194   return LLT();
10195 }
10196 
10197 // 12-bit optionally shifted immediates are legal for adds.
10198 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10199   if (Immed == std::numeric_limits<int64_t>::min()) {
10200     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10201                       << ": avoid UB for INT64_MIN\n");
10202     return false;
10203   }
10204   // Same encoding for add/sub, just flip the sign.
10205   Immed = std::abs(Immed);
10206   bool IsLegal = ((Immed >> 12) == 0 ||
10207                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
10208   LLVM_DEBUG(dbgs() << "Is " << Immed
10209                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
10210   return IsLegal;
10211 }
10212 
10213 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
10214 // immediates is the same as for an add or a sub.
10215 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
10216   return isLegalAddImmediate(Immed);
10217 }
10218 
10219 /// isLegalAddressingMode - Return true if the addressing mode represented
10220 /// by AM is legal for this target, for a load/store of the specified type.
10221 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
10222                                                   const AddrMode &AM, Type *Ty,
10223                                                   unsigned AS, Instruction *I) const {
10224   // AArch64 has five basic addressing modes:
10225   //  reg
10226   //  reg + 9-bit signed offset
10227   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
10228   //  reg1 + reg2
10229   //  reg + SIZE_IN_BYTES * reg
10230 
10231   // No global is ever allowed as a base.
10232   if (AM.BaseGV)
10233     return false;
10234 
10235   // No reg+reg+imm addressing.
10236   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
10237     return false;
10238 
10239   // FIXME: Update this method to support scalable addressing modes.
10240   if (isa<ScalableVectorType>(Ty))
10241     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
10242 
10243   // check reg + imm case:
10244   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
10245   uint64_t NumBytes = 0;
10246   if (Ty->isSized()) {
10247     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
10248     NumBytes = NumBits / 8;
10249     if (!isPowerOf2_64(NumBits))
10250       NumBytes = 0;
10251   }
10252 
10253   if (!AM.Scale) {
10254     int64_t Offset = AM.BaseOffs;
10255 
10256     // 9-bit signed offset
10257     if (isInt<9>(Offset))
10258       return true;
10259 
10260     // 12-bit unsigned offset
10261     unsigned shift = Log2_64(NumBytes);
10262     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
10263         // Must be a multiple of NumBytes (NumBytes is a power of 2)
10264         (Offset >> shift) << shift == Offset)
10265       return true;
10266     return false;
10267   }
10268 
10269   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
10270 
10271   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
10272 }
10273 
10274 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
10275   // Consider splitting large offset of struct or array.
10276   return true;
10277 }
10278 
10279 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
10280                                                 const AddrMode &AM, Type *Ty,
10281                                                 unsigned AS) const {
10282   // Scaling factors are not free at all.
10283   // Operands                     | Rt Latency
10284   // -------------------------------------------
10285   // Rt, [Xn, Xm]                 | 4
10286   // -------------------------------------------
10287   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
10288   // Rt, [Xn, Wm, <extend> #imm]  |
10289   if (isLegalAddressingMode(DL, AM, Ty, AS))
10290     // Scale represents reg2 * scale, thus account for 1 if
10291     // it is not equal to 0 or 1.
10292     return AM.Scale != 0 && AM.Scale != 1;
10293   return -1;
10294 }
10295 
10296 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
10297     const MachineFunction &MF, EVT VT) const {
10298   VT = VT.getScalarType();
10299 
10300   if (!VT.isSimple())
10301     return false;
10302 
10303   switch (VT.getSimpleVT().SimpleTy) {
10304   case MVT::f32:
10305   case MVT::f64:
10306     return true;
10307   default:
10308     break;
10309   }
10310 
10311   return false;
10312 }
10313 
10314 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
10315                                                        Type *Ty) const {
10316   switch (Ty->getScalarType()->getTypeID()) {
10317   case Type::FloatTyID:
10318   case Type::DoubleTyID:
10319     return true;
10320   default:
10321     return false;
10322   }
10323 }
10324 
10325 const MCPhysReg *
10326 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
10327   // LR is a callee-save register, but we must treat it as clobbered by any call
10328   // site. Hence we include LR in the scratch registers, which are in turn added
10329   // as implicit-defs for stackmaps and patchpoints.
10330   static const MCPhysReg ScratchRegs[] = {
10331     AArch64::X16, AArch64::X17, AArch64::LR, 0
10332   };
10333   return ScratchRegs;
10334 }
10335 
10336 bool
10337 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10338                                                      CombineLevel Level) const {
10339   N = N->getOperand(0).getNode();
10340   EVT VT = N->getValueType(0);
10341     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
10342     // it with shift to let it be lowered to UBFX.
10343   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
10344       isa<ConstantSDNode>(N->getOperand(1))) {
10345     uint64_t TruncMask = N->getConstantOperandVal(1);
10346     if (isMask_64(TruncMask) &&
10347       N->getOperand(0).getOpcode() == ISD::SRL &&
10348       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
10349       return false;
10350   }
10351   return true;
10352 }
10353 
10354 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10355                                                               Type *Ty) const {
10356   assert(Ty->isIntegerTy());
10357 
10358   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10359   if (BitSize == 0)
10360     return false;
10361 
10362   int64_t Val = Imm.getSExtValue();
10363   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
10364     return true;
10365 
10366   if ((int64_t)Val < 0)
10367     Val = ~Val;
10368   if (BitSize == 32)
10369     Val &= (1LL << 32) - 1;
10370 
10371   unsigned LZ = countLeadingZeros((uint64_t)Val);
10372   unsigned Shift = (63 - LZ) / 16;
10373   // MOVZ is free so return true for one or fewer MOVK.
10374   return Shift < 3;
10375 }
10376 
10377 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
10378                                                     unsigned Index) const {
10379   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
10380     return false;
10381 
10382   return (Index == 0 || Index == ResVT.getVectorNumElements());
10383 }
10384 
10385 /// Turn vector tests of the signbit in the form of:
10386 ///   xor (sra X, elt_size(X)-1), -1
10387 /// into:
10388 ///   cmge X, X, #0
10389 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
10390                                          const AArch64Subtarget *Subtarget) {
10391   EVT VT = N->getValueType(0);
10392   if (!Subtarget->hasNEON() || !VT.isVector())
10393     return SDValue();
10394 
10395   // There must be a shift right algebraic before the xor, and the xor must be a
10396   // 'not' operation.
10397   SDValue Shift = N->getOperand(0);
10398   SDValue Ones = N->getOperand(1);
10399   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
10400       !ISD::isBuildVectorAllOnes(Ones.getNode()))
10401     return SDValue();
10402 
10403   // The shift should be smearing the sign bit across each vector element.
10404   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10405   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
10406   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
10407     return SDValue();
10408 
10409   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
10410 }
10411 
10412 // Generate SUBS and CSEL for integer abs.
10413 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
10414   EVT VT = N->getValueType(0);
10415 
10416   SDValue N0 = N->getOperand(0);
10417   SDValue N1 = N->getOperand(1);
10418   SDLoc DL(N);
10419 
10420   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
10421   // and change it to SUB and CSEL.
10422   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
10423       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
10424       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
10425     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
10426       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
10427         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
10428                                   N0.getOperand(0));
10429         // Generate SUBS & CSEL.
10430         SDValue Cmp =
10431             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
10432                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
10433         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
10434                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
10435                            SDValue(Cmp.getNode(), 1));
10436       }
10437   return SDValue();
10438 }
10439 
10440 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
10441                                  TargetLowering::DAGCombinerInfo &DCI,
10442                                  const AArch64Subtarget *Subtarget) {
10443   if (DCI.isBeforeLegalizeOps())
10444     return SDValue();
10445 
10446   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
10447     return Cmp;
10448 
10449   return performIntegerAbsCombine(N, DAG);
10450 }
10451 
10452 SDValue
10453 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10454                                      SelectionDAG &DAG,
10455                                      SmallVectorImpl<SDNode *> &Created) const {
10456   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10457   if (isIntDivCheap(N->getValueType(0), Attr))
10458     return SDValue(N,0); // Lower SDIV as SDIV
10459 
10460   // fold (sdiv X, pow2)
10461   EVT VT = N->getValueType(0);
10462   if ((VT != MVT::i32 && VT != MVT::i64) ||
10463       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10464     return SDValue();
10465 
10466   SDLoc DL(N);
10467   SDValue N0 = N->getOperand(0);
10468   unsigned Lg2 = Divisor.countTrailingZeros();
10469   SDValue Zero = DAG.getConstant(0, DL, VT);
10470   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10471 
10472   // Add (N0 < 0) ? Pow2 - 1 : 0;
10473   SDValue CCVal;
10474   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
10475   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10476   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
10477 
10478   Created.push_back(Cmp.getNode());
10479   Created.push_back(Add.getNode());
10480   Created.push_back(CSel.getNode());
10481 
10482   // Divide by pow2.
10483   SDValue SRA =
10484       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
10485 
10486   // If we're dividing by a positive value, we're done.  Otherwise, we must
10487   // negate the result.
10488   if (Divisor.isNonNegative())
10489     return SRA;
10490 
10491   Created.push_back(SRA.getNode());
10492   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10493 }
10494 
10495 static bool IsSVECntIntrinsic(SDValue S) {
10496   switch(getIntrinsicID(S.getNode())) {
10497   default:
10498     break;
10499   case Intrinsic::aarch64_sve_cntb:
10500   case Intrinsic::aarch64_sve_cnth:
10501   case Intrinsic::aarch64_sve_cntw:
10502   case Intrinsic::aarch64_sve_cntd:
10503     return true;
10504   }
10505   return false;
10506 }
10507 
10508 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
10509                                  TargetLowering::DAGCombinerInfo &DCI,
10510                                  const AArch64Subtarget *Subtarget) {
10511   if (DCI.isBeforeLegalizeOps())
10512     return SDValue();
10513 
10514   // The below optimizations require a constant RHS.
10515   if (!isa<ConstantSDNode>(N->getOperand(1)))
10516     return SDValue();
10517 
10518   SDValue N0 = N->getOperand(0);
10519   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
10520   const APInt &ConstValue = C->getAPIntValue();
10521 
10522   // Allow the scaling to be folded into the `cnt` instruction by preventing
10523   // the scaling to be obscured here. This makes it easier to pattern match.
10524   if (IsSVECntIntrinsic(N0) ||
10525      (N0->getOpcode() == ISD::TRUNCATE &&
10526       (IsSVECntIntrinsic(N0->getOperand(0)))))
10527        if (ConstValue.sge(1) && ConstValue.sle(16))
10528          return SDValue();
10529 
10530   // Multiplication of a power of two plus/minus one can be done more
10531   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
10532   // future CPUs have a cheaper MADD instruction, this may need to be
10533   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
10534   // 64-bit is 5 cycles, so this is always a win.
10535   // More aggressively, some multiplications N0 * C can be lowered to
10536   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
10537   // e.g. 6=3*2=(2+1)*2.
10538   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
10539   // which equals to (1+2)*16-(1+2).
10540   // TrailingZeroes is used to test if the mul can be lowered to
10541   // shift+add+shift.
10542   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
10543   if (TrailingZeroes) {
10544     // Conservatively do not lower to shift+add+shift if the mul might be
10545     // folded into smul or umul.
10546     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
10547                             isZeroExtended(N0.getNode(), DAG)))
10548       return SDValue();
10549     // Conservatively do not lower to shift+add+shift if the mul might be
10550     // folded into madd or msub.
10551     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
10552                            N->use_begin()->getOpcode() == ISD::SUB))
10553       return SDValue();
10554   }
10555   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
10556   // and shift+add+shift.
10557   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
10558 
10559   unsigned ShiftAmt, AddSubOpc;
10560   // Is the shifted value the LHS operand of the add/sub?
10561   bool ShiftValUseIsN0 = true;
10562   // Do we need to negate the result?
10563   bool NegateResult = false;
10564 
10565   if (ConstValue.isNonNegative()) {
10566     // (mul x, 2^N + 1) => (add (shl x, N), x)
10567     // (mul x, 2^N - 1) => (sub (shl x, N), x)
10568     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
10569     APInt SCVMinus1 = ShiftedConstValue - 1;
10570     APInt CVPlus1 = ConstValue + 1;
10571     if (SCVMinus1.isPowerOf2()) {
10572       ShiftAmt = SCVMinus1.logBase2();
10573       AddSubOpc = ISD::ADD;
10574     } else if (CVPlus1.isPowerOf2()) {
10575       ShiftAmt = CVPlus1.logBase2();
10576       AddSubOpc = ISD::SUB;
10577     } else
10578       return SDValue();
10579   } else {
10580     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10581     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10582     APInt CVNegPlus1 = -ConstValue + 1;
10583     APInt CVNegMinus1 = -ConstValue - 1;
10584     if (CVNegPlus1.isPowerOf2()) {
10585       ShiftAmt = CVNegPlus1.logBase2();
10586       AddSubOpc = ISD::SUB;
10587       ShiftValUseIsN0 = false;
10588     } else if (CVNegMinus1.isPowerOf2()) {
10589       ShiftAmt = CVNegMinus1.logBase2();
10590       AddSubOpc = ISD::ADD;
10591       NegateResult = true;
10592     } else
10593       return SDValue();
10594   }
10595 
10596   SDLoc DL(N);
10597   EVT VT = N->getValueType(0);
10598   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
10599                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
10600 
10601   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
10602   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
10603   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
10604   assert(!(NegateResult && TrailingZeroes) &&
10605          "NegateResult and TrailingZeroes cannot both be true for now.");
10606   // Negate the result.
10607   if (NegateResult)
10608     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
10609   // Shift the result.
10610   if (TrailingZeroes)
10611     return DAG.getNode(ISD::SHL, DL, VT, Res,
10612                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
10613   return Res;
10614 }
10615 
10616 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
10617                                                          SelectionDAG &DAG) {
10618   // Take advantage of vector comparisons producing 0 or -1 in each lane to
10619   // optimize away operation when it's from a constant.
10620   //
10621   // The general transformation is:
10622   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
10623   //       AND(VECTOR_CMP(x,y), constant2)
10624   //    constant2 = UNARYOP(constant)
10625 
10626   // Early exit if this isn't a vector operation, the operand of the
10627   // unary operation isn't a bitwise AND, or if the sizes of the operations
10628   // aren't the same.
10629   EVT VT = N->getValueType(0);
10630   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
10631       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
10632       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
10633     return SDValue();
10634 
10635   // Now check that the other operand of the AND is a constant. We could
10636   // make the transformation for non-constant splats as well, but it's unclear
10637   // that would be a benefit as it would not eliminate any operations, just
10638   // perform one more step in scalar code before moving to the vector unit.
10639   if (BuildVectorSDNode *BV =
10640           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
10641     // Bail out if the vector isn't a constant.
10642     if (!BV->isConstant())
10643       return SDValue();
10644 
10645     // Everything checks out. Build up the new and improved node.
10646     SDLoc DL(N);
10647     EVT IntVT = BV->getValueType(0);
10648     // Create a new constant of the appropriate type for the transformed
10649     // DAG.
10650     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
10651     // The AND node needs bitcasts to/from an integer vector type around it.
10652     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
10653     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
10654                                  N->getOperand(0)->getOperand(0), MaskConst);
10655     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
10656     return Res;
10657   }
10658 
10659   return SDValue();
10660 }
10661 
10662 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
10663                                      const AArch64Subtarget *Subtarget) {
10664   // First try to optimize away the conversion when it's conditionally from
10665   // a constant. Vectors only.
10666   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
10667     return Res;
10668 
10669   EVT VT = N->getValueType(0);
10670   if (VT != MVT::f32 && VT != MVT::f64)
10671     return SDValue();
10672 
10673   // Only optimize when the source and destination types have the same width.
10674   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
10675     return SDValue();
10676 
10677   // If the result of an integer load is only used by an integer-to-float
10678   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
10679   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
10680   SDValue N0 = N->getOperand(0);
10681   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10682       // Do not change the width of a volatile load.
10683       !cast<LoadSDNode>(N0)->isVolatile()) {
10684     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10685     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10686                                LN0->getPointerInfo(), LN0->getAlignment(),
10687                                LN0->getMemOperand()->getFlags());
10688 
10689     // Make sure successors of the original load stay after it by updating them
10690     // to use the new Chain.
10691     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
10692 
10693     unsigned Opcode =
10694         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
10695     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
10696   }
10697 
10698   return SDValue();
10699 }
10700 
10701 /// Fold a floating-point multiply by power of two into floating-point to
10702 /// fixed-point conversion.
10703 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
10704                                      TargetLowering::DAGCombinerInfo &DCI,
10705                                      const AArch64Subtarget *Subtarget) {
10706   if (!Subtarget->hasNEON())
10707     return SDValue();
10708 
10709   if (!N->getValueType(0).isSimple())
10710     return SDValue();
10711 
10712   SDValue Op = N->getOperand(0);
10713   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10714       Op.getOpcode() != ISD::FMUL)
10715     return SDValue();
10716 
10717   SDValue ConstVec = Op->getOperand(1);
10718   if (!isa<BuildVectorSDNode>(ConstVec))
10719     return SDValue();
10720 
10721   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10722   uint32_t FloatBits = FloatTy.getSizeInBits();
10723   if (FloatBits != 32 && FloatBits != 64)
10724     return SDValue();
10725 
10726   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10727   uint32_t IntBits = IntTy.getSizeInBits();
10728   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10729     return SDValue();
10730 
10731   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10732   if (IntBits > FloatBits)
10733     return SDValue();
10734 
10735   BitVector UndefElements;
10736   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10737   int32_t Bits = IntBits == 64 ? 64 : 32;
10738   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10739   if (C == -1 || C == 0 || C > Bits)
10740     return SDValue();
10741 
10742   MVT ResTy;
10743   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10744   switch (NumLanes) {
10745   default:
10746     return SDValue();
10747   case 2:
10748     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10749     break;
10750   case 4:
10751     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10752     break;
10753   }
10754 
10755   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10756     return SDValue();
10757 
10758   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10759          "Illegal vector type after legalization");
10760 
10761   SDLoc DL(N);
10762   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10763   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10764                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
10765   SDValue FixConv =
10766       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10767                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10768                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10769   // We can handle smaller integers by generating an extra trunc.
10770   if (IntBits < FloatBits)
10771     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10772 
10773   return FixConv;
10774 }
10775 
10776 /// Fold a floating-point divide by power of two into fixed-point to
10777 /// floating-point conversion.
10778 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10779                                   TargetLowering::DAGCombinerInfo &DCI,
10780                                   const AArch64Subtarget *Subtarget) {
10781   if (!Subtarget->hasNEON())
10782     return SDValue();
10783 
10784   SDValue Op = N->getOperand(0);
10785   unsigned Opc = Op->getOpcode();
10786   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10787       !Op.getOperand(0).getValueType().isSimple() ||
10788       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10789     return SDValue();
10790 
10791   SDValue ConstVec = N->getOperand(1);
10792   if (!isa<BuildVectorSDNode>(ConstVec))
10793     return SDValue();
10794 
10795   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10796   int32_t IntBits = IntTy.getSizeInBits();
10797   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10798     return SDValue();
10799 
10800   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10801   int32_t FloatBits = FloatTy.getSizeInBits();
10802   if (FloatBits != 32 && FloatBits != 64)
10803     return SDValue();
10804 
10805   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10806   if (IntBits > FloatBits)
10807     return SDValue();
10808 
10809   BitVector UndefElements;
10810   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10811   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10812   if (C == -1 || C == 0 || C > FloatBits)
10813     return SDValue();
10814 
10815   MVT ResTy;
10816   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10817   switch (NumLanes) {
10818   default:
10819     return SDValue();
10820   case 2:
10821     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10822     break;
10823   case 4:
10824     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10825     break;
10826   }
10827 
10828   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10829     return SDValue();
10830 
10831   SDLoc DL(N);
10832   SDValue ConvInput = Op.getOperand(0);
10833   bool IsSigned = Opc == ISD::SINT_TO_FP;
10834   if (IntBits < FloatBits)
10835     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10836                             ResTy, ConvInput);
10837 
10838   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10839                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10840   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10841                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10842                      DAG.getConstant(C, DL, MVT::i32));
10843 }
10844 
10845 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10846 /// searches for and classifies those shifts.
10847 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10848                          bool &FromHi) {
10849   if (N.getOpcode() == ISD::SHL)
10850     FromHi = false;
10851   else if (N.getOpcode() == ISD::SRL)
10852     FromHi = true;
10853   else
10854     return false;
10855 
10856   if (!isa<ConstantSDNode>(N.getOperand(1)))
10857     return false;
10858 
10859   ShiftAmount = N->getConstantOperandVal(1);
10860   Src = N->getOperand(0);
10861   return true;
10862 }
10863 
10864 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10865 /// registers viewed as a high/low pair. This function looks for the pattern:
10866 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10867 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10868 /// aren't independent.
10869 static SDValue tryCombineToEXTR(SDNode *N,
10870                                 TargetLowering::DAGCombinerInfo &DCI) {
10871   SelectionDAG &DAG = DCI.DAG;
10872   SDLoc DL(N);
10873   EVT VT = N->getValueType(0);
10874 
10875   assert(N->getOpcode() == ISD::OR && "Unexpected root");
10876 
10877   if (VT != MVT::i32 && VT != MVT::i64)
10878     return SDValue();
10879 
10880   SDValue LHS;
10881   uint32_t ShiftLHS = 0;
10882   bool LHSFromHi = false;
10883   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10884     return SDValue();
10885 
10886   SDValue RHS;
10887   uint32_t ShiftRHS = 0;
10888   bool RHSFromHi = false;
10889   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10890     return SDValue();
10891 
10892   // If they're both trying to come from the high part of the register, they're
10893   // not really an EXTR.
10894   if (LHSFromHi == RHSFromHi)
10895     return SDValue();
10896 
10897   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10898     return SDValue();
10899 
10900   if (LHSFromHi) {
10901     std::swap(LHS, RHS);
10902     std::swap(ShiftLHS, ShiftRHS);
10903   }
10904 
10905   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10906                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
10907 }
10908 
10909 static SDValue tryCombineToBSL(SDNode *N,
10910                                 TargetLowering::DAGCombinerInfo &DCI) {
10911   EVT VT = N->getValueType(0);
10912   SelectionDAG &DAG = DCI.DAG;
10913   SDLoc DL(N);
10914 
10915   if (!VT.isVector())
10916     return SDValue();
10917 
10918   SDValue N0 = N->getOperand(0);
10919   if (N0.getOpcode() != ISD::AND)
10920     return SDValue();
10921 
10922   SDValue N1 = N->getOperand(1);
10923   if (N1.getOpcode() != ISD::AND)
10924     return SDValue();
10925 
10926   // We only have to look for constant vectors here since the general, variable
10927   // case can be handled in TableGen.
10928   unsigned Bits = VT.getScalarSizeInBits();
10929   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10930   for (int i = 1; i >= 0; --i)
10931     for (int j = 1; j >= 0; --j) {
10932       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10933       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10934       if (!BVN0 || !BVN1)
10935         continue;
10936 
10937       bool FoundMatch = true;
10938       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10939         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10940         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10941         if (!CN0 || !CN1 ||
10942             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10943           FoundMatch = false;
10944           break;
10945         }
10946       }
10947 
10948       if (FoundMatch)
10949         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
10950                            N0->getOperand(1 - i), N1->getOperand(1 - j));
10951     }
10952 
10953   return SDValue();
10954 }
10955 
10956 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10957                                 const AArch64Subtarget *Subtarget) {
10958   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10959   SelectionDAG &DAG = DCI.DAG;
10960   EVT VT = N->getValueType(0);
10961 
10962   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10963     return SDValue();
10964 
10965   if (SDValue Res = tryCombineToEXTR(N, DCI))
10966     return Res;
10967 
10968   if (SDValue Res = tryCombineToBSL(N, DCI))
10969     return Res;
10970 
10971   return SDValue();
10972 }
10973 
10974 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10975   if (!MemVT.getVectorElementType().isSimple())
10976     return false;
10977 
10978   uint64_t MaskForTy = 0ull;
10979   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10980   case MVT::i8:
10981     MaskForTy = 0xffull;
10982     break;
10983   case MVT::i16:
10984     MaskForTy = 0xffffull;
10985     break;
10986   case MVT::i32:
10987     MaskForTy = 0xffffffffull;
10988     break;
10989   default:
10990     return false;
10991     break;
10992   }
10993 
10994   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10995     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10996       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10997 
10998   return false;
10999 }
11000 
11001 static SDValue performSVEAndCombine(SDNode *N,
11002                                     TargetLowering::DAGCombinerInfo &DCI) {
11003   if (DCI.isBeforeLegalizeOps())
11004     return SDValue();
11005 
11006   SelectionDAG &DAG = DCI.DAG;
11007   SDValue Src = N->getOperand(0);
11008   unsigned Opc = Src->getOpcode();
11009 
11010   // Zero/any extend of an unsigned unpack
11011   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
11012     SDValue UnpkOp = Src->getOperand(0);
11013     SDValue Dup = N->getOperand(1);
11014 
11015     if (Dup.getOpcode() != AArch64ISD::DUP)
11016       return SDValue();
11017 
11018     SDLoc DL(N);
11019     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
11020     uint64_t ExtVal = C->getZExtValue();
11021 
11022     // If the mask is fully covered by the unpack, we don't need to push
11023     // a new AND onto the operand
11024     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
11025     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
11026         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
11027         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
11028       return Src;
11029 
11030     // Truncate to prevent a DUP with an over wide constant
11031     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11032 
11033     // Otherwise, make sure we propagate the AND to the operand
11034     // of the unpack
11035     Dup = DAG.getNode(AArch64ISD::DUP, DL,
11036                       UnpkOp->getValueType(0),
11037                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11038 
11039     SDValue And = DAG.getNode(ISD::AND, DL,
11040                               UnpkOp->getValueType(0), UnpkOp, Dup);
11041 
11042     return DAG.getNode(Opc, DL, N->getValueType(0), And);
11043   }
11044 
11045   SDValue Mask = N->getOperand(1);
11046 
11047   if (!Src.hasOneUse())
11048     return SDValue();
11049 
11050   EVT MemVT;
11051 
11052   // SVE load instructions perform an implicit zero-extend, which makes them
11053   // perfect candidates for combining.
11054   switch (Opc) {
11055   case AArch64ISD::LD1_MERGE_ZERO:
11056   case AArch64ISD::LDNF1_MERGE_ZERO:
11057   case AArch64ISD::LDFF1_MERGE_ZERO:
11058     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11059     break;
11060   case AArch64ISD::GLD1_MERGE_ZERO:
11061   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11062   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11063   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11064   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11065   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11066   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11067   case AArch64ISD::GLDFF1_MERGE_ZERO:
11068   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11069   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11070   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11071   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11072   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11073   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11074   case AArch64ISD::GLDNT1_MERGE_ZERO:
11075     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11076     break;
11077   default:
11078     return SDValue();
11079   }
11080 
11081   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11082     return Src;
11083 
11084   return SDValue();
11085 }
11086 
11087 static SDValue performANDCombine(SDNode *N,
11088                                  TargetLowering::DAGCombinerInfo &DCI) {
11089   SelectionDAG &DAG = DCI.DAG;
11090   SDValue LHS = N->getOperand(0);
11091   EVT VT = N->getValueType(0);
11092   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11093     return SDValue();
11094 
11095   if (VT.isScalableVector())
11096     return performSVEAndCombine(N, DCI);
11097 
11098   BuildVectorSDNode *BVN =
11099       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11100   if (!BVN)
11101     return SDValue();
11102 
11103   // AND does not accept an immediate, so check if we can use a BIC immediate
11104   // instruction instead. We do this here instead of using a (and x, (mvni imm))
11105   // pattern in isel, because some immediates may be lowered to the preferred
11106   // (and x, (movi imm)) form, even though an mvni representation also exists.
11107   APInt DefBits(VT.getSizeInBits(), 0);
11108   APInt UndefBits(VT.getSizeInBits(), 0);
11109   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11110     SDValue NewOp;
11111 
11112     DefBits = ~DefBits;
11113     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11114                                     DefBits, &LHS)) ||
11115         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11116                                     DefBits, &LHS)))
11117       return NewOp;
11118 
11119     UndefBits = ~UndefBits;
11120     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11121                                     UndefBits, &LHS)) ||
11122         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11123                                     UndefBits, &LHS)))
11124       return NewOp;
11125   }
11126 
11127   return SDValue();
11128 }
11129 
11130 static SDValue performSRLCombine(SDNode *N,
11131                                  TargetLowering::DAGCombinerInfo &DCI) {
11132   SelectionDAG &DAG = DCI.DAG;
11133   EVT VT = N->getValueType(0);
11134   if (VT != MVT::i32 && VT != MVT::i64)
11135     return SDValue();
11136 
11137   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
11138   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
11139   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
11140   SDValue N0 = N->getOperand(0);
11141   if (N0.getOpcode() == ISD::BSWAP) {
11142     SDLoc DL(N);
11143     SDValue N1 = N->getOperand(1);
11144     SDValue N00 = N0.getOperand(0);
11145     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11146       uint64_t ShiftAmt = C->getZExtValue();
11147       if (VT == MVT::i32 && ShiftAmt == 16 &&
11148           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
11149         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11150       if (VT == MVT::i64 && ShiftAmt == 32 &&
11151           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
11152         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11153     }
11154   }
11155   return SDValue();
11156 }
11157 
11158 static SDValue performConcatVectorsCombine(SDNode *N,
11159                                            TargetLowering::DAGCombinerInfo &DCI,
11160                                            SelectionDAG &DAG) {
11161   SDLoc dl(N);
11162   EVT VT = N->getValueType(0);
11163   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11164   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
11165 
11166   // Optimize concat_vectors of truncated vectors, where the intermediate
11167   // type is illegal, to avoid said illegality,  e.g.,
11168   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
11169   //                          (v2i16 (truncate (v2i64)))))
11170   // ->
11171   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
11172   //                                    (v4i32 (bitcast (v2i64))),
11173   //                                    <0, 2, 4, 6>)))
11174   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
11175   // on both input and result type, so we might generate worse code.
11176   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
11177   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
11178       N1Opc == ISD::TRUNCATE) {
11179     SDValue N00 = N0->getOperand(0);
11180     SDValue N10 = N1->getOperand(0);
11181     EVT N00VT = N00.getValueType();
11182 
11183     if (N00VT == N10.getValueType() &&
11184         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
11185         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
11186       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
11187       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
11188       for (size_t i = 0; i < Mask.size(); ++i)
11189         Mask[i] = i * 2;
11190       return DAG.getNode(ISD::TRUNCATE, dl, VT,
11191                          DAG.getVectorShuffle(
11192                              MidVT, dl,
11193                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
11194                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
11195     }
11196   }
11197 
11198   // Wait 'til after everything is legalized to try this. That way we have
11199   // legal vector types and such.
11200   if (DCI.isBeforeLegalizeOps())
11201     return SDValue();
11202 
11203   // Optimise concat_vectors of two [us]rhadds that use extracted subvectors
11204   // from the same original vectors. Combine these into a single [us]rhadd that
11205   // operates on the two original vectors. Example:
11206   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
11207   //                                        extract_subvector (v16i8 OpB,
11208   //                                        <0>))),
11209   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
11210   //                                        extract_subvector (v16i8 OpB,
11211   //                                        <8>)))))
11212   // ->
11213   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
11214   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
11215       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD)) {
11216     SDValue N00 = N0->getOperand(0);
11217     SDValue N01 = N0->getOperand(1);
11218     SDValue N10 = N1->getOperand(0);
11219     SDValue N11 = N1->getOperand(1);
11220 
11221     EVT N00VT = N00.getValueType();
11222     EVT N10VT = N10.getValueType();
11223 
11224     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11225         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11226         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11227         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
11228       SDValue N00Source = N00->getOperand(0);
11229       SDValue N01Source = N01->getOperand(0);
11230       SDValue N10Source = N10->getOperand(0);
11231       SDValue N11Source = N11->getOperand(0);
11232 
11233       if (N00Source == N10Source && N01Source == N11Source &&
11234           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
11235         assert(N0.getValueType() == N1.getValueType());
11236 
11237         uint64_t N00Index = N00.getConstantOperandVal(1);
11238         uint64_t N01Index = N01.getConstantOperandVal(1);
11239         uint64_t N10Index = N10.getConstantOperandVal(1);
11240         uint64_t N11Index = N11.getConstantOperandVal(1);
11241 
11242         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
11243             N10Index == N00VT.getVectorNumElements())
11244           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
11245       }
11246     }
11247   }
11248 
11249   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
11250   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
11251   // canonicalise to that.
11252   if (N0 == N1 && VT.getVectorNumElements() == 2) {
11253     assert(VT.getScalarSizeInBits() == 64);
11254     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
11255                        DAG.getConstant(0, dl, MVT::i64));
11256   }
11257 
11258   // Canonicalise concat_vectors so that the right-hand vector has as few
11259   // bit-casts as possible before its real operation. The primary matching
11260   // destination for these operations will be the narrowing "2" instructions,
11261   // which depend on the operation being performed on this right-hand vector.
11262   // For example,
11263   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
11264   // becomes
11265   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
11266 
11267   if (N1Opc != ISD::BITCAST)
11268     return SDValue();
11269   SDValue RHS = N1->getOperand(0);
11270   MVT RHSTy = RHS.getValueType().getSimpleVT();
11271   // If the RHS is not a vector, this is not the pattern we're looking for.
11272   if (!RHSTy.isVector())
11273     return SDValue();
11274 
11275   LLVM_DEBUG(
11276       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
11277 
11278   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
11279                                   RHSTy.getVectorNumElements() * 2);
11280   return DAG.getNode(ISD::BITCAST, dl, VT,
11281                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
11282                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
11283                                  RHS));
11284 }
11285 
11286 static SDValue tryCombineFixedPointConvert(SDNode *N,
11287                                            TargetLowering::DAGCombinerInfo &DCI,
11288                                            SelectionDAG &DAG) {
11289   // Wait until after everything is legalized to try this. That way we have
11290   // legal vector types and such.
11291   if (DCI.isBeforeLegalizeOps())
11292     return SDValue();
11293   // Transform a scalar conversion of a value from a lane extract into a
11294   // lane extract of a vector conversion. E.g., from foo1 to foo2:
11295   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
11296   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
11297   //
11298   // The second form interacts better with instruction selection and the
11299   // register allocator to avoid cross-class register copies that aren't
11300   // coalescable due to a lane reference.
11301 
11302   // Check the operand and see if it originates from a lane extract.
11303   SDValue Op1 = N->getOperand(1);
11304   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11305     // Yep, no additional predication needed. Perform the transform.
11306     SDValue IID = N->getOperand(0);
11307     SDValue Shift = N->getOperand(2);
11308     SDValue Vec = Op1.getOperand(0);
11309     SDValue Lane = Op1.getOperand(1);
11310     EVT ResTy = N->getValueType(0);
11311     EVT VecResTy;
11312     SDLoc DL(N);
11313 
11314     // The vector width should be 128 bits by the time we get here, even
11315     // if it started as 64 bits (the extract_vector handling will have
11316     // done so).
11317     assert(Vec.getValueSizeInBits() == 128 &&
11318            "unexpected vector size on extract_vector_elt!");
11319     if (Vec.getValueType() == MVT::v4i32)
11320       VecResTy = MVT::v4f32;
11321     else if (Vec.getValueType() == MVT::v2i64)
11322       VecResTy = MVT::v2f64;
11323     else
11324       llvm_unreachable("unexpected vector type!");
11325 
11326     SDValue Convert =
11327         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
11328     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
11329   }
11330   return SDValue();
11331 }
11332 
11333 // AArch64 high-vector "long" operations are formed by performing the non-high
11334 // version on an extract_subvector of each operand which gets the high half:
11335 //
11336 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
11337 //
11338 // However, there are cases which don't have an extract_high explicitly, but
11339 // have another operation that can be made compatible with one for free. For
11340 // example:
11341 //
11342 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
11343 //
11344 // This routine does the actual conversion of such DUPs, once outer routines
11345 // have determined that everything else is in order.
11346 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
11347 // similarly here.
11348 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
11349   switch (N.getOpcode()) {
11350   case AArch64ISD::DUP:
11351   case AArch64ISD::DUPLANE8:
11352   case AArch64ISD::DUPLANE16:
11353   case AArch64ISD::DUPLANE32:
11354   case AArch64ISD::DUPLANE64:
11355   case AArch64ISD::MOVI:
11356   case AArch64ISD::MOVIshift:
11357   case AArch64ISD::MOVIedit:
11358   case AArch64ISD::MOVImsl:
11359   case AArch64ISD::MVNIshift:
11360   case AArch64ISD::MVNImsl:
11361     break;
11362   default:
11363     // FMOV could be supported, but isn't very useful, as it would only occur
11364     // if you passed a bitcast' floating point immediate to an eligible long
11365     // integer op (addl, smull, ...).
11366     return SDValue();
11367   }
11368 
11369   MVT NarrowTy = N.getSimpleValueType();
11370   if (!NarrowTy.is64BitVector())
11371     return SDValue();
11372 
11373   MVT ElementTy = NarrowTy.getVectorElementType();
11374   unsigned NumElems = NarrowTy.getVectorNumElements();
11375   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
11376 
11377   SDLoc dl(N);
11378   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
11379                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
11380                      DAG.getConstant(NumElems, dl, MVT::i64));
11381 }
11382 
11383 static bool isEssentiallyExtractHighSubvector(SDValue N) {
11384   if (N.getOpcode() == ISD::BITCAST)
11385     N = N.getOperand(0);
11386   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11387     return false;
11388   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
11389          N.getOperand(0).getValueType().getVectorNumElements() / 2;
11390 }
11391 
11392 /// Helper structure to keep track of ISD::SET_CC operands.
11393 struct GenericSetCCInfo {
11394   const SDValue *Opnd0;
11395   const SDValue *Opnd1;
11396   ISD::CondCode CC;
11397 };
11398 
11399 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
11400 struct AArch64SetCCInfo {
11401   const SDValue *Cmp;
11402   AArch64CC::CondCode CC;
11403 };
11404 
11405 /// Helper structure to keep track of SetCC information.
11406 union SetCCInfo {
11407   GenericSetCCInfo Generic;
11408   AArch64SetCCInfo AArch64;
11409 };
11410 
11411 /// Helper structure to be able to read SetCC information.  If set to
11412 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
11413 /// GenericSetCCInfo.
11414 struct SetCCInfoAndKind {
11415   SetCCInfo Info;
11416   bool IsAArch64;
11417 };
11418 
11419 /// Check whether or not \p Op is a SET_CC operation, either a generic or
11420 /// an
11421 /// AArch64 lowered one.
11422 /// \p SetCCInfo is filled accordingly.
11423 /// \post SetCCInfo is meanginfull only when this function returns true.
11424 /// \return True when Op is a kind of SET_CC operation.
11425 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
11426   // If this is a setcc, this is straight forward.
11427   if (Op.getOpcode() == ISD::SETCC) {
11428     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
11429     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
11430     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11431     SetCCInfo.IsAArch64 = false;
11432     return true;
11433   }
11434   // Otherwise, check if this is a matching csel instruction.
11435   // In other words:
11436   // - csel 1, 0, cc
11437   // - csel 0, 1, !cc
11438   if (Op.getOpcode() != AArch64ISD::CSEL)
11439     return false;
11440   // Set the information about the operands.
11441   // TODO: we want the operands of the Cmp not the csel
11442   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
11443   SetCCInfo.IsAArch64 = true;
11444   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
11445       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11446 
11447   // Check that the operands matches the constraints:
11448   // (1) Both operands must be constants.
11449   // (2) One must be 1 and the other must be 0.
11450   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
11451   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11452 
11453   // Check (1).
11454   if (!TValue || !FValue)
11455     return false;
11456 
11457   // Check (2).
11458   if (!TValue->isOne()) {
11459     // Update the comparison when we are interested in !cc.
11460     std::swap(TValue, FValue);
11461     SetCCInfo.Info.AArch64.CC =
11462         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
11463   }
11464   return TValue->isOne() && FValue->isNullValue();
11465 }
11466 
11467 // Returns true if Op is setcc or zext of setcc.
11468 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
11469   if (isSetCC(Op, Info))
11470     return true;
11471   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
11472     isSetCC(Op->getOperand(0), Info));
11473 }
11474 
11475 // The folding we want to perform is:
11476 // (add x, [zext] (setcc cc ...) )
11477 //   -->
11478 // (csel x, (add x, 1), !cc ...)
11479 //
11480 // The latter will get matched to a CSINC instruction.
11481 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
11482   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
11483   SDValue LHS = Op->getOperand(0);
11484   SDValue RHS = Op->getOperand(1);
11485   SetCCInfoAndKind InfoAndKind;
11486 
11487   // If neither operand is a SET_CC, give up.
11488   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
11489     std::swap(LHS, RHS);
11490     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
11491       return SDValue();
11492   }
11493 
11494   // FIXME: This could be generatized to work for FP comparisons.
11495   EVT CmpVT = InfoAndKind.IsAArch64
11496                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
11497                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
11498   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
11499     return SDValue();
11500 
11501   SDValue CCVal;
11502   SDValue Cmp;
11503   SDLoc dl(Op);
11504   if (InfoAndKind.IsAArch64) {
11505     CCVal = DAG.getConstant(
11506         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
11507         MVT::i32);
11508     Cmp = *InfoAndKind.Info.AArch64.Cmp;
11509   } else
11510     Cmp = getAArch64Cmp(
11511         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
11512         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
11513         dl);
11514 
11515   EVT VT = Op->getValueType(0);
11516   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
11517   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
11518 }
11519 
11520 // The basic add/sub long vector instructions have variants with "2" on the end
11521 // which act on the high-half of their inputs. They are normally matched by
11522 // patterns like:
11523 //
11524 // (add (zeroext (extract_high LHS)),
11525 //      (zeroext (extract_high RHS)))
11526 // -> uaddl2 vD, vN, vM
11527 //
11528 // However, if one of the extracts is something like a duplicate, this
11529 // instruction can still be used profitably. This function puts the DAG into a
11530 // more appropriate form for those patterns to trigger.
11531 static SDValue performAddSubLongCombine(SDNode *N,
11532                                         TargetLowering::DAGCombinerInfo &DCI,
11533                                         SelectionDAG &DAG) {
11534   if (DCI.isBeforeLegalizeOps())
11535     return SDValue();
11536 
11537   MVT VT = N->getSimpleValueType(0);
11538   if (!VT.is128BitVector()) {
11539     if (N->getOpcode() == ISD::ADD)
11540       return performSetccAddFolding(N, DAG);
11541     return SDValue();
11542   }
11543 
11544   // Make sure both branches are extended in the same way.
11545   SDValue LHS = N->getOperand(0);
11546   SDValue RHS = N->getOperand(1);
11547   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
11548        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
11549       LHS.getOpcode() != RHS.getOpcode())
11550     return SDValue();
11551 
11552   unsigned ExtType = LHS.getOpcode();
11553 
11554   // It's not worth doing if at least one of the inputs isn't already an
11555   // extract, but we don't know which it'll be so we have to try both.
11556   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
11557     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
11558     if (!RHS.getNode())
11559       return SDValue();
11560 
11561     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
11562   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
11563     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
11564     if (!LHS.getNode())
11565       return SDValue();
11566 
11567     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
11568   }
11569 
11570   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
11571 }
11572 
11573 // Massage DAGs which we can use the high-half "long" operations on into
11574 // something isel will recognize better. E.g.
11575 //
11576 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
11577 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
11578 //                     (extract_high (v2i64 (dup128 scalar)))))
11579 //
11580 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
11581                                        TargetLowering::DAGCombinerInfo &DCI,
11582                                        SelectionDAG &DAG) {
11583   if (DCI.isBeforeLegalizeOps())
11584     return SDValue();
11585 
11586   SDValue LHS = N->getOperand(1);
11587   SDValue RHS = N->getOperand(2);
11588   assert(LHS.getValueType().is64BitVector() &&
11589          RHS.getValueType().is64BitVector() &&
11590          "unexpected shape for long operation");
11591 
11592   // Either node could be a DUP, but it's not worth doing both of them (you'd
11593   // just as well use the non-high version) so look for a corresponding extract
11594   // operation on the other "wing".
11595   if (isEssentiallyExtractHighSubvector(LHS)) {
11596     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
11597     if (!RHS.getNode())
11598       return SDValue();
11599   } else if (isEssentiallyExtractHighSubvector(RHS)) {
11600     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
11601     if (!LHS.getNode())
11602       return SDValue();
11603   }
11604 
11605   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
11606                      N->getOperand(0), LHS, RHS);
11607 }
11608 
11609 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
11610   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
11611   unsigned ElemBits = ElemTy.getSizeInBits();
11612 
11613   int64_t ShiftAmount;
11614   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
11615     APInt SplatValue, SplatUndef;
11616     unsigned SplatBitSize;
11617     bool HasAnyUndefs;
11618     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11619                               HasAnyUndefs, ElemBits) ||
11620         SplatBitSize != ElemBits)
11621       return SDValue();
11622 
11623     ShiftAmount = SplatValue.getSExtValue();
11624   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
11625     ShiftAmount = CVN->getSExtValue();
11626   } else
11627     return SDValue();
11628 
11629   unsigned Opcode;
11630   bool IsRightShift;
11631   switch (IID) {
11632   default:
11633     llvm_unreachable("Unknown shift intrinsic");
11634   case Intrinsic::aarch64_neon_sqshl:
11635     Opcode = AArch64ISD::SQSHL_I;
11636     IsRightShift = false;
11637     break;
11638   case Intrinsic::aarch64_neon_uqshl:
11639     Opcode = AArch64ISD::UQSHL_I;
11640     IsRightShift = false;
11641     break;
11642   case Intrinsic::aarch64_neon_srshl:
11643     Opcode = AArch64ISD::SRSHR_I;
11644     IsRightShift = true;
11645     break;
11646   case Intrinsic::aarch64_neon_urshl:
11647     Opcode = AArch64ISD::URSHR_I;
11648     IsRightShift = true;
11649     break;
11650   case Intrinsic::aarch64_neon_sqshlu:
11651     Opcode = AArch64ISD::SQSHLU_I;
11652     IsRightShift = false;
11653     break;
11654   case Intrinsic::aarch64_neon_sshl:
11655   case Intrinsic::aarch64_neon_ushl:
11656     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
11657     // left shift for positive shift amounts. Below, we only replace the current
11658     // node with VSHL, if this condition is met.
11659     Opcode = AArch64ISD::VSHL;
11660     IsRightShift = false;
11661     break;
11662   }
11663 
11664   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
11665     SDLoc dl(N);
11666     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11667                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
11668   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
11669     SDLoc dl(N);
11670     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11671                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
11672   }
11673 
11674   return SDValue();
11675 }
11676 
11677 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
11678 // the intrinsics must be legal and take an i32, this means there's almost
11679 // certainly going to be a zext in the DAG which we can eliminate.
11680 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
11681   SDValue AndN = N->getOperand(2);
11682   if (AndN.getOpcode() != ISD::AND)
11683     return SDValue();
11684 
11685   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
11686   if (!CMask || CMask->getZExtValue() != Mask)
11687     return SDValue();
11688 
11689   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
11690                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
11691 }
11692 
11693 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
11694                                            SelectionDAG &DAG) {
11695   SDLoc dl(N);
11696   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
11697                      DAG.getNode(Opc, dl,
11698                                  N->getOperand(1).getSimpleValueType(),
11699                                  N->getOperand(1)),
11700                      DAG.getConstant(0, dl, MVT::i64));
11701 }
11702 
11703 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
11704                                     SelectionDAG &DAG) {
11705   SDLoc dl(N);
11706   LLVMContext &Ctx = *DAG.getContext();
11707   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11708 
11709   EVT VT = N->getValueType(0);
11710   SDValue Pred = N->getOperand(1);
11711   SDValue Data = N->getOperand(2);
11712   EVT DataVT = Data.getValueType();
11713 
11714   if (DataVT.getVectorElementType().isScalarInteger() &&
11715       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
11716     if (!TLI.isTypeLegal(DataVT))
11717       return SDValue();
11718 
11719     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
11720       AArch64::NeonBitsPerVector / VT.getSizeInBits());
11721     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
11722     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
11723     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
11724 
11725     return Result;
11726   }
11727 
11728   return SDValue();
11729 }
11730 
11731 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
11732   SDLoc DL(N);
11733   SDValue Op1 = N->getOperand(1);
11734   SDValue Op2 = N->getOperand(2);
11735   EVT ScalarTy = Op1.getValueType();
11736 
11737   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
11738     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
11739     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
11740   }
11741 
11742   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
11743                      Op1, Op2);
11744 }
11745 
11746 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
11747   SDLoc dl(N);
11748   SDValue Scalar = N->getOperand(3);
11749   EVT ScalarTy = Scalar.getValueType();
11750 
11751   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
11752     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
11753 
11754   SDValue Passthru = N->getOperand(1);
11755   SDValue Pred = N->getOperand(2);
11756   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
11757                      Pred, Scalar, Passthru);
11758 }
11759 
11760 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
11761   SDLoc dl(N);
11762   LLVMContext &Ctx = *DAG.getContext();
11763   EVT VT = N->getValueType(0);
11764 
11765   assert(VT.isScalableVector() && "Expected a scalable vector.");
11766 
11767   // Current lowering only supports the SVE-ACLE types.
11768   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
11769     return SDValue();
11770 
11771   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
11772   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
11773   EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
11774 
11775   // Convert everything to the domain of EXT (i.e bytes).
11776   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
11777   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
11778   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
11779                             DAG.getConstant(ElemSize, dl, MVT::i32));
11780 
11781   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
11782   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
11783 }
11784 
11785 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
11786                                         TargetLowering::DAGCombinerInfo &DCI,
11787                                         SelectionDAG &DAG) {
11788   if (DCI.isBeforeLegalize())
11789     return SDValue();
11790 
11791   SDValue Comparator = N->getOperand(3);
11792   if (Comparator.getOpcode() == AArch64ISD::DUP ||
11793       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
11794     unsigned IID = getIntrinsicID(N);
11795     EVT VT = N->getValueType(0);
11796     EVT CmpVT = N->getOperand(2).getValueType();
11797     SDValue Pred = N->getOperand(1);
11798     SDValue Imm;
11799     SDLoc DL(N);
11800 
11801     switch (IID) {
11802     default:
11803       llvm_unreachable("Called with wrong intrinsic!");
11804       break;
11805 
11806     // Signed comparisons
11807     case Intrinsic::aarch64_sve_cmpeq_wide:
11808     case Intrinsic::aarch64_sve_cmpne_wide:
11809     case Intrinsic::aarch64_sve_cmpge_wide:
11810     case Intrinsic::aarch64_sve_cmpgt_wide:
11811     case Intrinsic::aarch64_sve_cmplt_wide:
11812     case Intrinsic::aarch64_sve_cmple_wide: {
11813       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11814         int64_t ImmVal = CN->getSExtValue();
11815         if (ImmVal >= -16 && ImmVal <= 15)
11816           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11817         else
11818           return SDValue();
11819       }
11820       break;
11821     }
11822     // Unsigned comparisons
11823     case Intrinsic::aarch64_sve_cmphs_wide:
11824     case Intrinsic::aarch64_sve_cmphi_wide:
11825     case Intrinsic::aarch64_sve_cmplo_wide:
11826     case Intrinsic::aarch64_sve_cmpls_wide:  {
11827       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11828         uint64_t ImmVal = CN->getZExtValue();
11829         if (ImmVal <= 127)
11830           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11831         else
11832           return SDValue();
11833       }
11834       break;
11835     }
11836     }
11837 
11838     if (!Imm)
11839       return SDValue();
11840 
11841     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
11842     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
11843                        N->getOperand(2), Splat, DAG.getCondCode(CC));
11844   }
11845 
11846   return SDValue();
11847 }
11848 
11849 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
11850                         AArch64CC::CondCode Cond) {
11851   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11852 
11853   SDLoc DL(Op);
11854   assert(Op.getValueType().isScalableVector() &&
11855          TLI.isTypeLegal(Op.getValueType()) &&
11856          "Expected legal scalable vector type!");
11857 
11858   // Ensure target specific opcodes are using legal type.
11859   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
11860   SDValue TVal = DAG.getConstant(1, DL, OutVT);
11861   SDValue FVal = DAG.getConstant(0, DL, OutVT);
11862 
11863   // Set condition code (CC) flags.
11864   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
11865 
11866   // Convert CC to integer based on requested condition.
11867   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
11868   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
11869   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
11870   return DAG.getZExtOrTrunc(Res, DL, VT);
11871 }
11872 
11873 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
11874                                      SelectionDAG &DAG) {
11875   SDLoc DL(N);
11876 
11877   SDValue Pred = N->getOperand(1);
11878   SDValue VecToReduce = N->getOperand(2);
11879 
11880   EVT ReduceVT = VecToReduce.getValueType();
11881   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
11882 
11883   // SVE reductions set the whole vector register with the first element
11884   // containing the reduction result, which we'll now extract.
11885   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11886   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
11887                      Zero);
11888 }
11889 
11890 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
11891                                             SelectionDAG &DAG) {
11892   SDLoc DL(N);
11893 
11894   SDValue Pred = N->getOperand(1);
11895   SDValue InitVal = N->getOperand(2);
11896   SDValue VecToReduce = N->getOperand(3);
11897   EVT ReduceVT = VecToReduce.getValueType();
11898 
11899   // Ordered reductions use the first lane of the result vector as the
11900   // reduction's initial value.
11901   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11902   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
11903                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
11904 
11905   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
11906 
11907   // SVE reductions set the whole vector register with the first element
11908   // containing the reduction result, which we'll now extract.
11909   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
11910                      Zero);
11911 }
11912 
11913 static SDValue performIntrinsicCombine(SDNode *N,
11914                                        TargetLowering::DAGCombinerInfo &DCI,
11915                                        const AArch64Subtarget *Subtarget) {
11916   SelectionDAG &DAG = DCI.DAG;
11917   unsigned IID = getIntrinsicID(N);
11918   switch (IID) {
11919   default:
11920     break;
11921   case Intrinsic::aarch64_neon_vcvtfxs2fp:
11922   case Intrinsic::aarch64_neon_vcvtfxu2fp:
11923     return tryCombineFixedPointConvert(N, DCI, DAG);
11924   case Intrinsic::aarch64_neon_saddv:
11925     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11926   case Intrinsic::aarch64_neon_uaddv:
11927     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11928   case Intrinsic::aarch64_neon_sminv:
11929     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11930   case Intrinsic::aarch64_neon_uminv:
11931     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11932   case Intrinsic::aarch64_neon_smaxv:
11933     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11934   case Intrinsic::aarch64_neon_umaxv:
11935     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11936   case Intrinsic::aarch64_neon_fmax:
11937     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11938                        N->getOperand(1), N->getOperand(2));
11939   case Intrinsic::aarch64_neon_fmin:
11940     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11941                        N->getOperand(1), N->getOperand(2));
11942   case Intrinsic::aarch64_neon_fmaxnm:
11943     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11944                        N->getOperand(1), N->getOperand(2));
11945   case Intrinsic::aarch64_neon_fminnm:
11946     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11947                        N->getOperand(1), N->getOperand(2));
11948   case Intrinsic::aarch64_neon_smull:
11949   case Intrinsic::aarch64_neon_umull:
11950   case Intrinsic::aarch64_neon_pmull:
11951   case Intrinsic::aarch64_neon_sqdmull:
11952     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11953   case Intrinsic::aarch64_neon_sqshl:
11954   case Intrinsic::aarch64_neon_uqshl:
11955   case Intrinsic::aarch64_neon_sqshlu:
11956   case Intrinsic::aarch64_neon_srshl:
11957   case Intrinsic::aarch64_neon_urshl:
11958   case Intrinsic::aarch64_neon_sshl:
11959   case Intrinsic::aarch64_neon_ushl:
11960     return tryCombineShiftImm(IID, N, DAG);
11961   case Intrinsic::aarch64_crc32b:
11962   case Intrinsic::aarch64_crc32cb:
11963     return tryCombineCRC32(0xff, N, DAG);
11964   case Intrinsic::aarch64_crc32h:
11965   case Intrinsic::aarch64_crc32ch:
11966     return tryCombineCRC32(0xffff, N, DAG);
11967   case Intrinsic::aarch64_sve_smaxv:
11968     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11969   case Intrinsic::aarch64_sve_umaxv:
11970     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11971   case Intrinsic::aarch64_sve_sminv:
11972     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11973   case Intrinsic::aarch64_sve_uminv:
11974     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11975   case Intrinsic::aarch64_sve_orv:
11976     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11977   case Intrinsic::aarch64_sve_eorv:
11978     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11979   case Intrinsic::aarch64_sve_andv:
11980     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11981   case Intrinsic::aarch64_sve_index:
11982     return LowerSVEIntrinsicIndex(N, DAG);
11983   case Intrinsic::aarch64_sve_dup:
11984     return LowerSVEIntrinsicDUP(N, DAG);
11985   case Intrinsic::aarch64_sve_dup_x:
11986     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
11987                        N->getOperand(1));
11988   case Intrinsic::aarch64_sve_ext:
11989     return LowerSVEIntrinsicEXT(N, DAG);
11990   case Intrinsic::aarch64_sve_smin:
11991     return DAG.getNode(AArch64ISD::SMIN_MERGE_OP1, SDLoc(N), N->getValueType(0),
11992                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11993   case Intrinsic::aarch64_sve_umin:
11994     return DAG.getNode(AArch64ISD::UMIN_MERGE_OP1, SDLoc(N), N->getValueType(0),
11995                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11996   case Intrinsic::aarch64_sve_smax:
11997     return DAG.getNode(AArch64ISD::SMAX_MERGE_OP1, SDLoc(N), N->getValueType(0),
11998                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11999   case Intrinsic::aarch64_sve_umax:
12000     return DAG.getNode(AArch64ISD::UMAX_MERGE_OP1, SDLoc(N), N->getValueType(0),
12001                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12002   case Intrinsic::aarch64_sve_lsl:
12003     return DAG.getNode(AArch64ISD::SHL_MERGE_OP1, SDLoc(N), N->getValueType(0),
12004                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12005   case Intrinsic::aarch64_sve_lsr:
12006     return DAG.getNode(AArch64ISD::SRL_MERGE_OP1, SDLoc(N), N->getValueType(0),
12007                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12008   case Intrinsic::aarch64_sve_asr:
12009     return DAG.getNode(AArch64ISD::SRA_MERGE_OP1, SDLoc(N), N->getValueType(0),
12010                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12011   case Intrinsic::aarch64_sve_cmphs:
12012     if (!N->getOperand(2).getValueType().isFloatingPoint())
12013       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12014                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12015                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
12016     break;
12017   case Intrinsic::aarch64_sve_cmphi:
12018     if (!N->getOperand(2).getValueType().isFloatingPoint())
12019       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12020                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12021                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
12022     break;
12023   case Intrinsic::aarch64_sve_cmpge:
12024     if (!N->getOperand(2).getValueType().isFloatingPoint())
12025       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12026                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12027                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
12028     break;
12029   case Intrinsic::aarch64_sve_cmpgt:
12030     if (!N->getOperand(2).getValueType().isFloatingPoint())
12031       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12032                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12033                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
12034     break;
12035   case Intrinsic::aarch64_sve_cmpeq:
12036     if (!N->getOperand(2).getValueType().isFloatingPoint())
12037       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12038                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12039                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
12040     break;
12041   case Intrinsic::aarch64_sve_cmpne:
12042     if (!N->getOperand(2).getValueType().isFloatingPoint())
12043       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12044                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12045                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
12046     break;
12047   case Intrinsic::aarch64_sve_fadda:
12048     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
12049   case Intrinsic::aarch64_sve_faddv:
12050     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
12051   case Intrinsic::aarch64_sve_fmaxnmv:
12052     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
12053   case Intrinsic::aarch64_sve_fmaxv:
12054     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
12055   case Intrinsic::aarch64_sve_fminnmv:
12056     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
12057   case Intrinsic::aarch64_sve_fminv:
12058     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
12059   case Intrinsic::aarch64_sve_sel:
12060     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
12061                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12062   case Intrinsic::aarch64_sve_cmpeq_wide:
12063     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
12064   case Intrinsic::aarch64_sve_cmpne_wide:
12065     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
12066   case Intrinsic::aarch64_sve_cmpge_wide:
12067     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
12068   case Intrinsic::aarch64_sve_cmpgt_wide:
12069     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
12070   case Intrinsic::aarch64_sve_cmplt_wide:
12071     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
12072   case Intrinsic::aarch64_sve_cmple_wide:
12073     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
12074   case Intrinsic::aarch64_sve_cmphs_wide:
12075     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
12076   case Intrinsic::aarch64_sve_cmphi_wide:
12077     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
12078   case Intrinsic::aarch64_sve_cmplo_wide:
12079     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
12080   case Intrinsic::aarch64_sve_cmpls_wide:
12081     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
12082   case Intrinsic::aarch64_sve_ptest_any:
12083     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12084                     AArch64CC::ANY_ACTIVE);
12085   case Intrinsic::aarch64_sve_ptest_first:
12086     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12087                     AArch64CC::FIRST_ACTIVE);
12088   case Intrinsic::aarch64_sve_ptest_last:
12089     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12090                     AArch64CC::LAST_ACTIVE);
12091   }
12092   return SDValue();
12093 }
12094 
12095 static SDValue performExtendCombine(SDNode *N,
12096                                     TargetLowering::DAGCombinerInfo &DCI,
12097                                     SelectionDAG &DAG) {
12098   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
12099   // we can convert that DUP into another extract_high (of a bigger DUP), which
12100   // helps the backend to decide that an sabdl2 would be useful, saving a real
12101   // extract_high operation.
12102   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
12103       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
12104     SDNode *ABDNode = N->getOperand(0).getNode();
12105     unsigned IID = getIntrinsicID(ABDNode);
12106     if (IID == Intrinsic::aarch64_neon_sabd ||
12107         IID == Intrinsic::aarch64_neon_uabd) {
12108       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
12109       if (!NewABD.getNode())
12110         return SDValue();
12111 
12112       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
12113                          NewABD);
12114     }
12115   }
12116 
12117   // This is effectively a custom type legalization for AArch64.
12118   //
12119   // Type legalization will split an extend of a small, legal, type to a larger
12120   // illegal type by first splitting the destination type, often creating
12121   // illegal source types, which then get legalized in isel-confusing ways,
12122   // leading to really terrible codegen. E.g.,
12123   //   %result = v8i32 sext v8i8 %value
12124   // becomes
12125   //   %losrc = extract_subreg %value, ...
12126   //   %hisrc = extract_subreg %value, ...
12127   //   %lo = v4i32 sext v4i8 %losrc
12128   //   %hi = v4i32 sext v4i8 %hisrc
12129   // Things go rapidly downhill from there.
12130   //
12131   // For AArch64, the [sz]ext vector instructions can only go up one element
12132   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
12133   // take two instructions.
12134   //
12135   // This implies that the most efficient way to do the extend from v8i8
12136   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
12137   // the normal splitting to happen for the v8i16->v8i32.
12138 
12139   // This is pre-legalization to catch some cases where the default
12140   // type legalization will create ill-tempered code.
12141   if (!DCI.isBeforeLegalizeOps())
12142     return SDValue();
12143 
12144   // We're only interested in cleaning things up for non-legal vector types
12145   // here. If both the source and destination are legal, things will just
12146   // work naturally without any fiddling.
12147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12148   EVT ResVT = N->getValueType(0);
12149   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
12150     return SDValue();
12151   // If the vector type isn't a simple VT, it's beyond the scope of what
12152   // we're  worried about here. Let legalization do its thing and hope for
12153   // the best.
12154   SDValue Src = N->getOperand(0);
12155   EVT SrcVT = Src->getValueType(0);
12156   if (!ResVT.isSimple() || !SrcVT.isSimple())
12157     return SDValue();
12158 
12159   // If the source VT is a 64-bit fixed or scalable vector, we can play games
12160   // and get the better results we want.
12161   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
12162     return SDValue();
12163 
12164   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
12165   ElementCount SrcEC = SrcVT.getVectorElementCount();
12166   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
12167   SDLoc DL(N);
12168   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
12169 
12170   // Now split the rest of the operation into two halves, each with a 64
12171   // bit source.
12172   EVT LoVT, HiVT;
12173   SDValue Lo, Hi;
12174   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
12175 
12176   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
12177                                LoVT.getVectorElementCount());
12178   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12179                    DAG.getConstant(0, DL, MVT::i64));
12180   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12181                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
12182   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
12183   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
12184 
12185   // Now combine the parts back together so we still have a single result
12186   // like the combiner expects.
12187   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
12188 }
12189 
12190 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
12191                                SDValue SplatVal, unsigned NumVecElts) {
12192   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
12193   unsigned OrigAlignment = St.getAlignment();
12194   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
12195 
12196   // Create scalar stores. This is at least as good as the code sequence for a
12197   // split unaligned store which is a dup.s, ext.b, and two stores.
12198   // Most of the time the three stores should be replaced by store pair
12199   // instructions (stp).
12200   SDLoc DL(&St);
12201   SDValue BasePtr = St.getBasePtr();
12202   uint64_t BaseOffset = 0;
12203 
12204   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
12205   SDValue NewST1 =
12206       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
12207                    OrigAlignment, St.getMemOperand()->getFlags());
12208 
12209   // As this in ISel, we will not merge this add which may degrade results.
12210   if (BasePtr->getOpcode() == ISD::ADD &&
12211       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
12212     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
12213     BasePtr = BasePtr->getOperand(0);
12214   }
12215 
12216   unsigned Offset = EltOffset;
12217   while (--NumVecElts) {
12218     unsigned Alignment = MinAlign(OrigAlignment, Offset);
12219     SDValue OffsetPtr =
12220         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12221                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
12222     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
12223                           PtrInfo.getWithOffset(Offset), Alignment,
12224                           St.getMemOperand()->getFlags());
12225     Offset += EltOffset;
12226   }
12227   return NewST1;
12228 }
12229 
12230 // Returns an SVE type that ContentTy can be trivially sign or zero extended
12231 // into.
12232 static MVT getSVEContainerType(EVT ContentTy) {
12233   assert(ContentTy.isSimple() && "No SVE containers for extended types");
12234 
12235   switch (ContentTy.getSimpleVT().SimpleTy) {
12236   default:
12237     llvm_unreachable("No known SVE container for this MVT type");
12238   case MVT::nxv2i8:
12239   case MVT::nxv2i16:
12240   case MVT::nxv2i32:
12241   case MVT::nxv2i64:
12242   case MVT::nxv2f32:
12243   case MVT::nxv2f64:
12244     return MVT::nxv2i64;
12245   case MVT::nxv4i8:
12246   case MVT::nxv4i16:
12247   case MVT::nxv4i32:
12248   case MVT::nxv4f32:
12249     return MVT::nxv4i32;
12250   case MVT::nxv8i8:
12251   case MVT::nxv8i16:
12252   case MVT::nxv8f16:
12253   case MVT::nxv8bf16:
12254     return MVT::nxv8i16;
12255   case MVT::nxv16i8:
12256     return MVT::nxv16i8;
12257   }
12258 }
12259 
12260 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
12261   SDLoc DL(N);
12262   EVT VT = N->getValueType(0);
12263 
12264   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12265     return SDValue();
12266 
12267   EVT ContainerVT = VT;
12268   if (ContainerVT.isInteger())
12269     ContainerVT = getSVEContainerType(ContainerVT);
12270 
12271   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
12272   SDValue Ops[] = { N->getOperand(0), // Chain
12273                     N->getOperand(2), // Pg
12274                     N->getOperand(3), // Base
12275                     DAG.getValueType(VT) };
12276 
12277   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
12278   SDValue LoadChain = SDValue(Load.getNode(), 1);
12279 
12280   if (ContainerVT.isInteger() && (VT != ContainerVT))
12281     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
12282 
12283   return DAG.getMergeValues({ Load, LoadChain }, DL);
12284 }
12285 
12286 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
12287   SDLoc DL(N);
12288   EVT VT = N->getValueType(0);
12289   EVT PtrTy = N->getOperand(3).getValueType();
12290 
12291   if (VT == MVT::nxv8bf16 &&
12292       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12293     return SDValue();
12294 
12295   EVT LoadVT = VT;
12296   if (VT.isFloatingPoint())
12297     LoadVT = VT.changeTypeToInteger();
12298 
12299   auto *MINode = cast<MemIntrinsicSDNode>(N);
12300   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
12301   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
12302                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
12303                                 MINode->getOperand(2), PassThru,
12304                                 MINode->getMemoryVT(), MINode->getMemOperand(),
12305                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
12306 
12307    if (VT.isFloatingPoint()) {
12308      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
12309      return DAG.getMergeValues(Ops, DL);
12310    }
12311 
12312   return L;
12313 }
12314 
12315 template <unsigned Opcode>
12316 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
12317   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
12318                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
12319                 "Unsupported opcode.");
12320   SDLoc DL(N);
12321   EVT VT = N->getValueType(0);
12322   if (VT == MVT::nxv8bf16 &&
12323       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12324     return SDValue();
12325 
12326   EVT LoadVT = VT;
12327   if (VT.isFloatingPoint())
12328     LoadVT = VT.changeTypeToInteger();
12329 
12330   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
12331   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
12332   SDValue LoadChain = SDValue(Load.getNode(), 1);
12333 
12334   if (VT.isFloatingPoint())
12335     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
12336 
12337   return DAG.getMergeValues({Load, LoadChain}, DL);
12338 }
12339 
12340 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
12341   SDLoc DL(N);
12342   SDValue Data = N->getOperand(2);
12343   EVT DataVT = Data.getValueType();
12344   EVT HwSrcVt = getSVEContainerType(DataVT);
12345   SDValue InputVT = DAG.getValueType(DataVT);
12346 
12347   if (DataVT == MVT::nxv8bf16 &&
12348       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12349     return SDValue();
12350 
12351   if (DataVT.isFloatingPoint())
12352     InputVT = DAG.getValueType(HwSrcVt);
12353 
12354   SDValue SrcNew;
12355   if (Data.getValueType().isFloatingPoint())
12356     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
12357   else
12358     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
12359 
12360   SDValue Ops[] = { N->getOperand(0), // Chain
12361                     SrcNew,
12362                     N->getOperand(4), // Base
12363                     N->getOperand(3), // Pg
12364                     InputVT
12365                   };
12366 
12367   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
12368 }
12369 
12370 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
12371   SDLoc DL(N);
12372 
12373   SDValue Data = N->getOperand(2);
12374   EVT DataVT = Data.getValueType();
12375   EVT PtrTy = N->getOperand(4).getValueType();
12376 
12377   if (DataVT == MVT::nxv8bf16 &&
12378       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12379     return SDValue();
12380 
12381   if (DataVT.isFloatingPoint())
12382     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
12383 
12384   auto *MINode = cast<MemIntrinsicSDNode>(N);
12385   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
12386                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
12387                             MINode->getMemoryVT(), MINode->getMemOperand(),
12388                             ISD::UNINDEXED, false, false);
12389 }
12390 
12391 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
12392 /// load store optimizer pass will merge them to store pair stores.  This should
12393 /// be better than a movi to create the vector zero followed by a vector store
12394 /// if the zero constant is not re-used, since one instructions and one register
12395 /// live range will be removed.
12396 ///
12397 /// For example, the final generated code should be:
12398 ///
12399 ///   stp xzr, xzr, [x0]
12400 ///
12401 /// instead of:
12402 ///
12403 ///   movi v0.2d, #0
12404 ///   str q0, [x0]
12405 ///
12406 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12407   SDValue StVal = St.getValue();
12408   EVT VT = StVal.getValueType();
12409 
12410   // Avoid scalarizing zero splat stores for scalable vectors.
12411   if (VT.isScalableVector())
12412     return SDValue();
12413 
12414   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
12415   // 2, 3 or 4 i32 elements.
12416   int NumVecElts = VT.getVectorNumElements();
12417   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
12418          VT.getVectorElementType().getSizeInBits() == 64) ||
12419         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
12420          VT.getVectorElementType().getSizeInBits() == 32)))
12421     return SDValue();
12422 
12423   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
12424     return SDValue();
12425 
12426   // If the zero constant has more than one use then the vector store could be
12427   // better since the constant mov will be amortized and stp q instructions
12428   // should be able to be formed.
12429   if (!StVal.hasOneUse())
12430     return SDValue();
12431 
12432   // If the store is truncating then it's going down to i16 or smaller, which
12433   // means it can be implemented in a single store anyway.
12434   if (St.isTruncatingStore())
12435     return SDValue();
12436 
12437   // If the immediate offset of the address operand is too large for the stp
12438   // instruction, then bail out.
12439   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
12440     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
12441     if (Offset < -512 || Offset > 504)
12442       return SDValue();
12443   }
12444 
12445   for (int I = 0; I < NumVecElts; ++I) {
12446     SDValue EltVal = StVal.getOperand(I);
12447     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
12448       return SDValue();
12449   }
12450 
12451   // Use a CopyFromReg WZR/XZR here to prevent
12452   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
12453   SDLoc DL(&St);
12454   unsigned ZeroReg;
12455   EVT ZeroVT;
12456   if (VT.getVectorElementType().getSizeInBits() == 32) {
12457     ZeroReg = AArch64::WZR;
12458     ZeroVT = MVT::i32;
12459   } else {
12460     ZeroReg = AArch64::XZR;
12461     ZeroVT = MVT::i64;
12462   }
12463   SDValue SplatVal =
12464       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
12465   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12466 }
12467 
12468 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
12469 /// value. The load store optimizer pass will merge them to store pair stores.
12470 /// This has better performance than a splat of the scalar followed by a split
12471 /// vector store. Even if the stores are not merged it is four stores vs a dup,
12472 /// followed by an ext.b and two stores.
12473 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12474   SDValue StVal = St.getValue();
12475   EVT VT = StVal.getValueType();
12476 
12477   // Don't replace floating point stores, they possibly won't be transformed to
12478   // stp because of the store pair suppress pass.
12479   if (VT.isFloatingPoint())
12480     return SDValue();
12481 
12482   // We can express a splat as store pair(s) for 2 or 4 elements.
12483   unsigned NumVecElts = VT.getVectorNumElements();
12484   if (NumVecElts != 4 && NumVecElts != 2)
12485     return SDValue();
12486 
12487   // If the store is truncating then it's going down to i16 or smaller, which
12488   // means it can be implemented in a single store anyway.
12489   if (St.isTruncatingStore())
12490     return SDValue();
12491 
12492   // Check that this is a splat.
12493   // Make sure that each of the relevant vector element locations are inserted
12494   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
12495   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
12496   SDValue SplatVal;
12497   for (unsigned I = 0; I < NumVecElts; ++I) {
12498     // Check for insert vector elements.
12499     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
12500       return SDValue();
12501 
12502     // Check that same value is inserted at each vector element.
12503     if (I == 0)
12504       SplatVal = StVal.getOperand(1);
12505     else if (StVal.getOperand(1) != SplatVal)
12506       return SDValue();
12507 
12508     // Check insert element index.
12509     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
12510     if (!CIndex)
12511       return SDValue();
12512     uint64_t IndexVal = CIndex->getZExtValue();
12513     if (IndexVal >= NumVecElts)
12514       return SDValue();
12515     IndexNotInserted.reset(IndexVal);
12516 
12517     StVal = StVal.getOperand(0);
12518   }
12519   // Check that all vector element locations were inserted to.
12520   if (IndexNotInserted.any())
12521       return SDValue();
12522 
12523   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12524 }
12525 
12526 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12527                            SelectionDAG &DAG,
12528                            const AArch64Subtarget *Subtarget) {
12529 
12530   StoreSDNode *S = cast<StoreSDNode>(N);
12531   if (S->isVolatile() || S->isIndexed())
12532     return SDValue();
12533 
12534   SDValue StVal = S->getValue();
12535   EVT VT = StVal.getValueType();
12536 
12537   if (!VT.isFixedLengthVector())
12538     return SDValue();
12539 
12540   // If we get a splat of zeros, convert this vector store to a store of
12541   // scalars. They will be merged into store pairs of xzr thereby removing one
12542   // instruction and one register.
12543   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
12544     return ReplacedZeroSplat;
12545 
12546   // FIXME: The logic for deciding if an unaligned store should be split should
12547   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
12548   // a call to that function here.
12549 
12550   if (!Subtarget->isMisaligned128StoreSlow())
12551     return SDValue();
12552 
12553   // Don't split at -Oz.
12554   if (DAG.getMachineFunction().getFunction().hasMinSize())
12555     return SDValue();
12556 
12557   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
12558   // those up regresses performance on micro-benchmarks and olden/bh.
12559   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
12560     return SDValue();
12561 
12562   // Split unaligned 16B stores. They are terrible for performance.
12563   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
12564   // extensions can use this to mark that it does not want splitting to happen
12565   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
12566   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
12567   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
12568       S->getAlignment() <= 2)
12569     return SDValue();
12570 
12571   // If we get a splat of a scalar convert this vector store to a store of
12572   // scalars. They will be merged into store pairs thereby removing two
12573   // instructions.
12574   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
12575     return ReplacedSplat;
12576 
12577   SDLoc DL(S);
12578 
12579   // Split VT into two.
12580   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
12581   unsigned NumElts = HalfVT.getVectorNumElements();
12582   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12583                                    DAG.getConstant(0, DL, MVT::i64));
12584   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12585                                    DAG.getConstant(NumElts, DL, MVT::i64));
12586   SDValue BasePtr = S->getBasePtr();
12587   SDValue NewST1 =
12588       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
12589                    S->getAlignment(), S->getMemOperand()->getFlags());
12590   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12591                                   DAG.getConstant(8, DL, MVT::i64));
12592   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
12593                       S->getPointerInfo(), S->getAlignment(),
12594                       S->getMemOperand()->getFlags());
12595 }
12596 
12597 /// Target-specific DAG combine function for post-increment LD1 (lane) and
12598 /// post-increment LD1R.
12599 static SDValue performPostLD1Combine(SDNode *N,
12600                                      TargetLowering::DAGCombinerInfo &DCI,
12601                                      bool IsLaneOp) {
12602   if (DCI.isBeforeLegalizeOps())
12603     return SDValue();
12604 
12605   SelectionDAG &DAG = DCI.DAG;
12606   EVT VT = N->getValueType(0);
12607 
12608   if (VT.isScalableVector())
12609     return SDValue();
12610 
12611   unsigned LoadIdx = IsLaneOp ? 1 : 0;
12612   SDNode *LD = N->getOperand(LoadIdx).getNode();
12613   // If it is not LOAD, can not do such combine.
12614   if (LD->getOpcode() != ISD::LOAD)
12615     return SDValue();
12616 
12617   // The vector lane must be a constant in the LD1LANE opcode.
12618   SDValue Lane;
12619   if (IsLaneOp) {
12620     Lane = N->getOperand(2);
12621     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
12622     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
12623       return SDValue();
12624   }
12625 
12626   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
12627   EVT MemVT = LoadSDN->getMemoryVT();
12628   // Check if memory operand is the same type as the vector element.
12629   if (MemVT != VT.getVectorElementType())
12630     return SDValue();
12631 
12632   // Check if there are other uses. If so, do not combine as it will introduce
12633   // an extra load.
12634   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
12635        ++UI) {
12636     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
12637       continue;
12638     if (*UI != N)
12639       return SDValue();
12640   }
12641 
12642   SDValue Addr = LD->getOperand(1);
12643   SDValue Vector = N->getOperand(0);
12644   // Search for a use of the address operand that is an increment.
12645   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
12646        Addr.getNode()->use_end(); UI != UE; ++UI) {
12647     SDNode *User = *UI;
12648     if (User->getOpcode() != ISD::ADD
12649         || UI.getUse().getResNo() != Addr.getResNo())
12650       continue;
12651 
12652     // If the increment is a constant, it must match the memory ref size.
12653     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12654     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12655       uint32_t IncVal = CInc->getZExtValue();
12656       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
12657       if (IncVal != NumBytes)
12658         continue;
12659       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12660     }
12661 
12662     // To avoid cycle construction make sure that neither the load nor the add
12663     // are predecessors to each other or the Vector.
12664     SmallPtrSet<const SDNode *, 32> Visited;
12665     SmallVector<const SDNode *, 16> Worklist;
12666     Visited.insert(Addr.getNode());
12667     Worklist.push_back(User);
12668     Worklist.push_back(LD);
12669     Worklist.push_back(Vector.getNode());
12670     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
12671         SDNode::hasPredecessorHelper(User, Visited, Worklist))
12672       continue;
12673 
12674     SmallVector<SDValue, 8> Ops;
12675     Ops.push_back(LD->getOperand(0));  // Chain
12676     if (IsLaneOp) {
12677       Ops.push_back(Vector);           // The vector to be inserted
12678       Ops.push_back(Lane);             // The lane to be inserted in the vector
12679     }
12680     Ops.push_back(Addr);
12681     Ops.push_back(Inc);
12682 
12683     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
12684     SDVTList SDTys = DAG.getVTList(Tys);
12685     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
12686     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
12687                                            MemVT,
12688                                            LoadSDN->getMemOperand());
12689 
12690     // Update the uses.
12691     SDValue NewResults[] = {
12692         SDValue(LD, 0),            // The result of load
12693         SDValue(UpdN.getNode(), 2) // Chain
12694     };
12695     DCI.CombineTo(LD, NewResults);
12696     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
12697     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
12698 
12699     break;
12700   }
12701   return SDValue();
12702 }
12703 
12704 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
12705 /// address translation.
12706 static bool performTBISimplification(SDValue Addr,
12707                                      TargetLowering::DAGCombinerInfo &DCI,
12708                                      SelectionDAG &DAG) {
12709   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
12710   KnownBits Known;
12711   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12712                                         !DCI.isBeforeLegalizeOps());
12713   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12714   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
12715     DCI.CommitTargetLoweringOpt(TLO);
12716     return true;
12717   }
12718   return false;
12719 }
12720 
12721 static SDValue performSTORECombine(SDNode *N,
12722                                    TargetLowering::DAGCombinerInfo &DCI,
12723                                    SelectionDAG &DAG,
12724                                    const AArch64Subtarget *Subtarget) {
12725   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
12726     return Split;
12727 
12728   if (Subtarget->supportsAddressTopByteIgnored() &&
12729       performTBISimplification(N->getOperand(2), DCI, DAG))
12730     return SDValue(N, 0);
12731 
12732   return SDValue();
12733 }
12734 
12735 
12736 /// Target-specific DAG combine function for NEON load/store intrinsics
12737 /// to merge base address updates.
12738 static SDValue performNEONPostLDSTCombine(SDNode *N,
12739                                           TargetLowering::DAGCombinerInfo &DCI,
12740                                           SelectionDAG &DAG) {
12741   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12742     return SDValue();
12743 
12744   unsigned AddrOpIdx = N->getNumOperands() - 1;
12745   SDValue Addr = N->getOperand(AddrOpIdx);
12746 
12747   // Search for a use of the address operand that is an increment.
12748   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12749        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12750     SDNode *User = *UI;
12751     if (User->getOpcode() != ISD::ADD ||
12752         UI.getUse().getResNo() != Addr.getResNo())
12753       continue;
12754 
12755     // Check that the add is independent of the load/store.  Otherwise, folding
12756     // it would create a cycle.
12757     SmallPtrSet<const SDNode *, 32> Visited;
12758     SmallVector<const SDNode *, 16> Worklist;
12759     Visited.insert(Addr.getNode());
12760     Worklist.push_back(N);
12761     Worklist.push_back(User);
12762     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12763         SDNode::hasPredecessorHelper(User, Visited, Worklist))
12764       continue;
12765 
12766     // Find the new opcode for the updating load/store.
12767     bool IsStore = false;
12768     bool IsLaneOp = false;
12769     bool IsDupOp = false;
12770     unsigned NewOpc = 0;
12771     unsigned NumVecs = 0;
12772     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12773     switch (IntNo) {
12774     default: llvm_unreachable("unexpected intrinsic for Neon base update");
12775     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
12776       NumVecs = 2; break;
12777     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
12778       NumVecs = 3; break;
12779     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
12780       NumVecs = 4; break;
12781     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
12782       NumVecs = 2; IsStore = true; break;
12783     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
12784       NumVecs = 3; IsStore = true; break;
12785     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
12786       NumVecs = 4; IsStore = true; break;
12787     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
12788       NumVecs = 2; break;
12789     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
12790       NumVecs = 3; break;
12791     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
12792       NumVecs = 4; break;
12793     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
12794       NumVecs = 2; IsStore = true; break;
12795     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
12796       NumVecs = 3; IsStore = true; break;
12797     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
12798       NumVecs = 4; IsStore = true; break;
12799     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
12800       NumVecs = 2; IsDupOp = true; break;
12801     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
12802       NumVecs = 3; IsDupOp = true; break;
12803     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
12804       NumVecs = 4; IsDupOp = true; break;
12805     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
12806       NumVecs = 2; IsLaneOp = true; break;
12807     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
12808       NumVecs = 3; IsLaneOp = true; break;
12809     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
12810       NumVecs = 4; IsLaneOp = true; break;
12811     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
12812       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
12813     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
12814       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
12815     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
12816       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
12817     }
12818 
12819     EVT VecTy;
12820     if (IsStore)
12821       VecTy = N->getOperand(2).getValueType();
12822     else
12823       VecTy = N->getValueType(0);
12824 
12825     // If the increment is a constant, it must match the memory ref size.
12826     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12827     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12828       uint32_t IncVal = CInc->getZExtValue();
12829       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12830       if (IsLaneOp || IsDupOp)
12831         NumBytes /= VecTy.getVectorNumElements();
12832       if (IncVal != NumBytes)
12833         continue;
12834       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12835     }
12836     SmallVector<SDValue, 8> Ops;
12837     Ops.push_back(N->getOperand(0)); // Incoming chain
12838     // Load lane and store have vector list as input.
12839     if (IsLaneOp || IsStore)
12840       for (unsigned i = 2; i < AddrOpIdx; ++i)
12841         Ops.push_back(N->getOperand(i));
12842     Ops.push_back(Addr); // Base register
12843     Ops.push_back(Inc);
12844 
12845     // Return Types.
12846     EVT Tys[6];
12847     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
12848     unsigned n;
12849     for (n = 0; n < NumResultVecs; ++n)
12850       Tys[n] = VecTy;
12851     Tys[n++] = MVT::i64;  // Type of write back register
12852     Tys[n] = MVT::Other;  // Type of the chain
12853     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
12854 
12855     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
12856     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
12857                                            MemInt->getMemoryVT(),
12858                                            MemInt->getMemOperand());
12859 
12860     // Update the uses.
12861     std::vector<SDValue> NewResults;
12862     for (unsigned i = 0; i < NumResultVecs; ++i) {
12863       NewResults.push_back(SDValue(UpdN.getNode(), i));
12864     }
12865     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
12866     DCI.CombineTo(N, NewResults);
12867     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12868 
12869     break;
12870   }
12871   return SDValue();
12872 }
12873 
12874 // Checks to see if the value is the prescribed width and returns information
12875 // about its extension mode.
12876 static
12877 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
12878   ExtType = ISD::NON_EXTLOAD;
12879   switch(V.getNode()->getOpcode()) {
12880   default:
12881     return false;
12882   case ISD::LOAD: {
12883     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
12884     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
12885        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
12886       ExtType = LoadNode->getExtensionType();
12887       return true;
12888     }
12889     return false;
12890   }
12891   case ISD::AssertSext: {
12892     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12893     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12894        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12895       ExtType = ISD::SEXTLOAD;
12896       return true;
12897     }
12898     return false;
12899   }
12900   case ISD::AssertZext: {
12901     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12902     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12903        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12904       ExtType = ISD::ZEXTLOAD;
12905       return true;
12906     }
12907     return false;
12908   }
12909   case ISD::Constant:
12910   case ISD::TargetConstant: {
12911     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
12912            1LL << (width - 1);
12913   }
12914   }
12915 
12916   return true;
12917 }
12918 
12919 // This function does a whole lot of voodoo to determine if the tests are
12920 // equivalent without and with a mask. Essentially what happens is that given a
12921 // DAG resembling:
12922 //
12923 //  +-------------+ +-------------+ +-------------+ +-------------+
12924 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
12925 //  +-------------+ +-------------+ +-------------+ +-------------+
12926 //           |           |           |               |
12927 //           V           V           |    +----------+
12928 //          +-------------+  +----+  |    |
12929 //          |     ADD     |  |0xff|  |    |
12930 //          +-------------+  +----+  |    |
12931 //                  |           |    |    |
12932 //                  V           V    |    |
12933 //                 +-------------+   |    |
12934 //                 |     AND     |   |    |
12935 //                 +-------------+   |    |
12936 //                      |            |    |
12937 //                      +-----+      |    |
12938 //                            |      |    |
12939 //                            V      V    V
12940 //                           +-------------+
12941 //                           |     CMP     |
12942 //                           +-------------+
12943 //
12944 // The AND node may be safely removed for some combinations of inputs. In
12945 // particular we need to take into account the extension type of the Input,
12946 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
12947 // width of the input (this can work for any width inputs, the above graph is
12948 // specific to 8 bits.
12949 //
12950 // The specific equations were worked out by generating output tables for each
12951 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
12952 // problem was simplified by working with 4 bit inputs, which means we only
12953 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
12954 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
12955 // patterns present in both extensions (0,7). For every distinct set of
12956 // AddConstant and CompConstants bit patterns we can consider the masked and
12957 // unmasked versions to be equivalent if the result of this function is true for
12958 // all 16 distinct bit patterns of for the current extension type of Input (w0).
12959 //
12960 //   sub      w8, w0, w1
12961 //   and      w10, w8, #0x0f
12962 //   cmp      w8, w2
12963 //   cset     w9, AArch64CC
12964 //   cmp      w10, w2
12965 //   cset     w11, AArch64CC
12966 //   cmp      w9, w11
12967 //   cset     w0, eq
12968 //   ret
12969 //
12970 // Since the above function shows when the outputs are equivalent it defines
12971 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
12972 // would be expensive to run during compiles. The equations below were written
12973 // in a test harness that confirmed they gave equivalent outputs to the above
12974 // for all inputs function, so they can be used determine if the removal is
12975 // legal instead.
12976 //
12977 // isEquivalentMaskless() is the code for testing if the AND can be removed
12978 // factored out of the DAG recognition as the DAG can take several forms.
12979 
12980 static bool isEquivalentMaskless(unsigned CC, unsigned width,
12981                                  ISD::LoadExtType ExtType, int AddConstant,
12982                                  int CompConstant) {
12983   // By being careful about our equations and only writing the in term
12984   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
12985   // make them generally applicable to all bit widths.
12986   int MaxUInt = (1 << width);
12987 
12988   // For the purposes of these comparisons sign extending the type is
12989   // equivalent to zero extending the add and displacing it by half the integer
12990   // width. Provided we are careful and make sure our equations are valid over
12991   // the whole range we can just adjust the input and avoid writing equations
12992   // for sign extended inputs.
12993   if (ExtType == ISD::SEXTLOAD)
12994     AddConstant -= (1 << (width-1));
12995 
12996   switch(CC) {
12997   case AArch64CC::LE:
12998   case AArch64CC::GT:
12999     if ((AddConstant == 0) ||
13000         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
13001         (AddConstant >= 0 && CompConstant < 0) ||
13002         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
13003       return true;
13004     break;
13005   case AArch64CC::LT:
13006   case AArch64CC::GE:
13007     if ((AddConstant == 0) ||
13008         (AddConstant >= 0 && CompConstant <= 0) ||
13009         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
13010       return true;
13011     break;
13012   case AArch64CC::HI:
13013   case AArch64CC::LS:
13014     if ((AddConstant >= 0 && CompConstant < 0) ||
13015        (AddConstant <= 0 && CompConstant >= -1 &&
13016         CompConstant < AddConstant + MaxUInt))
13017       return true;
13018    break;
13019   case AArch64CC::PL:
13020   case AArch64CC::MI:
13021     if ((AddConstant == 0) ||
13022         (AddConstant > 0 && CompConstant <= 0) ||
13023         (AddConstant < 0 && CompConstant <= AddConstant))
13024       return true;
13025     break;
13026   case AArch64CC::LO:
13027   case AArch64CC::HS:
13028     if ((AddConstant >= 0 && CompConstant <= 0) ||
13029         (AddConstant <= 0 && CompConstant >= 0 &&
13030          CompConstant <= AddConstant + MaxUInt))
13031       return true;
13032     break;
13033   case AArch64CC::EQ:
13034   case AArch64CC::NE:
13035     if ((AddConstant > 0 && CompConstant < 0) ||
13036         (AddConstant < 0 && CompConstant >= 0 &&
13037          CompConstant < AddConstant + MaxUInt) ||
13038         (AddConstant >= 0 && CompConstant >= 0 &&
13039          CompConstant >= AddConstant) ||
13040         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
13041       return true;
13042     break;
13043   case AArch64CC::VS:
13044   case AArch64CC::VC:
13045   case AArch64CC::AL:
13046   case AArch64CC::NV:
13047     return true;
13048   case AArch64CC::Invalid:
13049     break;
13050   }
13051 
13052   return false;
13053 }
13054 
13055 static
13056 SDValue performCONDCombine(SDNode *N,
13057                            TargetLowering::DAGCombinerInfo &DCI,
13058                            SelectionDAG &DAG, unsigned CCIndex,
13059                            unsigned CmpIndex) {
13060   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
13061   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
13062   unsigned CondOpcode = SubsNode->getOpcode();
13063 
13064   if (CondOpcode != AArch64ISD::SUBS)
13065     return SDValue();
13066 
13067   // There is a SUBS feeding this condition. Is it fed by a mask we can
13068   // use?
13069 
13070   SDNode *AndNode = SubsNode->getOperand(0).getNode();
13071   unsigned MaskBits = 0;
13072 
13073   if (AndNode->getOpcode() != ISD::AND)
13074     return SDValue();
13075 
13076   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
13077     uint32_t CNV = CN->getZExtValue();
13078     if (CNV == 255)
13079       MaskBits = 8;
13080     else if (CNV == 65535)
13081       MaskBits = 16;
13082   }
13083 
13084   if (!MaskBits)
13085     return SDValue();
13086 
13087   SDValue AddValue = AndNode->getOperand(0);
13088 
13089   if (AddValue.getOpcode() != ISD::ADD)
13090     return SDValue();
13091 
13092   // The basic dag structure is correct, grab the inputs and validate them.
13093 
13094   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
13095   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
13096   SDValue SubsInputValue = SubsNode->getOperand(1);
13097 
13098   // The mask is present and the provenance of all the values is a smaller type,
13099   // lets see if the mask is superfluous.
13100 
13101   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
13102       !isa<ConstantSDNode>(SubsInputValue.getNode()))
13103     return SDValue();
13104 
13105   ISD::LoadExtType ExtType;
13106 
13107   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
13108       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
13109       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
13110     return SDValue();
13111 
13112   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
13113                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
13114                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
13115     return SDValue();
13116 
13117   // The AND is not necessary, remove it.
13118 
13119   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
13120                                SubsNode->getValueType(1));
13121   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
13122 
13123   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
13124   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
13125 
13126   return SDValue(N, 0);
13127 }
13128 
13129 // Optimize compare with zero and branch.
13130 static SDValue performBRCONDCombine(SDNode *N,
13131                                     TargetLowering::DAGCombinerInfo &DCI,
13132                                     SelectionDAG &DAG) {
13133   MachineFunction &MF = DAG.getMachineFunction();
13134   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
13135   // will not be produced, as they are conditional branch instructions that do
13136   // not set flags.
13137   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
13138     return SDValue();
13139 
13140   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
13141     N = NV.getNode();
13142   SDValue Chain = N->getOperand(0);
13143   SDValue Dest = N->getOperand(1);
13144   SDValue CCVal = N->getOperand(2);
13145   SDValue Cmp = N->getOperand(3);
13146 
13147   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
13148   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
13149   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
13150     return SDValue();
13151 
13152   unsigned CmpOpc = Cmp.getOpcode();
13153   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
13154     return SDValue();
13155 
13156   // Only attempt folding if there is only one use of the flag and no use of the
13157   // value.
13158   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
13159     return SDValue();
13160 
13161   SDValue LHS = Cmp.getOperand(0);
13162   SDValue RHS = Cmp.getOperand(1);
13163 
13164   assert(LHS.getValueType() == RHS.getValueType() &&
13165          "Expected the value type to be the same for both operands!");
13166   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
13167     return SDValue();
13168 
13169   if (isNullConstant(LHS))
13170     std::swap(LHS, RHS);
13171 
13172   if (!isNullConstant(RHS))
13173     return SDValue();
13174 
13175   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
13176       LHS.getOpcode() == ISD::SRL)
13177     return SDValue();
13178 
13179   // Fold the compare into the branch instruction.
13180   SDValue BR;
13181   if (CC == AArch64CC::EQ)
13182     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13183   else
13184     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13185 
13186   // Do not add new nodes to DAG combiner worklist.
13187   DCI.CombineTo(N, BR, false);
13188 
13189   return SDValue();
13190 }
13191 
13192 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
13193 // as well as whether the test should be inverted.  This code is required to
13194 // catch these cases (as opposed to standard dag combines) because
13195 // AArch64ISD::TBZ is matched during legalization.
13196 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
13197                                  SelectionDAG &DAG) {
13198 
13199   if (!Op->hasOneUse())
13200     return Op;
13201 
13202   // We don't handle undef/constant-fold cases below, as they should have
13203   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
13204   // etc.)
13205 
13206   // (tbz (trunc x), b) -> (tbz x, b)
13207   // This case is just here to enable more of the below cases to be caught.
13208   if (Op->getOpcode() == ISD::TRUNCATE &&
13209       Bit < Op->getValueType(0).getSizeInBits()) {
13210     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13211   }
13212 
13213   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
13214   if (Op->getOpcode() == ISD::ANY_EXTEND &&
13215       Bit < Op->getOperand(0).getValueSizeInBits()) {
13216     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13217   }
13218 
13219   if (Op->getNumOperands() != 2)
13220     return Op;
13221 
13222   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13223   if (!C)
13224     return Op;
13225 
13226   switch (Op->getOpcode()) {
13227   default:
13228     return Op;
13229 
13230   // (tbz (and x, m), b) -> (tbz x, b)
13231   case ISD::AND:
13232     if ((C->getZExtValue() >> Bit) & 1)
13233       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13234     return Op;
13235 
13236   // (tbz (shl x, c), b) -> (tbz x, b-c)
13237   case ISD::SHL:
13238     if (C->getZExtValue() <= Bit &&
13239         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13240       Bit = Bit - C->getZExtValue();
13241       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13242     }
13243     return Op;
13244 
13245   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
13246   case ISD::SRA:
13247     Bit = Bit + C->getZExtValue();
13248     if (Bit >= Op->getValueType(0).getSizeInBits())
13249       Bit = Op->getValueType(0).getSizeInBits() - 1;
13250     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13251 
13252   // (tbz (srl x, c), b) -> (tbz x, b+c)
13253   case ISD::SRL:
13254     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13255       Bit = Bit + C->getZExtValue();
13256       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13257     }
13258     return Op;
13259 
13260   // (tbz (xor x, -1), b) -> (tbnz x, b)
13261   case ISD::XOR:
13262     if ((C->getZExtValue() >> Bit) & 1)
13263       Invert = !Invert;
13264     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13265   }
13266 }
13267 
13268 // Optimize test single bit zero/non-zero and branch.
13269 static SDValue performTBZCombine(SDNode *N,
13270                                  TargetLowering::DAGCombinerInfo &DCI,
13271                                  SelectionDAG &DAG) {
13272   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13273   bool Invert = false;
13274   SDValue TestSrc = N->getOperand(1);
13275   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
13276 
13277   if (TestSrc == NewTestSrc)
13278     return SDValue();
13279 
13280   unsigned NewOpc = N->getOpcode();
13281   if (Invert) {
13282     if (NewOpc == AArch64ISD::TBZ)
13283       NewOpc = AArch64ISD::TBNZ;
13284     else {
13285       assert(NewOpc == AArch64ISD::TBNZ);
13286       NewOpc = AArch64ISD::TBZ;
13287     }
13288   }
13289 
13290   SDLoc DL(N);
13291   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
13292                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
13293 }
13294 
13295 // vselect (v1i1 setcc) ->
13296 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
13297 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
13298 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
13299 // such VSELECT.
13300 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
13301   SDValue N0 = N->getOperand(0);
13302   EVT CCVT = N0.getValueType();
13303 
13304   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
13305       CCVT.getVectorElementType() != MVT::i1)
13306     return SDValue();
13307 
13308   EVT ResVT = N->getValueType(0);
13309   EVT CmpVT = N0.getOperand(0).getValueType();
13310   // Only combine when the result type is of the same size as the compared
13311   // operands.
13312   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
13313     return SDValue();
13314 
13315   SDValue IfTrue = N->getOperand(1);
13316   SDValue IfFalse = N->getOperand(2);
13317   SDValue SetCC =
13318       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
13319                    N0.getOperand(0), N0.getOperand(1),
13320                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
13321   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
13322                      IfTrue, IfFalse);
13323 }
13324 
13325 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
13326 /// the compare-mask instructions rather than going via NZCV, even if LHS and
13327 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
13328 /// with a vector one followed by a DUP shuffle on the result.
13329 static SDValue performSelectCombine(SDNode *N,
13330                                     TargetLowering::DAGCombinerInfo &DCI) {
13331   SelectionDAG &DAG = DCI.DAG;
13332   SDValue N0 = N->getOperand(0);
13333   EVT ResVT = N->getValueType(0);
13334 
13335   if (N0.getOpcode() != ISD::SETCC)
13336     return SDValue();
13337 
13338   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
13339   // scalar SetCCResultType. We also don't expect vectors, because we assume
13340   // that selects fed by vector SETCCs are canonicalized to VSELECT.
13341   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
13342          "Scalar-SETCC feeding SELECT has unexpected result type!");
13343 
13344   // If NumMaskElts == 0, the comparison is larger than select result. The
13345   // largest real NEON comparison is 64-bits per lane, which means the result is
13346   // at most 32-bits and an illegal vector. Just bail out for now.
13347   EVT SrcVT = N0.getOperand(0).getValueType();
13348 
13349   // Don't try to do this optimization when the setcc itself has i1 operands.
13350   // There are no legal vectors of i1, so this would be pointless.
13351   if (SrcVT == MVT::i1)
13352     return SDValue();
13353 
13354   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
13355   if (!ResVT.isVector() || NumMaskElts == 0)
13356     return SDValue();
13357 
13358   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
13359   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
13360 
13361   // Also bail out if the vector CCVT isn't the same size as ResVT.
13362   // This can happen if the SETCC operand size doesn't divide the ResVT size
13363   // (e.g., f64 vs v3f32).
13364   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
13365     return SDValue();
13366 
13367   // Make sure we didn't create illegal types, if we're not supposed to.
13368   assert(DCI.isBeforeLegalize() ||
13369          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
13370 
13371   // First perform a vector comparison, where lane 0 is the one we're interested
13372   // in.
13373   SDLoc DL(N0);
13374   SDValue LHS =
13375       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
13376   SDValue RHS =
13377       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
13378   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
13379 
13380   // Now duplicate the comparison mask we want across all other lanes.
13381   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
13382   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
13383   Mask = DAG.getNode(ISD::BITCAST, DL,
13384                      ResVT.changeVectorElementTypeToInteger(), Mask);
13385 
13386   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
13387 }
13388 
13389 /// Get rid of unnecessary NVCASTs (that don't change the type).
13390 static SDValue performNVCASTCombine(SDNode *N) {
13391   if (N->getValueType(0) == N->getOperand(0).getValueType())
13392     return N->getOperand(0);
13393 
13394   return SDValue();
13395 }
13396 
13397 // If all users of the globaladdr are of the form (globaladdr + constant), find
13398 // the smallest constant, fold it into the globaladdr's offset and rewrite the
13399 // globaladdr as (globaladdr + constant) - constant.
13400 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
13401                                            const AArch64Subtarget *Subtarget,
13402                                            const TargetMachine &TM) {
13403   auto *GN = cast<GlobalAddressSDNode>(N);
13404   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
13405       AArch64II::MO_NO_FLAG)
13406     return SDValue();
13407 
13408   uint64_t MinOffset = -1ull;
13409   for (SDNode *N : GN->uses()) {
13410     if (N->getOpcode() != ISD::ADD)
13411       return SDValue();
13412     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
13413     if (!C)
13414       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13415     if (!C)
13416       return SDValue();
13417     MinOffset = std::min(MinOffset, C->getZExtValue());
13418   }
13419   uint64_t Offset = MinOffset + GN->getOffset();
13420 
13421   // Require that the new offset is larger than the existing one. Otherwise, we
13422   // can end up oscillating between two possible DAGs, for example,
13423   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
13424   if (Offset <= uint64_t(GN->getOffset()))
13425     return SDValue();
13426 
13427   // Check whether folding this offset is legal. It must not go out of bounds of
13428   // the referenced object to avoid violating the code model, and must be
13429   // smaller than 2^21 because this is the largest offset expressible in all
13430   // object formats.
13431   //
13432   // This check also prevents us from folding negative offsets, which will end
13433   // up being treated in the same way as large positive ones. They could also
13434   // cause code model violations, and aren't really common enough to matter.
13435   if (Offset >= (1 << 21))
13436     return SDValue();
13437 
13438   const GlobalValue *GV = GN->getGlobal();
13439   Type *T = GV->getValueType();
13440   if (!T->isSized() ||
13441       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
13442     return SDValue();
13443 
13444   SDLoc DL(GN);
13445   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
13446   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
13447                      DAG.getConstant(MinOffset, DL, MVT::i64));
13448 }
13449 
13450 // Turns the vector of indices into a vector of byte offstes by scaling Offset
13451 // by (BitWidth / 8).
13452 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
13453                                           SDLoc DL, unsigned BitWidth) {
13454   assert(Offset.getValueType().isScalableVector() &&
13455          "This method is only for scalable vectors of offsets");
13456 
13457   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
13458   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
13459 
13460   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
13461 }
13462 
13463 /// Check if the value of \p OffsetInBytes can be used as an immediate for
13464 /// the gather load/prefetch and scatter store instructions with vector base and
13465 /// immediate offset addressing mode:
13466 ///
13467 ///      [<Zn>.[S|D]{, #<imm>}]
13468 ///
13469 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13470 
13471 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
13472                                                   unsigned ScalarSizeInBytes) {
13473   // The immediate is not a multiple of the scalar size.
13474   if (OffsetInBytes % ScalarSizeInBytes)
13475     return false;
13476 
13477   // The immediate is out of range.
13478   if (OffsetInBytes / ScalarSizeInBytes > 31)
13479     return false;
13480 
13481   return true;
13482 }
13483 
13484 /// Check if the value of \p Offset represents a valid immediate for the SVE
13485 /// gather load/prefetch and scatter store instructiona with vector base and
13486 /// immediate offset addressing mode:
13487 ///
13488 ///      [<Zn>.[S|D]{, #<imm>}]
13489 ///
13490 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13491 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
13492                                            unsigned ScalarSizeInBytes) {
13493   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
13494   return OffsetConst && isValidImmForSVEVecImmAddrMode(
13495                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
13496 }
13497 
13498 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
13499                                           unsigned Opcode,
13500                                           bool OnlyPackedOffsets = true) {
13501   const SDValue Src = N->getOperand(2);
13502   const EVT SrcVT = Src->getValueType(0);
13503   assert(SrcVT.isScalableVector() &&
13504          "Scatter stores are only possible for SVE vectors");
13505 
13506   SDLoc DL(N);
13507   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
13508 
13509   // Make sure that source data will fit into an SVE register
13510   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13511     return SDValue();
13512 
13513   // For FPs, ACLE only supports _packed_ single and double precision types.
13514   if (SrcElVT.isFloatingPoint())
13515     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
13516       return SDValue();
13517 
13518   // Depending on the addressing mode, this is either a pointer or a vector of
13519   // pointers (that fits into one register)
13520   SDValue Base = N->getOperand(4);
13521   // Depending on the addressing mode, this is either a single offset or a
13522   // vector of offsets  (that fits into one register)
13523   SDValue Offset = N->getOperand(5);
13524 
13525   // For "scalar + vector of indices", just scale the indices. This only
13526   // applies to non-temporal scatters because there's no instruction that takes
13527   // indicies.
13528   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
13529     Offset =
13530         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
13531     Opcode = AArch64ISD::SSTNT1_PRED;
13532   }
13533 
13534   // In the case of non-temporal gather loads there's only one SVE instruction
13535   // per data-size: "scalar + vector", i.e.
13536   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13537   // Since we do have intrinsics that allow the arguments to be in a different
13538   // order, we may need to swap them to match the spec.
13539   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
13540     std::swap(Base, Offset);
13541 
13542   // SST1_IMM requires that the offset is an immediate that is:
13543   //    * a multiple of #SizeInBytes,
13544   //    * in the range [0, 31 x #SizeInBytes],
13545   // where #SizeInBytes is the size in bytes of the stored items. For
13546   // immediates outside that range and non-immediate scalar offsets use SST1 or
13547   // SST1_UXTW instead.
13548   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
13549     if (!isValidImmForSVEVecImmAddrMode(Offset,
13550                                         SrcVT.getScalarSizeInBits() / 8)) {
13551       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13552         Opcode = AArch64ISD::SST1_UXTW_PRED;
13553       else
13554         Opcode = AArch64ISD::SST1_PRED;
13555 
13556       std::swap(Base, Offset);
13557     }
13558   }
13559 
13560   auto &TLI = DAG.getTargetLoweringInfo();
13561   if (!TLI.isTypeLegal(Base.getValueType()))
13562     return SDValue();
13563 
13564   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
13565   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13566   // nxv2i64. Legalize accordingly.
13567   if (!OnlyPackedOffsets &&
13568       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13569     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13570 
13571   if (!TLI.isTypeLegal(Offset.getValueType()))
13572     return SDValue();
13573 
13574   // Source value type that is representable in hardware
13575   EVT HwSrcVt = getSVEContainerType(SrcVT);
13576 
13577   // Keep the original type of the input data to store - this is needed to be
13578   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
13579   // FP values we want the integer equivalent, so just use HwSrcVt.
13580   SDValue InputVT = DAG.getValueType(SrcVT);
13581   if (SrcVT.isFloatingPoint())
13582     InputVT = DAG.getValueType(HwSrcVt);
13583 
13584   SDVTList VTs = DAG.getVTList(MVT::Other);
13585   SDValue SrcNew;
13586 
13587   if (Src.getValueType().isFloatingPoint())
13588     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
13589   else
13590     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
13591 
13592   SDValue Ops[] = {N->getOperand(0), // Chain
13593                    SrcNew,
13594                    N->getOperand(3), // Pg
13595                    Base,
13596                    Offset,
13597                    InputVT};
13598 
13599   return DAG.getNode(Opcode, DL, VTs, Ops);
13600 }
13601 
13602 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
13603                                         unsigned Opcode,
13604                                         bool OnlyPackedOffsets = true) {
13605   const EVT RetVT = N->getValueType(0);
13606   assert(RetVT.isScalableVector() &&
13607          "Gather loads are only possible for SVE vectors");
13608 
13609   SDLoc DL(N);
13610 
13611   // Make sure that the loaded data will fit into an SVE register
13612   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13613     return SDValue();
13614 
13615   // Depending on the addressing mode, this is either a pointer or a vector of
13616   // pointers (that fits into one register)
13617   SDValue Base = N->getOperand(3);
13618   // Depending on the addressing mode, this is either a single offset or a
13619   // vector of offsets  (that fits into one register)
13620   SDValue Offset = N->getOperand(4);
13621 
13622   // For "scalar + vector of indices", just scale the indices. This only
13623   // applies to non-temporal gathers because there's no instruction that takes
13624   // indicies.
13625   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
13626     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
13627                                         RetVT.getScalarSizeInBits());
13628     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
13629   }
13630 
13631   // In the case of non-temporal gather loads there's only one SVE instruction
13632   // per data-size: "scalar + vector", i.e.
13633   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13634   // Since we do have intrinsics that allow the arguments to be in a different
13635   // order, we may need to swap them to match the spec.
13636   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
13637       Offset.getValueType().isVector())
13638     std::swap(Base, Offset);
13639 
13640   // GLD{FF}1_IMM requires that the offset is an immediate that is:
13641   //    * a multiple of #SizeInBytes,
13642   //    * in the range [0, 31 x #SizeInBytes],
13643   // where #SizeInBytes is the size in bytes of the loaded items. For
13644   // immediates outside that range and non-immediate scalar offsets use
13645   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
13646   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
13647       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
13648     if (!isValidImmForSVEVecImmAddrMode(Offset,
13649                                         RetVT.getScalarSizeInBits() / 8)) {
13650       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13651         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13652                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
13653                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
13654       else
13655         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13656                      ? AArch64ISD::GLD1_MERGE_ZERO
13657                      : AArch64ISD::GLDFF1_MERGE_ZERO;
13658 
13659       std::swap(Base, Offset);
13660     }
13661   }
13662 
13663   auto &TLI = DAG.getTargetLoweringInfo();
13664   if (!TLI.isTypeLegal(Base.getValueType()))
13665     return SDValue();
13666 
13667   // Some gather load variants allow unpacked offsets, but only as nxv2i32
13668   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13669   // nxv2i64. Legalize accordingly.
13670   if (!OnlyPackedOffsets &&
13671       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13672     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13673 
13674   // Return value type that is representable in hardware
13675   EVT HwRetVt = getSVEContainerType(RetVT);
13676 
13677   // Keep the original output value type around - this is needed to be able to
13678   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
13679   // values we want the integer equivalent, so just use HwRetVT.
13680   SDValue OutVT = DAG.getValueType(RetVT);
13681   if (RetVT.isFloatingPoint())
13682     OutVT = DAG.getValueType(HwRetVt);
13683 
13684   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
13685   SDValue Ops[] = {N->getOperand(0), // Chain
13686                    N->getOperand(2), // Pg
13687                    Base, Offset, OutVT};
13688 
13689   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
13690   SDValue LoadChain = SDValue(Load.getNode(), 1);
13691 
13692   if (RetVT.isInteger() && (RetVT != HwRetVt))
13693     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
13694 
13695   // If the original return value was FP, bitcast accordingly. Doing it here
13696   // means that we can avoid adding TableGen patterns for FPs.
13697   if (RetVT.isFloatingPoint())
13698     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
13699 
13700   return DAG.getMergeValues({Load, LoadChain}, DL);
13701 }
13702 
13703 static SDValue
13704 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13705                               SelectionDAG &DAG) {
13706   if (DCI.isBeforeLegalizeOps())
13707     return SDValue();
13708 
13709   SDLoc DL(N);
13710   SDValue Src = N->getOperand(0);
13711   unsigned Opc = Src->getOpcode();
13712 
13713   // Sign extend of an unsigned unpack -> signed unpack
13714   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
13715 
13716     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
13717                                                : AArch64ISD::SUNPKLO;
13718 
13719     // Push the sign extend to the operand of the unpack
13720     // This is necessary where, for example, the operand of the unpack
13721     // is another unpack:
13722     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
13723     // ->
13724     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
13725     // ->
13726     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
13727     SDValue ExtOp = Src->getOperand(0);
13728     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
13729     EVT EltTy = VT.getVectorElementType();
13730     (void)EltTy;
13731 
13732     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
13733            "Sign extending from an invalid type");
13734 
13735     EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13736                                  VT.getVectorElementType(),
13737                                  VT.getVectorElementCount() * 2);
13738 
13739     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
13740                               ExtOp, DAG.getValueType(ExtVT));
13741 
13742     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
13743   }
13744 
13745   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
13746   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
13747   unsigned NewOpc;
13748   unsigned MemVTOpNum = 4;
13749   switch (Opc) {
13750   case AArch64ISD::LD1_MERGE_ZERO:
13751     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
13752     MemVTOpNum = 3;
13753     break;
13754   case AArch64ISD::LDNF1_MERGE_ZERO:
13755     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
13756     MemVTOpNum = 3;
13757     break;
13758   case AArch64ISD::LDFF1_MERGE_ZERO:
13759     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
13760     MemVTOpNum = 3;
13761     break;
13762   case AArch64ISD::GLD1_MERGE_ZERO:
13763     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
13764     break;
13765   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
13766     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
13767     break;
13768   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
13769     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
13770     break;
13771   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
13772     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
13773     break;
13774   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
13775     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
13776     break;
13777   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
13778     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
13779     break;
13780   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
13781     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
13782     break;
13783   case AArch64ISD::GLDFF1_MERGE_ZERO:
13784     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
13785     break;
13786   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
13787     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
13788     break;
13789   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
13790     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
13791     break;
13792   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
13793     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
13794     break;
13795   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
13796     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
13797     break;
13798   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
13799     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
13800     break;
13801   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
13802     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
13803     break;
13804   case AArch64ISD::GLDNT1_MERGE_ZERO:
13805     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
13806     break;
13807   default:
13808     return SDValue();
13809   }
13810 
13811   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
13812   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
13813 
13814   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
13815     return SDValue();
13816 
13817   EVT DstVT = N->getValueType(0);
13818   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
13819 
13820   SmallVector<SDValue, 5> Ops;
13821   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
13822     Ops.push_back(Src->getOperand(I));
13823 
13824   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
13825   DCI.CombineTo(N, ExtLoad);
13826   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
13827 
13828   // Return N so it doesn't get rechecked
13829   return SDValue(N, 0);
13830 }
13831 
13832 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
13833 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
13834 /// != nxv2i32) do not need legalization.
13835 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
13836   const unsigned OffsetPos = 4;
13837   SDValue Offset = N->getOperand(OffsetPos);
13838 
13839   // Not an unpacked vector, bail out.
13840   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
13841     return SDValue();
13842 
13843   // Extend the unpacked offset vector to 64-bit lanes.
13844   SDLoc DL(N);
13845   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
13846   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13847   // Replace the offset operand with the 64-bit one.
13848   Ops[OffsetPos] = Offset;
13849 
13850   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13851 }
13852 
13853 /// Combines a node carrying the intrinsic
13854 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
13855 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
13856 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
13857 /// sve gather prefetch instruction with vector plus immediate addressing mode.
13858 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
13859                                                unsigned ScalarSizeInBytes) {
13860   const unsigned ImmPos = 4, OffsetPos = 3;
13861   // No need to combine the node if the immediate is valid...
13862   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
13863     return SDValue();
13864 
13865   // ...otherwise swap the offset base with the offset...
13866   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13867   std::swap(Ops[ImmPos], Ops[OffsetPos]);
13868   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
13869   // `aarch64_sve_prfb_gather_uxtw_index`.
13870   SDLoc DL(N);
13871   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
13872                            MVT::i64);
13873 
13874   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13875 }
13876 
13877 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
13878                                                  DAGCombinerInfo &DCI) const {
13879   SelectionDAG &DAG = DCI.DAG;
13880   switch (N->getOpcode()) {
13881   default:
13882     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
13883     break;
13884   case ISD::ADD:
13885   case ISD::SUB:
13886     return performAddSubLongCombine(N, DCI, DAG);
13887   case ISD::XOR:
13888     return performXorCombine(N, DAG, DCI, Subtarget);
13889   case ISD::MUL:
13890     return performMulCombine(N, DAG, DCI, Subtarget);
13891   case ISD::SINT_TO_FP:
13892   case ISD::UINT_TO_FP:
13893     return performIntToFpCombine(N, DAG, Subtarget);
13894   case ISD::FP_TO_SINT:
13895   case ISD::FP_TO_UINT:
13896     return performFpToIntCombine(N, DAG, DCI, Subtarget);
13897   case ISD::FDIV:
13898     return performFDivCombine(N, DAG, DCI, Subtarget);
13899   case ISD::OR:
13900     return performORCombine(N, DCI, Subtarget);
13901   case ISD::AND:
13902     return performANDCombine(N, DCI);
13903   case ISD::SRL:
13904     return performSRLCombine(N, DCI);
13905   case ISD::INTRINSIC_WO_CHAIN:
13906     return performIntrinsicCombine(N, DCI, Subtarget);
13907   case ISD::ANY_EXTEND:
13908   case ISD::ZERO_EXTEND:
13909   case ISD::SIGN_EXTEND:
13910     return performExtendCombine(N, DCI, DAG);
13911   case ISD::SIGN_EXTEND_INREG:
13912     return performSignExtendInRegCombine(N, DCI, DAG);
13913   case ISD::CONCAT_VECTORS:
13914     return performConcatVectorsCombine(N, DCI, DAG);
13915   case ISD::SELECT:
13916     return performSelectCombine(N, DCI);
13917   case ISD::VSELECT:
13918     return performVSelectCombine(N, DCI.DAG);
13919   case ISD::LOAD:
13920     if (performTBISimplification(N->getOperand(1), DCI, DAG))
13921       return SDValue(N, 0);
13922     break;
13923   case ISD::STORE:
13924     return performSTORECombine(N, DCI, DAG, Subtarget);
13925   case AArch64ISD::BRCOND:
13926     return performBRCONDCombine(N, DCI, DAG);
13927   case AArch64ISD::TBNZ:
13928   case AArch64ISD::TBZ:
13929     return performTBZCombine(N, DCI, DAG);
13930   case AArch64ISD::CSEL:
13931     return performCONDCombine(N, DCI, DAG, 2, 3);
13932   case AArch64ISD::DUP:
13933     return performPostLD1Combine(N, DCI, false);
13934   case AArch64ISD::NVCAST:
13935     return performNVCASTCombine(N);
13936   case ISD::INSERT_VECTOR_ELT:
13937     return performPostLD1Combine(N, DCI, true);
13938   case ISD::INTRINSIC_VOID:
13939   case ISD::INTRINSIC_W_CHAIN:
13940     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13941     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
13942       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
13943     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
13944       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
13945     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
13946       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
13947     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
13948       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
13949     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
13950     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
13951     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
13952     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
13953     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
13954     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
13955     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
13956     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
13957       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
13958     case Intrinsic::aarch64_neon_ld2:
13959     case Intrinsic::aarch64_neon_ld3:
13960     case Intrinsic::aarch64_neon_ld4:
13961     case Intrinsic::aarch64_neon_ld1x2:
13962     case Intrinsic::aarch64_neon_ld1x3:
13963     case Intrinsic::aarch64_neon_ld1x4:
13964     case Intrinsic::aarch64_neon_ld2lane:
13965     case Intrinsic::aarch64_neon_ld3lane:
13966     case Intrinsic::aarch64_neon_ld4lane:
13967     case Intrinsic::aarch64_neon_ld2r:
13968     case Intrinsic::aarch64_neon_ld3r:
13969     case Intrinsic::aarch64_neon_ld4r:
13970     case Intrinsic::aarch64_neon_st2:
13971     case Intrinsic::aarch64_neon_st3:
13972     case Intrinsic::aarch64_neon_st4:
13973     case Intrinsic::aarch64_neon_st1x2:
13974     case Intrinsic::aarch64_neon_st1x3:
13975     case Intrinsic::aarch64_neon_st1x4:
13976     case Intrinsic::aarch64_neon_st2lane:
13977     case Intrinsic::aarch64_neon_st3lane:
13978     case Intrinsic::aarch64_neon_st4lane:
13979       return performNEONPostLDSTCombine(N, DCI, DAG);
13980     case Intrinsic::aarch64_sve_ldnt1:
13981       return performLDNT1Combine(N, DAG);
13982     case Intrinsic::aarch64_sve_ld1rq:
13983       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
13984     case Intrinsic::aarch64_sve_ld1ro:
13985       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
13986     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
13987       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13988     case Intrinsic::aarch64_sve_ldnt1_gather:
13989       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13990     case Intrinsic::aarch64_sve_ldnt1_gather_index:
13991       return performGatherLoadCombine(N, DAG,
13992                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
13993     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
13994       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13995     case Intrinsic::aarch64_sve_ld1:
13996       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
13997     case Intrinsic::aarch64_sve_ldnf1:
13998       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
13999     case Intrinsic::aarch64_sve_ldff1:
14000       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
14001     case Intrinsic::aarch64_sve_st1:
14002       return performST1Combine(N, DAG);
14003     case Intrinsic::aarch64_sve_stnt1:
14004       return performSTNT1Combine(N, DAG);
14005     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
14006       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14007     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
14008       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14009     case Intrinsic::aarch64_sve_stnt1_scatter:
14010       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14011     case Intrinsic::aarch64_sve_stnt1_scatter_index:
14012       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
14013     case Intrinsic::aarch64_sve_ld1_gather:
14014       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
14015     case Intrinsic::aarch64_sve_ld1_gather_index:
14016       return performGatherLoadCombine(N, DAG,
14017                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
14018     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
14019       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
14020                                       /*OnlyPackedOffsets=*/false);
14021     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
14022       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
14023                                       /*OnlyPackedOffsets=*/false);
14024     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
14025       return performGatherLoadCombine(N, DAG,
14026                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
14027                                       /*OnlyPackedOffsets=*/false);
14028     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
14029       return performGatherLoadCombine(N, DAG,
14030                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
14031                                       /*OnlyPackedOffsets=*/false);
14032     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
14033       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
14034     case Intrinsic::aarch64_sve_ldff1_gather:
14035       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
14036     case Intrinsic::aarch64_sve_ldff1_gather_index:
14037       return performGatherLoadCombine(N, DAG,
14038                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
14039     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
14040       return performGatherLoadCombine(N, DAG,
14041                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
14042                                       /*OnlyPackedOffsets=*/false);
14043     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
14044       return performGatherLoadCombine(N, DAG,
14045                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
14046                                       /*OnlyPackedOffsets=*/false);
14047     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
14048       return performGatherLoadCombine(N, DAG,
14049                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
14050                                       /*OnlyPackedOffsets=*/false);
14051     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
14052       return performGatherLoadCombine(N, DAG,
14053                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
14054                                       /*OnlyPackedOffsets=*/false);
14055     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
14056       return performGatherLoadCombine(N, DAG,
14057                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
14058     case Intrinsic::aarch64_sve_st1_scatter:
14059       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
14060     case Intrinsic::aarch64_sve_st1_scatter_index:
14061       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
14062     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
14063       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
14064                                         /*OnlyPackedOffsets=*/false);
14065     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
14066       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
14067                                         /*OnlyPackedOffsets=*/false);
14068     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
14069       return performScatterStoreCombine(N, DAG,
14070                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
14071                                         /*OnlyPackedOffsets=*/false);
14072     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
14073       return performScatterStoreCombine(N, DAG,
14074                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
14075                                         /*OnlyPackedOffsets=*/false);
14076     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
14077       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
14078     case Intrinsic::aarch64_sve_tuple_get: {
14079       SDLoc DL(N);
14080       SDValue Chain = N->getOperand(0);
14081       SDValue Src1 = N->getOperand(2);
14082       SDValue Idx = N->getOperand(3);
14083 
14084       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14085       EVT ResVT = N->getValueType(0);
14086       uint64_t NumLanes = ResVT.getVectorElementCount().Min;
14087       SDValue Val =
14088           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1,
14089                       DAG.getConstant(IdxConst * NumLanes, DL, MVT::i32));
14090       return DAG.getMergeValues({Val, Chain}, DL);
14091     }
14092     case Intrinsic::aarch64_sve_tuple_set: {
14093       SDLoc DL(N);
14094       SDValue Chain = N->getOperand(0);
14095       SDValue Tuple = N->getOperand(2);
14096       SDValue Idx = N->getOperand(3);
14097       SDValue Vec = N->getOperand(4);
14098 
14099       EVT TupleVT = Tuple.getValueType();
14100       uint64_t TupleLanes = TupleVT.getVectorElementCount().Min;
14101 
14102       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14103       uint64_t NumLanes = Vec.getValueType().getVectorElementCount().Min;
14104 
14105       if ((TupleLanes % NumLanes) != 0)
14106         report_fatal_error("invalid tuple vector!");
14107 
14108       uint64_t NumVecs = TupleLanes / NumLanes;
14109 
14110       SmallVector<SDValue, 4> Opnds;
14111       for (unsigned I = 0; I < NumVecs; ++I) {
14112         if (I == IdxConst)
14113           Opnds.push_back(Vec);
14114         else {
14115           Opnds.push_back(
14116               DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, Vec.getValueType(), Tuple,
14117                           DAG.getConstant(I * NumLanes, DL, MVT::i32)));
14118         }
14119       }
14120       SDValue Concat =
14121           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
14122       return DAG.getMergeValues({Concat, Chain}, DL);
14123     }
14124     case Intrinsic::aarch64_sve_tuple_create2:
14125     case Intrinsic::aarch64_sve_tuple_create3:
14126     case Intrinsic::aarch64_sve_tuple_create4: {
14127       SDLoc DL(N);
14128       SDValue Chain = N->getOperand(0);
14129 
14130       SmallVector<SDValue, 4> Opnds;
14131       for (unsigned I = 2; I < N->getNumOperands(); ++I)
14132         Opnds.push_back(N->getOperand(I));
14133 
14134       EVT VT = Opnds[0].getValueType();
14135       EVT EltVT = VT.getVectorElementType();
14136       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
14137                                     VT.getVectorElementCount() *
14138                                         (N->getNumOperands() - 2));
14139       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
14140       return DAG.getMergeValues({Concat, Chain}, DL);
14141     }
14142     case Intrinsic::aarch64_sve_ld2:
14143     case Intrinsic::aarch64_sve_ld3:
14144     case Intrinsic::aarch64_sve_ld4: {
14145       SDLoc DL(N);
14146       SDValue Chain = N->getOperand(0);
14147       SDValue Mask = N->getOperand(2);
14148       SDValue BasePtr = N->getOperand(3);
14149       SDValue LoadOps[] = {Chain, Mask, BasePtr};
14150       unsigned IntrinsicID =
14151           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14152       SDValue Result =
14153           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
14154       return DAG.getMergeValues({Result, Chain}, DL);
14155     }
14156     default:
14157       break;
14158     }
14159     break;
14160   case ISD::GlobalAddress:
14161     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
14162   }
14163   return SDValue();
14164 }
14165 
14166 // Check if the return value is used as only a return value, as otherwise
14167 // we can't perform a tail-call. In particular, we need to check for
14168 // target ISD nodes that are returns and any other "odd" constructs
14169 // that the generic analysis code won't necessarily catch.
14170 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
14171                                                SDValue &Chain) const {
14172   if (N->getNumValues() != 1)
14173     return false;
14174   if (!N->hasNUsesOfValue(1, 0))
14175     return false;
14176 
14177   SDValue TCChain = Chain;
14178   SDNode *Copy = *N->use_begin();
14179   if (Copy->getOpcode() == ISD::CopyToReg) {
14180     // If the copy has a glue operand, we conservatively assume it isn't safe to
14181     // perform a tail call.
14182     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
14183         MVT::Glue)
14184       return false;
14185     TCChain = Copy->getOperand(0);
14186   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
14187     return false;
14188 
14189   bool HasRet = false;
14190   for (SDNode *Node : Copy->uses()) {
14191     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
14192       return false;
14193     HasRet = true;
14194   }
14195 
14196   if (!HasRet)
14197     return false;
14198 
14199   Chain = TCChain;
14200   return true;
14201 }
14202 
14203 // Return whether the an instruction can potentially be optimized to a tail
14204 // call. This will cause the optimizers to attempt to move, or duplicate,
14205 // return instructions to help enable tail call optimizations for this
14206 // instruction.
14207 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14208   return CI->isTailCall();
14209 }
14210 
14211 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
14212                                                    SDValue &Offset,
14213                                                    ISD::MemIndexedMode &AM,
14214                                                    bool &IsInc,
14215                                                    SelectionDAG &DAG) const {
14216   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
14217     return false;
14218 
14219   Base = Op->getOperand(0);
14220   // All of the indexed addressing mode instructions take a signed
14221   // 9 bit immediate offset.
14222   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
14223     int64_t RHSC = RHS->getSExtValue();
14224     if (Op->getOpcode() == ISD::SUB)
14225       RHSC = -(uint64_t)RHSC;
14226     if (!isInt<9>(RHSC))
14227       return false;
14228     IsInc = (Op->getOpcode() == ISD::ADD);
14229     Offset = Op->getOperand(1);
14230     return true;
14231   }
14232   return false;
14233 }
14234 
14235 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14236                                                       SDValue &Offset,
14237                                                       ISD::MemIndexedMode &AM,
14238                                                       SelectionDAG &DAG) const {
14239   EVT VT;
14240   SDValue Ptr;
14241   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14242     VT = LD->getMemoryVT();
14243     Ptr = LD->getBasePtr();
14244   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14245     VT = ST->getMemoryVT();
14246     Ptr = ST->getBasePtr();
14247   } else
14248     return false;
14249 
14250   bool IsInc;
14251   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
14252     return false;
14253   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
14254   return true;
14255 }
14256 
14257 bool AArch64TargetLowering::getPostIndexedAddressParts(
14258     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
14259     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
14260   EVT VT;
14261   SDValue Ptr;
14262   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14263     VT = LD->getMemoryVT();
14264     Ptr = LD->getBasePtr();
14265   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14266     VT = ST->getMemoryVT();
14267     Ptr = ST->getBasePtr();
14268   } else
14269     return false;
14270 
14271   bool IsInc;
14272   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
14273     return false;
14274   // Post-indexing updates the base, so it's not a valid transform
14275   // if that's not the same as the load's pointer.
14276   if (Ptr != Base)
14277     return false;
14278   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
14279   return true;
14280 }
14281 
14282 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
14283                                   SelectionDAG &DAG) {
14284   SDLoc DL(N);
14285   SDValue Op = N->getOperand(0);
14286 
14287   if (N->getValueType(0) != MVT::i16 ||
14288       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
14289     return;
14290 
14291   Op = SDValue(
14292       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
14293                          DAG.getUNDEF(MVT::i32), Op,
14294                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
14295       0);
14296   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
14297   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
14298 }
14299 
14300 static void ReplaceReductionResults(SDNode *N,
14301                                     SmallVectorImpl<SDValue> &Results,
14302                                     SelectionDAG &DAG, unsigned InterOp,
14303                                     unsigned AcrossOp) {
14304   EVT LoVT, HiVT;
14305   SDValue Lo, Hi;
14306   SDLoc dl(N);
14307   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
14308   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
14309   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
14310   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
14311   Results.push_back(SplitVal);
14312 }
14313 
14314 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
14315   SDLoc DL(N);
14316   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
14317   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
14318                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
14319                                        DAG.getConstant(64, DL, MVT::i64)));
14320   return std::make_pair(Lo, Hi);
14321 }
14322 
14323 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
14324     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14325   SDValue In = N->getOperand(0);
14326   EVT InVT = In.getValueType();
14327 
14328   // Common code will handle these just fine.
14329   if (!InVT.isScalableVector() || !InVT.isInteger())
14330     return;
14331 
14332   SDLoc DL(N);
14333   EVT VT = N->getValueType(0);
14334 
14335   // The following checks bail if this is not a halving operation.
14336 
14337   ElementCount ResEC = VT.getVectorElementCount();
14338 
14339   if (InVT.getVectorElementCount().Min != (ResEC.Min * 2))
14340     return;
14341 
14342   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
14343   if (!CIndex)
14344     return;
14345 
14346   unsigned Index = CIndex->getZExtValue();
14347   if ((Index != 0) && (Index != ResEC.Min))
14348     return;
14349 
14350   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
14351   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
14352 
14353   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
14354   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
14355 }
14356 
14357 // Create an even/odd pair of X registers holding integer value V.
14358 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
14359   SDLoc dl(V.getNode());
14360   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
14361   SDValue VHi = DAG.getAnyExtOrTrunc(
14362       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
14363       dl, MVT::i64);
14364   if (DAG.getDataLayout().isBigEndian())
14365     std::swap (VLo, VHi);
14366   SDValue RegClass =
14367       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
14368   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
14369   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
14370   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
14371   return SDValue(
14372       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
14373 }
14374 
14375 static void ReplaceCMP_SWAP_128Results(SDNode *N,
14376                                        SmallVectorImpl<SDValue> &Results,
14377                                        SelectionDAG &DAG,
14378                                        const AArch64Subtarget *Subtarget) {
14379   assert(N->getValueType(0) == MVT::i128 &&
14380          "AtomicCmpSwap on types less than 128 should be legal");
14381 
14382   if (Subtarget->hasLSE()) {
14383     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
14384     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
14385     SDValue Ops[] = {
14386         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
14387         createGPRPairNode(DAG, N->getOperand(3)), // Store value
14388         N->getOperand(1), // Ptr
14389         N->getOperand(0), // Chain in
14390     };
14391 
14392     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14393 
14394     unsigned Opcode;
14395     switch (MemOp->getOrdering()) {
14396     case AtomicOrdering::Monotonic:
14397       Opcode = AArch64::CASPX;
14398       break;
14399     case AtomicOrdering::Acquire:
14400       Opcode = AArch64::CASPAX;
14401       break;
14402     case AtomicOrdering::Release:
14403       Opcode = AArch64::CASPLX;
14404       break;
14405     case AtomicOrdering::AcquireRelease:
14406     case AtomicOrdering::SequentiallyConsistent:
14407       Opcode = AArch64::CASPALX;
14408       break;
14409     default:
14410       llvm_unreachable("Unexpected ordering!");
14411     }
14412 
14413     MachineSDNode *CmpSwap = DAG.getMachineNode(
14414         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
14415     DAG.setNodeMemRefs(CmpSwap, {MemOp});
14416 
14417     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
14418     if (DAG.getDataLayout().isBigEndian())
14419       std::swap(SubReg1, SubReg2);
14420     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
14421                                             SDValue(CmpSwap, 0));
14422     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
14423                                             SDValue(CmpSwap, 0));
14424     Results.push_back(
14425         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
14426     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
14427     return;
14428   }
14429 
14430   auto Desired = splitInt128(N->getOperand(2), DAG);
14431   auto New = splitInt128(N->getOperand(3), DAG);
14432   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
14433                    New.first,        New.second,    N->getOperand(0)};
14434   SDNode *CmpSwap = DAG.getMachineNode(
14435       AArch64::CMP_SWAP_128, SDLoc(N),
14436       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
14437 
14438   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14439   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
14440 
14441   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14442                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
14443   Results.push_back(SDValue(CmpSwap, 3));
14444 }
14445 
14446 void AArch64TargetLowering::ReplaceNodeResults(
14447     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14448   switch (N->getOpcode()) {
14449   default:
14450     llvm_unreachable("Don't know how to custom expand this");
14451   case ISD::BITCAST:
14452     ReplaceBITCASTResults(N, Results, DAG);
14453     return;
14454   case ISD::VECREDUCE_ADD:
14455   case ISD::VECREDUCE_SMAX:
14456   case ISD::VECREDUCE_SMIN:
14457   case ISD::VECREDUCE_UMAX:
14458   case ISD::VECREDUCE_UMIN:
14459     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
14460     return;
14461 
14462   case ISD::CTPOP:
14463     Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
14464     return;
14465   case AArch64ISD::SADDV:
14466     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
14467     return;
14468   case AArch64ISD::UADDV:
14469     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
14470     return;
14471   case AArch64ISD::SMINV:
14472     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
14473     return;
14474   case AArch64ISD::UMINV:
14475     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
14476     return;
14477   case AArch64ISD::SMAXV:
14478     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
14479     return;
14480   case AArch64ISD::UMAXV:
14481     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
14482     return;
14483   case ISD::FP_TO_UINT:
14484   case ISD::FP_TO_SINT:
14485     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
14486     // Let normal code take care of it by not adding anything to Results.
14487     return;
14488   case ISD::ATOMIC_CMP_SWAP:
14489     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
14490     return;
14491   case ISD::LOAD: {
14492     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
14493            "unexpected load's value type");
14494     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
14495     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
14496       // Non-volatile loads are optimized later in AArch64's load/store
14497       // optimizer.
14498       return;
14499     }
14500 
14501     SDValue Result = DAG.getMemIntrinsicNode(
14502         AArch64ISD::LDP, SDLoc(N),
14503         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
14504         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
14505         LoadNode->getMemOperand());
14506 
14507     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14508                                Result.getValue(0), Result.getValue(1));
14509     Results.append({Pair, Result.getValue(2) /* Chain */});
14510     return;
14511   }
14512   case ISD::EXTRACT_SUBVECTOR:
14513     ReplaceExtractSubVectorResults(N, Results, DAG);
14514     return;
14515   case ISD::INTRINSIC_WO_CHAIN: {
14516     EVT VT = N->getValueType(0);
14517     assert((VT == MVT::i8 || VT == MVT::i16) &&
14518            "custom lowering for unexpected type");
14519 
14520     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
14521     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14522     switch (IntID) {
14523     default:
14524       return;
14525     case Intrinsic::aarch64_sve_clasta_n: {
14526       SDLoc DL(N);
14527       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14528       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
14529                            N->getOperand(1), Op2, N->getOperand(3));
14530       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14531       return;
14532     }
14533     case Intrinsic::aarch64_sve_clastb_n: {
14534       SDLoc DL(N);
14535       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14536       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
14537                            N->getOperand(1), Op2, N->getOperand(3));
14538       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14539       return;
14540     }
14541     case Intrinsic::aarch64_sve_lasta: {
14542       SDLoc DL(N);
14543       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
14544                            N->getOperand(1), N->getOperand(2));
14545       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14546       return;
14547     }
14548     case Intrinsic::aarch64_sve_lastb: {
14549       SDLoc DL(N);
14550       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
14551                            N->getOperand(1), N->getOperand(2));
14552       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14553       return;
14554     }
14555     }
14556   }
14557   }
14558 }
14559 
14560 bool AArch64TargetLowering::useLoadStackGuardNode() const {
14561   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
14562     return TargetLowering::useLoadStackGuardNode();
14563   return true;
14564 }
14565 
14566 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
14567   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
14568   // reciprocal if there are three or more FDIVs.
14569   return 3;
14570 }
14571 
14572 TargetLoweringBase::LegalizeTypeAction
14573 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
14574   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
14575   // v4i16, v2i32 instead of to promote.
14576   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
14577       VT == MVT::v1f32)
14578     return TypeWidenVector;
14579 
14580   return TargetLoweringBase::getPreferredVectorAction(VT);
14581 }
14582 
14583 // Loads and stores less than 128-bits are already atomic; ones above that
14584 // are doomed anyway, so defer to the default libcall and blame the OS when
14585 // things go wrong.
14586 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14587   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14588   return Size == 128;
14589 }
14590 
14591 // Loads and stores less than 128-bits are already atomic; ones above that
14592 // are doomed anyway, so defer to the default libcall and blame the OS when
14593 // things go wrong.
14594 TargetLowering::AtomicExpansionKind
14595 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14596   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14597   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
14598 }
14599 
14600 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
14601 TargetLowering::AtomicExpansionKind
14602 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14603   if (AI->isFloatingPointOperation())
14604     return AtomicExpansionKind::CmpXChg;
14605 
14606   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14607   if (Size > 128) return AtomicExpansionKind::None;
14608   // Nand not supported in LSE.
14609   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
14610   // Leave 128 bits to LLSC.
14611   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
14612 }
14613 
14614 TargetLowering::AtomicExpansionKind
14615 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
14616     AtomicCmpXchgInst *AI) const {
14617   // If subtarget has LSE, leave cmpxchg intact for codegen.
14618   if (Subtarget->hasLSE())
14619     return AtomicExpansionKind::None;
14620   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14621   // implement cmpxchg without spilling. If the address being exchanged is also
14622   // on the stack and close enough to the spill slot, this can lead to a
14623   // situation where the monitor always gets cleared and the atomic operation
14624   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14625   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
14626     return AtomicExpansionKind::None;
14627   return AtomicExpansionKind::LLSC;
14628 }
14629 
14630 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14631                                              AtomicOrdering Ord) const {
14632   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14633   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14634   bool IsAcquire = isAcquireOrStronger(Ord);
14635 
14636   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
14637   // intrinsic must return {i64, i64} and we have to recombine them into a
14638   // single i128 here.
14639   if (ValTy->getPrimitiveSizeInBits() == 128) {
14640     Intrinsic::ID Int =
14641         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
14642     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
14643 
14644     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14645     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
14646 
14647     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14648     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14649     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14650     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14651     return Builder.CreateOr(
14652         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
14653   }
14654 
14655   Type *Tys[] = { Addr->getType() };
14656   Intrinsic::ID Int =
14657       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
14658   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
14659 
14660   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
14661 
14662   const DataLayout &DL = M->getDataLayout();
14663   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
14664   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
14665 
14666   return Builder.CreateBitCast(Trunc, EltTy);
14667 }
14668 
14669 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14670     IRBuilder<> &Builder) const {
14671   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14672   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
14673 }
14674 
14675 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
14676                                                    Value *Val, Value *Addr,
14677                                                    AtomicOrdering Ord) const {
14678   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14679   bool IsRelease = isReleaseOrStronger(Ord);
14680 
14681   // Since the intrinsics must have legal type, the i128 intrinsics take two
14682   // parameters: "i64, i64". We must marshal Val into the appropriate form
14683   // before the call.
14684   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
14685     Intrinsic::ID Int =
14686         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
14687     Function *Stxr = Intrinsic::getDeclaration(M, Int);
14688     Type *Int64Ty = Type::getInt64Ty(M->getContext());
14689 
14690     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
14691     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
14692     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14693     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
14694   }
14695 
14696   Intrinsic::ID Int =
14697       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
14698   Type *Tys[] = { Addr->getType() };
14699   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
14700 
14701   const DataLayout &DL = M->getDataLayout();
14702   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
14703   Val = Builder.CreateBitCast(Val, IntValTy);
14704 
14705   return Builder.CreateCall(Stxr,
14706                             {Builder.CreateZExtOrBitCast(
14707                                  Val, Stxr->getFunctionType()->getParamType(0)),
14708                              Addr});
14709 }
14710 
14711 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
14712     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14713   if (Ty->isArrayTy())
14714     return true;
14715 
14716   const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
14717   if (TySize.isScalable() && TySize.getKnownMinSize() > 128)
14718     return true;
14719 
14720   return false;
14721 }
14722 
14723 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
14724                                                             EVT) const {
14725   return false;
14726 }
14727 
14728 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
14729   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
14730   Function *ThreadPointerFunc =
14731       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
14732   return IRB.CreatePointerCast(
14733       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
14734                              Offset),
14735       IRB.getInt8PtrTy()->getPointerTo(0));
14736 }
14737 
14738 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
14739   // Android provides a fixed TLS slot for the stack cookie. See the definition
14740   // of TLS_SLOT_STACK_GUARD in
14741   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14742   if (Subtarget->isTargetAndroid())
14743     return UseTlsOffset(IRB, 0x28);
14744 
14745   // Fuchsia is similar.
14746   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
14747   if (Subtarget->isTargetFuchsia())
14748     return UseTlsOffset(IRB, -0x10);
14749 
14750   return TargetLowering::getIRStackGuard(IRB);
14751 }
14752 
14753 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
14754   // MSVC CRT provides functionalities for stack protection.
14755   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
14756     // MSVC CRT has a global variable holding security cookie.
14757     M.getOrInsertGlobal("__security_cookie",
14758                         Type::getInt8PtrTy(M.getContext()));
14759 
14760     // MSVC CRT has a function to validate security cookie.
14761     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
14762         "__security_check_cookie", Type::getVoidTy(M.getContext()),
14763         Type::getInt8PtrTy(M.getContext()));
14764     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
14765       F->setCallingConv(CallingConv::Win64);
14766       F->addAttribute(1, Attribute::AttrKind::InReg);
14767     }
14768     return;
14769   }
14770   TargetLowering::insertSSPDeclarations(M);
14771 }
14772 
14773 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
14774   // MSVC CRT has a global variable holding security cookie.
14775   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
14776     return M.getGlobalVariable("__security_cookie");
14777   return TargetLowering::getSDagStackGuard(M);
14778 }
14779 
14780 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
14781   // MSVC CRT has a function to validate security cookie.
14782   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
14783     return M.getFunction("__security_check_cookie");
14784   return TargetLowering::getSSPStackGuardCheck(M);
14785 }
14786 
14787 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
14788   // Android provides a fixed TLS slot for the SafeStack pointer. See the
14789   // definition of TLS_SLOT_SAFESTACK in
14790   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14791   if (Subtarget->isTargetAndroid())
14792     return UseTlsOffset(IRB, 0x48);
14793 
14794   // Fuchsia is similar.
14795   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
14796   if (Subtarget->isTargetFuchsia())
14797     return UseTlsOffset(IRB, -0x8);
14798 
14799   return TargetLowering::getSafeStackPointerLocation(IRB);
14800 }
14801 
14802 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
14803     const Instruction &AndI) const {
14804   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
14805   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
14806   // may be beneficial to sink in other cases, but we would have to check that
14807   // the cmp would not get folded into the br to form a cbz for these to be
14808   // beneficial.
14809   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
14810   if (!Mask)
14811     return false;
14812   return Mask->getValue().isPowerOf2();
14813 }
14814 
14815 bool AArch64TargetLowering::
14816     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
14817         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
14818         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
14819         SelectionDAG &DAG) const {
14820   // Does baseline recommend not to perform the fold by default?
14821   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
14822           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
14823     return false;
14824   // Else, if this is a vector shift, prefer 'shl'.
14825   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
14826 }
14827 
14828 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
14829                                               SDNode *N) const {
14830   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
14831       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
14832     return false;
14833   return true;
14834 }
14835 
14836 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14837   // Update IsSplitCSR in AArch64unctionInfo.
14838   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
14839   AFI->setIsSplitCSR(true);
14840 }
14841 
14842 void AArch64TargetLowering::insertCopiesSplitCSR(
14843     MachineBasicBlock *Entry,
14844     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14845   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
14846   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14847   if (!IStart)
14848     return;
14849 
14850   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14851   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14852   MachineBasicBlock::iterator MBBI = Entry->begin();
14853   for (const MCPhysReg *I = IStart; *I; ++I) {
14854     const TargetRegisterClass *RC = nullptr;
14855     if (AArch64::GPR64RegClass.contains(*I))
14856       RC = &AArch64::GPR64RegClass;
14857     else if (AArch64::FPR64RegClass.contains(*I))
14858       RC = &AArch64::FPR64RegClass;
14859     else
14860       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14861 
14862     Register NewVR = MRI->createVirtualRegister(RC);
14863     // Create copy from CSR to a virtual register.
14864     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14865     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14866     // nounwind. If we want to generalize this later, we may need to emit
14867     // CFI pseudo-instructions.
14868     assert(Entry->getParent()->getFunction().hasFnAttribute(
14869                Attribute::NoUnwind) &&
14870            "Function should be nounwind in insertCopiesSplitCSR!");
14871     Entry->addLiveIn(*I);
14872     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14873         .addReg(*I);
14874 
14875     // Insert the copy-back instructions right before the terminator.
14876     for (auto *Exit : Exits)
14877       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14878               TII->get(TargetOpcode::COPY), *I)
14879           .addReg(NewVR);
14880   }
14881 }
14882 
14883 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
14884   // Integer division on AArch64 is expensive. However, when aggressively
14885   // optimizing for code size, we prefer to use a div instruction, as it is
14886   // usually smaller than the alternative sequence.
14887   // The exception to this is vector division. Since AArch64 doesn't have vector
14888   // integer division, leaving the division as-is is a loss even in terms of
14889   // size, because it will have to be scalarized, while the alternative code
14890   // sequence can be performed in vector form.
14891   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
14892   return OptSize && !VT.isVector();
14893 }
14894 
14895 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
14896   // We want inc-of-add for scalars and sub-of-not for vectors.
14897   return VT.isScalarInteger();
14898 }
14899 
14900 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
14901   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
14902 }
14903 
14904 unsigned
14905 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
14906   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
14907     return getPointerTy(DL).getSizeInBits();
14908 
14909   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
14910 }
14911 
14912 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
14913   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14914   TargetLoweringBase::finalizeLowering(MF);
14915 }
14916 
14917 // Unlike X86, we let frame lowering assign offsets to all catch objects.
14918 bool AArch64TargetLowering::needsFixedCatchObjects() const {
14919   return false;
14920 }
14921 
14922 bool AArch64TargetLowering::shouldLocalize(
14923     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
14924   switch (MI.getOpcode()) {
14925   case TargetOpcode::G_GLOBAL_VALUE: {
14926     // On Darwin, TLS global vars get selected into function calls, which
14927     // we don't want localized, as they can get moved into the middle of a
14928     // another call sequence.
14929     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
14930     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
14931       return false;
14932     break;
14933   }
14934   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
14935   // localizable.
14936   case AArch64::ADRP:
14937   case AArch64::G_ADD_LOW:
14938     return true;
14939   default:
14940     break;
14941   }
14942   return TargetLoweringBase::shouldLocalize(MI, TTI);
14943 }
14944 
14945 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
14946   if (isa<ScalableVectorType>(Inst.getType()))
14947     return true;
14948 
14949   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
14950     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
14951       return true;
14952 
14953   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
14954     if (isa<ScalableVectorType>(AI->getAllocatedType()))
14955       return true;
14956   }
14957 
14958   return false;
14959 }
14960 
14961 // Return the largest legal scalable vector type that matches VT's element type.
14962 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
14963   assert(VT.isFixedLengthVector() &&
14964          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14965          "Expected legal fixed length vector!");
14966   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
14967   default:
14968     llvm_unreachable("unexpected element type for SVE container");
14969   case MVT::i8:
14970     return EVT(MVT::nxv16i8);
14971   case MVT::i16:
14972     return EVT(MVT::nxv8i16);
14973   case MVT::i32:
14974     return EVT(MVT::nxv4i32);
14975   case MVT::i64:
14976     return EVT(MVT::nxv2i64);
14977   case MVT::f16:
14978     return EVT(MVT::nxv8f16);
14979   case MVT::f32:
14980     return EVT(MVT::nxv4f32);
14981   case MVT::f64:
14982     return EVT(MVT::nxv2f64);
14983   }
14984 }
14985 
14986 // Return a PTRUE with active lanes corresponding to the extent of VT.
14987 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
14988                                                 EVT VT) {
14989   assert(VT.isFixedLengthVector() &&
14990          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14991          "Expected legal fixed length vector!");
14992 
14993   int PgPattern;
14994   switch (VT.getVectorNumElements()) {
14995   default:
14996     llvm_unreachable("unexpected element count for SVE predicate");
14997   case 1:
14998     PgPattern = AArch64SVEPredPattern::vl1;
14999     break;
15000   case 2:
15001     PgPattern = AArch64SVEPredPattern::vl2;
15002     break;
15003   case 4:
15004     PgPattern = AArch64SVEPredPattern::vl4;
15005     break;
15006   case 8:
15007     PgPattern = AArch64SVEPredPattern::vl8;
15008     break;
15009   case 16:
15010     PgPattern = AArch64SVEPredPattern::vl16;
15011     break;
15012   case 32:
15013     PgPattern = AArch64SVEPredPattern::vl32;
15014     break;
15015   case 64:
15016     PgPattern = AArch64SVEPredPattern::vl64;
15017     break;
15018   case 128:
15019     PgPattern = AArch64SVEPredPattern::vl128;
15020     break;
15021   case 256:
15022     PgPattern = AArch64SVEPredPattern::vl256;
15023     break;
15024   }
15025 
15026   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
15027   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
15028   // variants of instructions when available.
15029 
15030   MVT MaskVT;
15031   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15032   default:
15033     llvm_unreachable("unexpected element type for SVE predicate");
15034   case MVT::i8:
15035     MaskVT = MVT::nxv16i1;
15036     break;
15037   case MVT::i16:
15038   case MVT::f16:
15039     MaskVT = MVT::nxv8i1;
15040     break;
15041   case MVT::i32:
15042   case MVT::f32:
15043     MaskVT = MVT::nxv4i1;
15044     break;
15045   case MVT::i64:
15046   case MVT::f64:
15047     MaskVT = MVT::nxv2i1;
15048     break;
15049   }
15050 
15051   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
15052                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
15053 }
15054 
15055 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
15056                                              EVT VT) {
15057   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15058          "Expected legal scalable vector!");
15059   auto PredTy = VT.changeVectorElementType(MVT::i1);
15060   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
15061 }
15062 
15063 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
15064   if (VT.isFixedLengthVector())
15065     return getPredicateForFixedLengthVector(DAG, DL, VT);
15066 
15067   return getPredicateForScalableVector(DAG, DL, VT);
15068 }
15069 
15070 // Grow V to consume an entire SVE register.
15071 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15072   assert(VT.isScalableVector() &&
15073          "Expected to convert into a scalable vector!");
15074   assert(V.getValueType().isFixedLengthVector() &&
15075          "Expected a fixed length vector operand!");
15076   SDLoc DL(V);
15077   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15078   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
15079 }
15080 
15081 // Shrink V so it's just big enough to maintain a VT's worth of data.
15082 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15083   assert(VT.isFixedLengthVector() &&
15084          "Expected to convert into a fixed length vector!");
15085   assert(V.getValueType().isScalableVector() &&
15086          "Expected a scalable vector operand!");
15087   SDLoc DL(V);
15088   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15089   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
15090 }
15091 
15092 // Convert all fixed length vector loads larger than NEON to masked_loads.
15093 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
15094     SDValue Op, SelectionDAG &DAG) const {
15095   auto Load = cast<LoadSDNode>(Op);
15096 
15097   SDLoc DL(Op);
15098   EVT VT = Op.getValueType();
15099   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15100 
15101   auto NewLoad = DAG.getMaskedLoad(
15102       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
15103       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
15104       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
15105       Load->getExtensionType());
15106 
15107   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
15108   SDValue MergedValues[2] = {Result, Load->getChain()};
15109   return DAG.getMergeValues(MergedValues, DL);
15110 }
15111 
15112 // Convert all fixed length vector stores larger than NEON to masked_stores.
15113 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
15114     SDValue Op, SelectionDAG &DAG) const {
15115   auto Store = cast<StoreSDNode>(Op);
15116 
15117   SDLoc DL(Op);
15118   EVT VT = Store->getValue().getValueType();
15119   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15120 
15121   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
15122   return DAG.getMaskedStore(
15123       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
15124       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
15125       Store->getMemOperand(), Store->getAddressingMode(),
15126       Store->isTruncatingStore());
15127 }
15128 
15129 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
15130     SDValue Op, SelectionDAG &DAG) const {
15131   EVT VT = Op.getValueType();
15132   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
15133 
15134   SDLoc DL(Op);
15135   SDValue Val = Op.getOperand(0);
15136   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
15137   Val = convertToScalableVector(DAG, ContainerVT, Val);
15138 
15139   // Repeatedly truncate Val until the result is of the desired element type.
15140   switch (ContainerVT.getSimpleVT().SimpleTy) {
15141   default:
15142     llvm_unreachable("unimplemented container type");
15143   case MVT::nxv2i64:
15144     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
15145     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
15146     if (VT.getVectorElementType() == MVT::i32)
15147       break;
15148     LLVM_FALLTHROUGH;
15149   case MVT::nxv4i32:
15150     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
15151     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
15152     if (VT.getVectorElementType() == MVT::i16)
15153       break;
15154     LLVM_FALLTHROUGH;
15155   case MVT::nxv8i16:
15156     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
15157     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
15158     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
15159     break;
15160   }
15161 
15162   return convertFromScalableVector(DAG, VT, Val);
15163 }
15164 
15165 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
15166                                                    SelectionDAG &DAG,
15167                                                    unsigned NewOp) const {
15168   EVT VT = Op.getValueType();
15169   SDLoc DL(Op);
15170   auto Pg = getPredicateForVector(DAG, DL, VT);
15171 
15172   if (useSVEForFixedLengthVectorVT(VT)) {
15173     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15174 
15175     // Create list of operands by convereting existing ones to scalable types.
15176     SmallVector<SDValue, 4> Operands = {Pg};
15177     for (const SDValue &V : Op->op_values()) {
15178       if (isa<CondCodeSDNode>(V)) {
15179         Operands.push_back(V);
15180         continue;
15181       }
15182 
15183       assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
15184              "Only fixed length vectors are supported!");
15185       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
15186     }
15187 
15188     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
15189     return convertFromScalableVector(DAG, VT, ScalableRes);
15190   }
15191 
15192   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
15193 
15194   SmallVector<SDValue, 4> Operands = {Pg};
15195   for (const SDValue &V : Op->op_values()) {
15196     assert((isa<CondCodeSDNode>(V) || V.getValueType().isScalableVector()) &&
15197            "Only scalable vectors are supported!");
15198     Operands.push_back(V);
15199   }
15200 
15201   return DAG.getNode(NewOp, DL, VT, Operands);
15202 }
15203