xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp (revision 606d0e4a9a862a7b4e3469a084834ca0e888afa4)
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/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ObjCARCUtil.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/CodeGen/Analysis.h"
36 #include "llvm/CodeGen/CallingConvLower.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/RuntimeLibcalls.h"
46 #include "llvm/CodeGen/SelectionDAG.h"
47 #include "llvm/CodeGen/SelectionDAGNodes.h"
48 #include "llvm/CodeGen/TargetCallingConv.h"
49 #include "llvm/CodeGen/TargetInstrInfo.h"
50 #include "llvm/CodeGen/ValueTypes.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/GetElementPtrTypeIterator.h"
58 #include "llvm/IR/GlobalValue.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/Intrinsics.h"
64 #include "llvm/IR/IntrinsicsAArch64.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/OperandTraits.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCRegisterInfo.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/CodeGen.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Compiler.h"
76 #include "llvm/Support/Debug.h"
77 #include "llvm/Support/ErrorHandling.h"
78 #include "llvm/Support/KnownBits.h"
79 #include "llvm/Support/MachineValueType.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Target/TargetMachine.h"
83 #include "llvm/Target/TargetOptions.h"
84 #include <algorithm>
85 #include <bitset>
86 #include <cassert>
87 #include <cctype>
88 #include <cstdint>
89 #include <cstdlib>
90 #include <iterator>
91 #include <limits>
92 #include <tuple>
93 #include <utility>
94 #include <vector>
95 
96 using namespace llvm;
97 using namespace llvm::PatternMatch;
98 
99 #define DEBUG_TYPE "aarch64-lower"
100 
101 STATISTIC(NumTailCalls, "Number of tail calls");
102 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
103 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
104 
105 // FIXME: The necessary dtprel relocations don't seem to be supported
106 // well in the GNU bfd and gold linkers at the moment. Therefore, by
107 // default, for now, fall back to GeneralDynamic code generation.
108 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109     "aarch64-elf-ldtls-generation", cl::Hidden,
110     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111     cl::init(false));
112 
113 static cl::opt<bool>
114 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115                          cl::desc("Enable AArch64 logical imm instruction "
116                                   "optimization"),
117                          cl::init(true));
118 
119 // Temporary option added for the purpose of testing functionality added
120 // to DAGCombiner.cpp in D92230. It is expected that this can be removed
121 // in future when both implementations will be based off MGATHER rather
122 // than the GLD1 nodes added for the SVE gather load intrinsics.
123 static cl::opt<bool>
124 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
125                                 cl::desc("Combine extends of AArch64 masked "
126                                          "gather intrinsics"),
127                                 cl::init(true));
128 
129 /// Value type used for condition codes.
130 static const MVT MVT_CC = MVT::i32;
131 
132 static inline EVT getPackedSVEVectorVT(EVT VT) {
133   switch (VT.getSimpleVT().SimpleTy) {
134   default:
135     llvm_unreachable("unexpected element type for vector");
136   case MVT::i8:
137     return MVT::nxv16i8;
138   case MVT::i16:
139     return MVT::nxv8i16;
140   case MVT::i32:
141     return MVT::nxv4i32;
142   case MVT::i64:
143     return MVT::nxv2i64;
144   case MVT::f16:
145     return MVT::nxv8f16;
146   case MVT::f32:
147     return MVT::nxv4f32;
148   case MVT::f64:
149     return MVT::nxv2f64;
150   case MVT::bf16:
151     return MVT::nxv8bf16;
152   }
153 }
154 
155 // NOTE: Currently there's only a need to return integer vector types. If this
156 // changes then just add an extra "type" parameter.
157 static inline EVT getPackedSVEVectorVT(ElementCount EC) {
158   switch (EC.getKnownMinValue()) {
159   default:
160     llvm_unreachable("unexpected element count for vector");
161   case 16:
162     return MVT::nxv16i8;
163   case 8:
164     return MVT::nxv8i16;
165   case 4:
166     return MVT::nxv4i32;
167   case 2:
168     return MVT::nxv2i64;
169   }
170 }
171 
172 static inline EVT getPromotedVTForPredicate(EVT VT) {
173   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
174          "Expected scalable predicate vector type!");
175   switch (VT.getVectorMinNumElements()) {
176   default:
177     llvm_unreachable("unexpected element count for vector");
178   case 2:
179     return MVT::nxv2i64;
180   case 4:
181     return MVT::nxv4i32;
182   case 8:
183     return MVT::nxv8i16;
184   case 16:
185     return MVT::nxv16i8;
186   }
187 }
188 
189 /// Returns true if VT's elements occupy the lowest bit positions of its
190 /// associated register class without any intervening space.
191 ///
192 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
193 /// same register class, but only nxv8f16 can be treated as a packed vector.
194 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
195   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
196          "Expected legal vector type!");
197   return VT.isFixedLengthVector() ||
198          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
199 }
200 
201 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
202 // predicate and end with a passthru value matching the result type.
203 static bool isMergePassthruOpcode(unsigned Opc) {
204   switch (Opc) {
205   default:
206     return false;
207   case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
208   case AArch64ISD::BSWAP_MERGE_PASSTHRU:
209   case AArch64ISD::REVH_MERGE_PASSTHRU:
210   case AArch64ISD::REVW_MERGE_PASSTHRU:
211   case AArch64ISD::CTLZ_MERGE_PASSTHRU:
212   case AArch64ISD::CTPOP_MERGE_PASSTHRU:
213   case AArch64ISD::DUP_MERGE_PASSTHRU:
214   case AArch64ISD::ABS_MERGE_PASSTHRU:
215   case AArch64ISD::NEG_MERGE_PASSTHRU:
216   case AArch64ISD::FNEG_MERGE_PASSTHRU:
217   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
218   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
219   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
220   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
221   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
222   case AArch64ISD::FRINT_MERGE_PASSTHRU:
223   case AArch64ISD::FROUND_MERGE_PASSTHRU:
224   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
225   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
226   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
227   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
228   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
229   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
230   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
231   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
232   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
233   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
234   case AArch64ISD::FABS_MERGE_PASSTHRU:
235     return true;
236   }
237 }
238 
239 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
240                                              const AArch64Subtarget &STI)
241     : TargetLowering(TM), Subtarget(&STI) {
242   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
243   // we have to make something up. Arbitrarily, choose ZeroOrOne.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // When comparing vectors the result sets the different elements in the
246   // vector to all-one or all-zero.
247   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 
249   // Set up the register classes.
250   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
251   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
252 
253   if (Subtarget->hasLS64()) {
254     addRegisterClass(MVT::i64x8, &AArch64::GPR64x8ClassRegClass);
255     setOperationAction(ISD::LOAD, MVT::i64x8, Custom);
256     setOperationAction(ISD::STORE, MVT::i64x8, Custom);
257   }
258 
259   if (Subtarget->hasFPARMv8()) {
260     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
261     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
262     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
263     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
264     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
265   }
266 
267   if (Subtarget->hasNEON()) {
268     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
269     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
270     // Someone set us up the NEON.
271     addDRTypeForNEON(MVT::v2f32);
272     addDRTypeForNEON(MVT::v8i8);
273     addDRTypeForNEON(MVT::v4i16);
274     addDRTypeForNEON(MVT::v2i32);
275     addDRTypeForNEON(MVT::v1i64);
276     addDRTypeForNEON(MVT::v1f64);
277     addDRTypeForNEON(MVT::v4f16);
278     if (Subtarget->hasBF16())
279       addDRTypeForNEON(MVT::v4bf16);
280 
281     addQRTypeForNEON(MVT::v4f32);
282     addQRTypeForNEON(MVT::v2f64);
283     addQRTypeForNEON(MVT::v16i8);
284     addQRTypeForNEON(MVT::v8i16);
285     addQRTypeForNEON(MVT::v4i32);
286     addQRTypeForNEON(MVT::v2i64);
287     addQRTypeForNEON(MVT::v8f16);
288     if (Subtarget->hasBF16())
289       addQRTypeForNEON(MVT::v8bf16);
290   }
291 
292   if (Subtarget->hasSVE()) {
293     // Add legal sve predicate types
294     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
295     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
296     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
297     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
298 
299     // Add legal sve data types
300     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
301     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
302     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
303     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
304 
305     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
306     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
307     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
308     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
309     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
310     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
311 
312     if (Subtarget->hasBF16()) {
313       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
314       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
315       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
316     }
317 
318     if (Subtarget->useSVEForFixedLengthVectors()) {
319       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
320         if (useSVEForFixedLengthVectorVT(VT))
321           addRegisterClass(VT, &AArch64::ZPRRegClass);
322 
323       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
324         if (useSVEForFixedLengthVectorVT(VT))
325           addRegisterClass(VT, &AArch64::ZPRRegClass);
326     }
327 
328     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
329       setOperationAction(ISD::SADDSAT, VT, Legal);
330       setOperationAction(ISD::UADDSAT, VT, Legal);
331       setOperationAction(ISD::SSUBSAT, VT, Legal);
332       setOperationAction(ISD::USUBSAT, VT, Legal);
333       setOperationAction(ISD::UREM, VT, Expand);
334       setOperationAction(ISD::SREM, VT, Expand);
335       setOperationAction(ISD::SDIVREM, VT, Expand);
336       setOperationAction(ISD::UDIVREM, VT, Expand);
337     }
338 
339     for (auto VT :
340          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
341            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
342       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
343 
344     for (auto VT :
345          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
346            MVT::nxv2f64 }) {
347       setCondCodeAction(ISD::SETO, VT, Expand);
348       setCondCodeAction(ISD::SETOLT, VT, Expand);
349       setCondCodeAction(ISD::SETLT, VT, Expand);
350       setCondCodeAction(ISD::SETOLE, VT, Expand);
351       setCondCodeAction(ISD::SETLE, VT, Expand);
352       setCondCodeAction(ISD::SETULT, VT, Expand);
353       setCondCodeAction(ISD::SETULE, VT, Expand);
354       setCondCodeAction(ISD::SETUGE, VT, Expand);
355       setCondCodeAction(ISD::SETUGT, VT, Expand);
356       setCondCodeAction(ISD::SETUEQ, VT, Expand);
357       setCondCodeAction(ISD::SETUNE, VT, Expand);
358 
359       setOperationAction(ISD::FREM, VT, Expand);
360       setOperationAction(ISD::FPOW, VT, Expand);
361       setOperationAction(ISD::FPOWI, VT, Expand);
362       setOperationAction(ISD::FCOS, VT, Expand);
363       setOperationAction(ISD::FSIN, VT, Expand);
364       setOperationAction(ISD::FSINCOS, VT, Expand);
365       setOperationAction(ISD::FEXP, VT, Expand);
366       setOperationAction(ISD::FEXP2, VT, Expand);
367       setOperationAction(ISD::FLOG, VT, Expand);
368       setOperationAction(ISD::FLOG2, VT, Expand);
369       setOperationAction(ISD::FLOG10, VT, Expand);
370     }
371   }
372 
373   // Compute derived properties from the register classes
374   computeRegisterProperties(Subtarget->getRegisterInfo());
375 
376   // Provide all sorts of operation actions
377   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
378   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
379   setOperationAction(ISD::SETCC, MVT::i32, Custom);
380   setOperationAction(ISD::SETCC, MVT::i64, Custom);
381   setOperationAction(ISD::SETCC, MVT::f16, Custom);
382   setOperationAction(ISD::SETCC, MVT::f32, Custom);
383   setOperationAction(ISD::SETCC, MVT::f64, Custom);
384   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
385   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
386   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
387   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
388   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
389   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
390   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
391   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
392   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
393   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
394   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
395   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
396   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
397   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
398   setOperationAction(ISD::SELECT, MVT::i32, Custom);
399   setOperationAction(ISD::SELECT, MVT::i64, Custom);
400   setOperationAction(ISD::SELECT, MVT::f16, Custom);
401   setOperationAction(ISD::SELECT, MVT::f32, Custom);
402   setOperationAction(ISD::SELECT, MVT::f64, Custom);
403   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
404   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
405   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
406   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
407   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
408   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
409   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
410 
411   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
412   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
413   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
414 
415   setOperationAction(ISD::FREM, MVT::f32, Expand);
416   setOperationAction(ISD::FREM, MVT::f64, Expand);
417   setOperationAction(ISD::FREM, MVT::f80, Expand);
418 
419   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
420 
421   // Custom lowering hooks are needed for XOR
422   // to fold it into CSINC/CSINV.
423   setOperationAction(ISD::XOR, MVT::i32, Custom);
424   setOperationAction(ISD::XOR, MVT::i64, Custom);
425 
426   // Virtually no operation on f128 is legal, but LLVM can't expand them when
427   // there's a valid register class, so we need custom operations in most cases.
428   setOperationAction(ISD::FABS, MVT::f128, Expand);
429   setOperationAction(ISD::FADD, MVT::f128, LibCall);
430   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
431   setOperationAction(ISD::FCOS, MVT::f128, Expand);
432   setOperationAction(ISD::FDIV, MVT::f128, LibCall);
433   setOperationAction(ISD::FMA, MVT::f128, Expand);
434   setOperationAction(ISD::FMUL, MVT::f128, LibCall);
435   setOperationAction(ISD::FNEG, MVT::f128, Expand);
436   setOperationAction(ISD::FPOW, MVT::f128, Expand);
437   setOperationAction(ISD::FREM, MVT::f128, Expand);
438   setOperationAction(ISD::FRINT, MVT::f128, Expand);
439   setOperationAction(ISD::FSIN, MVT::f128, Expand);
440   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
441   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
442   setOperationAction(ISD::FSUB, MVT::f128, LibCall);
443   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
444   setOperationAction(ISD::SETCC, MVT::f128, Custom);
445   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
446   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
447   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
448   setOperationAction(ISD::SELECT, MVT::f128, Custom);
449   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
450   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
451 
452   // Lowering for many of the conversions is actually specified by the non-f128
453   // type. The LowerXXX function will be trivial when f128 isn't involved.
454   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
455   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
456   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
457   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
458   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
459   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
460   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
461   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
462   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
463   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
464   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
465   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
466   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
467   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
468   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
469   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
470   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
471   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
472   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
473   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
474   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
475   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
476   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
477   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
478   setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
479   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
480   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
481   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
482   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
483   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
484 
485   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
486   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
487   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
488   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
489 
490   // Variable arguments.
491   setOperationAction(ISD::VASTART, MVT::Other, Custom);
492   setOperationAction(ISD::VAARG, MVT::Other, Custom);
493   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
494   setOperationAction(ISD::VAEND, MVT::Other, Expand);
495 
496   // Variable-sized objects.
497   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
498   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
499 
500   if (Subtarget->isTargetWindows())
501     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
502   else
503     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
504 
505   // Constant pool entries
506   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
507 
508   // BlockAddress
509   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
510 
511   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
512   setOperationAction(ISD::ADDC, MVT::i32, Custom);
513   setOperationAction(ISD::ADDE, MVT::i32, Custom);
514   setOperationAction(ISD::SUBC, MVT::i32, Custom);
515   setOperationAction(ISD::SUBE, MVT::i32, Custom);
516   setOperationAction(ISD::ADDC, MVT::i64, Custom);
517   setOperationAction(ISD::ADDE, MVT::i64, Custom);
518   setOperationAction(ISD::SUBC, MVT::i64, Custom);
519   setOperationAction(ISD::SUBE, MVT::i64, Custom);
520 
521   // AArch64 lacks both left-rotate and popcount instructions.
522   setOperationAction(ISD::ROTL, MVT::i32, Expand);
523   setOperationAction(ISD::ROTL, MVT::i64, Expand);
524   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
525     setOperationAction(ISD::ROTL, VT, Expand);
526     setOperationAction(ISD::ROTR, VT, Expand);
527   }
528 
529   // AArch64 doesn't have i32 MULH{S|U}.
530   setOperationAction(ISD::MULHU, MVT::i32, Expand);
531   setOperationAction(ISD::MULHS, MVT::i32, Expand);
532 
533   // AArch64 doesn't have {U|S}MUL_LOHI.
534   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
535   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
536 
537   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
538   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
539   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
540 
541   setOperationAction(ISD::ABS, MVT::i32, Custom);
542   setOperationAction(ISD::ABS, MVT::i64, Custom);
543 
544   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
545   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
546   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
547     setOperationAction(ISD::SDIVREM, VT, Expand);
548     setOperationAction(ISD::UDIVREM, VT, Expand);
549   }
550   setOperationAction(ISD::SREM, MVT::i32, Expand);
551   setOperationAction(ISD::SREM, MVT::i64, Expand);
552   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
553   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
554   setOperationAction(ISD::UREM, MVT::i32, Expand);
555   setOperationAction(ISD::UREM, MVT::i64, Expand);
556 
557   // Custom lower Add/Sub/Mul with overflow.
558   setOperationAction(ISD::SADDO, MVT::i32, Custom);
559   setOperationAction(ISD::SADDO, MVT::i64, Custom);
560   setOperationAction(ISD::UADDO, MVT::i32, Custom);
561   setOperationAction(ISD::UADDO, MVT::i64, Custom);
562   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
563   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
564   setOperationAction(ISD::USUBO, MVT::i32, Custom);
565   setOperationAction(ISD::USUBO, MVT::i64, Custom);
566   setOperationAction(ISD::SMULO, MVT::i32, Custom);
567   setOperationAction(ISD::SMULO, MVT::i64, Custom);
568   setOperationAction(ISD::UMULO, MVT::i32, Custom);
569   setOperationAction(ISD::UMULO, MVT::i64, Custom);
570 
571   setOperationAction(ISD::FSIN, MVT::f32, Expand);
572   setOperationAction(ISD::FSIN, MVT::f64, Expand);
573   setOperationAction(ISD::FCOS, MVT::f32, Expand);
574   setOperationAction(ISD::FCOS, MVT::f64, Expand);
575   setOperationAction(ISD::FPOW, MVT::f32, Expand);
576   setOperationAction(ISD::FPOW, MVT::f64, Expand);
577   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
578   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
579   if (Subtarget->hasFullFP16())
580     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
581   else
582     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
583 
584   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
585   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
586   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
587   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
588   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
589   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
590   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
591   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
592   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
593   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
594   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
595   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
596   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
597   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
598   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
599   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
600   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
601   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
602   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
603   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
604   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
605   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
606   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
607   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
608   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
609   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
610   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
611   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
612   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
613   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
614   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
615   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
616   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
617 
618   if (!Subtarget->hasFullFP16()) {
619     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
620     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
621     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
622     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
623     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
624     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
625     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
626     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
627     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
628     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
629     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
630     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
631     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
632     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
633     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
634     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
635     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
636     setOperationAction(ISD::FROUNDEVEN,  MVT::f16,  Promote);
637     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
638     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
639     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
640     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
641     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
642 
643     // promote v4f16 to v4f32 when that is known to be safe.
644     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
645     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
646     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
647     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
648     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
649     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
650     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
651     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
652 
653     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
654     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
655     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
656     setOperationAction(ISD::FROUNDEVEN,  MVT::v4f16, Expand);
657     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
658     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
659     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
660     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
661     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
662     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
663     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
664     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
665     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
666     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
667     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
668     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
669 
670     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
671     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
672     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
673     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
674     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
675     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
676     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
677     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
678     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
679     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
680     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
681     setOperationAction(ISD::FROUNDEVEN,  MVT::v8f16, Expand);
682     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
683     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
684     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
685     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
686     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
687     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
688     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
689     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
690     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
691   }
692 
693   // AArch64 has implementations of a lot of rounding-like FP operations.
694   for (MVT Ty : {MVT::f32, MVT::f64}) {
695     setOperationAction(ISD::FFLOOR, Ty, Legal);
696     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
697     setOperationAction(ISD::FCEIL, Ty, Legal);
698     setOperationAction(ISD::FRINT, Ty, Legal);
699     setOperationAction(ISD::FTRUNC, Ty, Legal);
700     setOperationAction(ISD::FROUND, Ty, Legal);
701     setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
702     setOperationAction(ISD::FMINNUM, Ty, Legal);
703     setOperationAction(ISD::FMAXNUM, Ty, Legal);
704     setOperationAction(ISD::FMINIMUM, Ty, Legal);
705     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
706     setOperationAction(ISD::LROUND, Ty, Legal);
707     setOperationAction(ISD::LLROUND, Ty, Legal);
708     setOperationAction(ISD::LRINT, Ty, Legal);
709     setOperationAction(ISD::LLRINT, Ty, Legal);
710   }
711 
712   if (Subtarget->hasFullFP16()) {
713     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
714     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
715     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
716     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
717     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
718     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
719     setOperationAction(ISD::FROUNDEVEN,  MVT::f16, Legal);
720     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
721     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
722     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
723     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
724   }
725 
726   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
727 
728   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
729   setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
730 
731   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
732   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
733   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
734   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
735   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
736 
737   // Generate outline atomics library calls only if LSE was not specified for
738   // subtarget
739   if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
740     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
741     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
742     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
743     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
744     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
745     setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
746     setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
747     setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
748     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
749     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
750     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
751     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
752     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
753     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
754     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
755     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
756     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
757     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
758     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
759     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
760     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
761     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
762     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
763     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
764     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
765 #define LCALLNAMES(A, B, N)                                                    \
766   setLibcallName(A##N##_RELAX, #B #N "_relax");                                \
767   setLibcallName(A##N##_ACQ, #B #N "_acq");                                    \
768   setLibcallName(A##N##_REL, #B #N "_rel");                                    \
769   setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
770 #define LCALLNAME4(A, B)                                                       \
771   LCALLNAMES(A, B, 1)                                                          \
772   LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
773 #define LCALLNAME5(A, B)                                                       \
774   LCALLNAMES(A, B, 1)                                                          \
775   LCALLNAMES(A, B, 2)                                                          \
776   LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
777     LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
778     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
779     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
780     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
781     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
782     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
783 #undef LCALLNAMES
784 #undef LCALLNAME4
785 #undef LCALLNAME5
786   }
787 
788   // 128-bit loads and stores can be done without expanding
789   setOperationAction(ISD::LOAD, MVT::i128, Custom);
790   setOperationAction(ISD::STORE, MVT::i128, Custom);
791 
792   // Aligned 128-bit loads and stores are single-copy atomic according to the
793   // v8.4a spec.
794   if (Subtarget->hasLSE2()) {
795     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
796     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
797   }
798 
799   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
800   // custom lowering, as there are no un-paired non-temporal stores and
801   // legalization will break up 256 bit inputs.
802   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
803   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
804   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
805   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
806   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
807   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
808   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
809 
810   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
811   // This requires the Performance Monitors extension.
812   if (Subtarget->hasPerfMon())
813     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
814 
815   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
816       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
817     // Issue __sincos_stret if available.
818     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
819     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
820   } else {
821     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
822     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
823   }
824 
825   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
826     // MSVCRT doesn't have powi; fall back to pow
827     setLibcallName(RTLIB::POWI_F32, nullptr);
828     setLibcallName(RTLIB::POWI_F64, nullptr);
829   }
830 
831   // Make floating-point constants legal for the large code model, so they don't
832   // become loads from the constant pool.
833   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
834     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
835     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
836   }
837 
838   // AArch64 does not have floating-point extending loads, i1 sign-extending
839   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
840   for (MVT VT : MVT::fp_valuetypes()) {
841     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
842     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
843     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
844     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
845   }
846   for (MVT VT : MVT::integer_valuetypes())
847     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
848 
849   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
850   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
851   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
852   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
853   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
854   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
855   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
856 
857   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
858   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
859   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
860 
861   // Indexed loads and stores are supported.
862   for (unsigned im = (unsigned)ISD::PRE_INC;
863        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
864     setIndexedLoadAction(im, MVT::i8, Legal);
865     setIndexedLoadAction(im, MVT::i16, Legal);
866     setIndexedLoadAction(im, MVT::i32, Legal);
867     setIndexedLoadAction(im, MVT::i64, Legal);
868     setIndexedLoadAction(im, MVT::f64, Legal);
869     setIndexedLoadAction(im, MVT::f32, Legal);
870     setIndexedLoadAction(im, MVT::f16, Legal);
871     setIndexedLoadAction(im, MVT::bf16, Legal);
872     setIndexedStoreAction(im, MVT::i8, Legal);
873     setIndexedStoreAction(im, MVT::i16, Legal);
874     setIndexedStoreAction(im, MVT::i32, Legal);
875     setIndexedStoreAction(im, MVT::i64, Legal);
876     setIndexedStoreAction(im, MVT::f64, Legal);
877     setIndexedStoreAction(im, MVT::f32, Legal);
878     setIndexedStoreAction(im, MVT::f16, Legal);
879     setIndexedStoreAction(im, MVT::bf16, Legal);
880   }
881 
882   // Trap.
883   setOperationAction(ISD::TRAP, MVT::Other, Legal);
884   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
885   setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
886 
887   // We combine OR nodes for bitfield operations.
888   setTargetDAGCombine(ISD::OR);
889   // Try to create BICs for vector ANDs.
890   setTargetDAGCombine(ISD::AND);
891 
892   // Vector add and sub nodes may conceal a high-half opportunity.
893   // Also, try to fold ADD into CSINC/CSINV..
894   setTargetDAGCombine(ISD::ADD);
895   setTargetDAGCombine(ISD::ABS);
896   setTargetDAGCombine(ISD::SUB);
897   setTargetDAGCombine(ISD::XOR);
898   setTargetDAGCombine(ISD::SINT_TO_FP);
899   setTargetDAGCombine(ISD::UINT_TO_FP);
900 
901   setTargetDAGCombine(ISD::FP_TO_SINT);
902   setTargetDAGCombine(ISD::FP_TO_UINT);
903   setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
904   setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
905   setTargetDAGCombine(ISD::FDIV);
906 
907   // Try and combine setcc with csel
908   setTargetDAGCombine(ISD::SETCC);
909 
910   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
911 
912   setTargetDAGCombine(ISD::ANY_EXTEND);
913   setTargetDAGCombine(ISD::ZERO_EXTEND);
914   setTargetDAGCombine(ISD::SIGN_EXTEND);
915   setTargetDAGCombine(ISD::VECTOR_SPLICE);
916   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
917   setTargetDAGCombine(ISD::TRUNCATE);
918   setTargetDAGCombine(ISD::CONCAT_VECTORS);
919   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
920   setTargetDAGCombine(ISD::STORE);
921   if (Subtarget->supportsAddressTopByteIgnored())
922     setTargetDAGCombine(ISD::LOAD);
923 
924   setTargetDAGCombine(ISD::MUL);
925 
926   setTargetDAGCombine(ISD::SELECT);
927   setTargetDAGCombine(ISD::VSELECT);
928 
929   setTargetDAGCombine(ISD::INTRINSIC_VOID);
930   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
931   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
932   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
933   setTargetDAGCombine(ISD::VECREDUCE_ADD);
934   setTargetDAGCombine(ISD::STEP_VECTOR);
935 
936   setTargetDAGCombine(ISD::FP_EXTEND);
937 
938   setTargetDAGCombine(ISD::GlobalAddress);
939 
940   // In case of strict alignment, avoid an excessive number of byte wide stores.
941   MaxStoresPerMemsetOptSize = 8;
942   MaxStoresPerMemset =
943       Subtarget->requiresStrictAlign() ? MaxStoresPerMemsetOptSize : 32;
944 
945   MaxGluedStoresPerMemcpy = 4;
946   MaxStoresPerMemcpyOptSize = 4;
947   MaxStoresPerMemcpy =
948       Subtarget->requiresStrictAlign() ? MaxStoresPerMemcpyOptSize : 16;
949 
950   MaxStoresPerMemmoveOptSize = 4;
951   MaxStoresPerMemmove = 4;
952 
953   MaxLoadsPerMemcmpOptSize = 4;
954   MaxLoadsPerMemcmp =
955       Subtarget->requiresStrictAlign() ? MaxLoadsPerMemcmpOptSize : 8;
956 
957   setStackPointerRegisterToSaveRestore(AArch64::SP);
958 
959   setSchedulingPreference(Sched::Hybrid);
960 
961   EnableExtLdPromotion = true;
962 
963   // Set required alignment.
964   setMinFunctionAlignment(Align(4));
965   // Set preferred alignments.
966   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
967   setMaxBytesForAlignment(STI.getMaxBytesForLoopAlignment());
968   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
969 
970   // Only change the limit for entries in a jump table if specified by
971   // the sub target, but not at the command line.
972   unsigned MaxJT = STI.getMaximumJumpTableSize();
973   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
974     setMaximumJumpTableSize(MaxJT);
975 
976   setHasExtractBitsInsn(true);
977 
978   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
979 
980   if (Subtarget->hasNEON()) {
981     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
982     // silliness like this:
983     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
984     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
985     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
986     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
987     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
988     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
989     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
990     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
991     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
992     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
993     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
994     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
995     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
996     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
997     setOperationAction(ISD::FROUNDEVEN, MVT::v1f64, Expand);
998     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
999     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
1000     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
1001     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
1002     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
1003     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
1004     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
1005     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
1006     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
1007     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
1008     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
1009 
1010     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
1011     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
1012     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
1013     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
1014     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
1015 
1016     setOperationAction(ISD::FP_TO_SINT_SAT, MVT::v1i64, Expand);
1017     setOperationAction(ISD::FP_TO_UINT_SAT, MVT::v1i64, Expand);
1018 
1019     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
1020 
1021     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
1022     // elements smaller than i32, so promote the input to i32 first.
1023     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
1024     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
1025 
1026     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
1027     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
1028     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
1029     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
1030     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
1031     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
1032     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
1033     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
1034     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
1035 
1036     if (Subtarget->hasFullFP16()) {
1037       setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Custom);
1038       setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1039       setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Custom);
1040       setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1041       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1042       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1043       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
1044       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1045     } else {
1046       // when AArch64 doesn't have fullfp16 support, promote the input
1047       // to i32 first.
1048       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
1049       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
1050       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v16i8, MVT::v16i32);
1051       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v16i8, MVT::v16i32);
1052       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
1053       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
1054       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
1055       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
1056     }
1057 
1058     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
1059     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
1060     setOperationAction(ISD::BITREVERSE, MVT::v8i8, Legal);
1061     setOperationAction(ISD::BITREVERSE, MVT::v16i8, Legal);
1062     setOperationAction(ISD::BITREVERSE, MVT::v2i32, Custom);
1063     setOperationAction(ISD::BITREVERSE, MVT::v4i32, Custom);
1064     setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1065     setOperationAction(ISD::BITREVERSE, MVT::v2i64, Custom);
1066     for (auto VT : {MVT::v1i64, MVT::v2i64}) {
1067       setOperationAction(ISD::UMAX, VT, Custom);
1068       setOperationAction(ISD::SMAX, VT, Custom);
1069       setOperationAction(ISD::UMIN, VT, Custom);
1070       setOperationAction(ISD::SMIN, VT, Custom);
1071     }
1072 
1073     // AArch64 doesn't have MUL.2d:
1074     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
1075     // Custom handling for some quad-vector types to detect MULL.
1076     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
1077     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1078     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1079 
1080     // Saturates
1081     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1082                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1083       setOperationAction(ISD::SADDSAT, VT, Legal);
1084       setOperationAction(ISD::UADDSAT, VT, Legal);
1085       setOperationAction(ISD::SSUBSAT, VT, Legal);
1086       setOperationAction(ISD::USUBSAT, VT, Legal);
1087     }
1088 
1089     for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
1090                    MVT::v4i32}) {
1091       setOperationAction(ISD::ABDS, VT, Legal);
1092       setOperationAction(ISD::ABDU, VT, Legal);
1093     }
1094 
1095     // Vector reductions
1096     for (MVT VT : { MVT::v4f16, MVT::v2f32,
1097                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1098       if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) {
1099         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1100         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1101 
1102         setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
1103       }
1104     }
1105     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1106                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1107       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1108       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1109       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1110       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1111       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1112     }
1113     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
1114 
1115     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
1116     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
1117     // Likewise, narrowing and extending vector loads/stores aren't handled
1118     // directly.
1119     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1120       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
1121 
1122       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
1123         setOperationAction(ISD::MULHS, VT, Legal);
1124         setOperationAction(ISD::MULHU, VT, Legal);
1125       } else {
1126         setOperationAction(ISD::MULHS, VT, Expand);
1127         setOperationAction(ISD::MULHU, VT, Expand);
1128       }
1129       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1130       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1131 
1132       setOperationAction(ISD::BSWAP, VT, Expand);
1133       setOperationAction(ISD::CTTZ, VT, Expand);
1134 
1135       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1136         setTruncStoreAction(VT, InnerVT, Expand);
1137         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1138         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1139         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1140       }
1141     }
1142 
1143     // AArch64 has implementations of a lot of rounding-like FP operations.
1144     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
1145       setOperationAction(ISD::FFLOOR, Ty, Legal);
1146       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1147       setOperationAction(ISD::FCEIL, Ty, Legal);
1148       setOperationAction(ISD::FRINT, Ty, Legal);
1149       setOperationAction(ISD::FTRUNC, Ty, Legal);
1150       setOperationAction(ISD::FROUND, Ty, Legal);
1151       setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
1152     }
1153 
1154     if (Subtarget->hasFullFP16()) {
1155       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
1156         setOperationAction(ISD::FFLOOR, Ty, Legal);
1157         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1158         setOperationAction(ISD::FCEIL, Ty, Legal);
1159         setOperationAction(ISD::FRINT, Ty, Legal);
1160         setOperationAction(ISD::FTRUNC, Ty, Legal);
1161         setOperationAction(ISD::FROUND, Ty, Legal);
1162         setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
1163       }
1164     }
1165 
1166     if (Subtarget->hasSVE())
1167       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
1168 
1169     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
1170 
1171     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i16, MVT::v4i8, Custom);
1172     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1173     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1174     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i32, MVT::v4i8, Custom);
1175     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1176     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1177   }
1178 
1179   if (Subtarget->hasSVE()) {
1180     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
1181       setOperationAction(ISD::BITREVERSE, VT, Custom);
1182       setOperationAction(ISD::BSWAP, VT, Custom);
1183       setOperationAction(ISD::CTLZ, VT, Custom);
1184       setOperationAction(ISD::CTPOP, VT, Custom);
1185       setOperationAction(ISD::CTTZ, VT, Custom);
1186       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1187       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1188       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1189       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1190       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1191       setOperationAction(ISD::MGATHER, VT, Custom);
1192       setOperationAction(ISD::MSCATTER, VT, Custom);
1193       setOperationAction(ISD::MLOAD, VT, Custom);
1194       setOperationAction(ISD::MUL, VT, Custom);
1195       setOperationAction(ISD::MULHS, VT, Custom);
1196       setOperationAction(ISD::MULHU, VT, Custom);
1197       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1198       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1199       setOperationAction(ISD::SELECT, VT, Custom);
1200       setOperationAction(ISD::SETCC, VT, Custom);
1201       setOperationAction(ISD::SDIV, VT, Custom);
1202       setOperationAction(ISD::UDIV, VT, Custom);
1203       setOperationAction(ISD::SMIN, VT, Custom);
1204       setOperationAction(ISD::UMIN, VT, Custom);
1205       setOperationAction(ISD::SMAX, VT, Custom);
1206       setOperationAction(ISD::UMAX, VT, Custom);
1207       setOperationAction(ISD::SHL, VT, Custom);
1208       setOperationAction(ISD::SRL, VT, Custom);
1209       setOperationAction(ISD::SRA, VT, Custom);
1210       setOperationAction(ISD::ABS, VT, Custom);
1211       setOperationAction(ISD::ABDS, VT, Custom);
1212       setOperationAction(ISD::ABDU, VT, Custom);
1213       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1214       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1215       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1216       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1217       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1218       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1219       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1220       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1221 
1222       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1223       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1224       setOperationAction(ISD::SELECT_CC, VT, Expand);
1225       setOperationAction(ISD::ROTL, VT, Expand);
1226       setOperationAction(ISD::ROTR, VT, Expand);
1227     }
1228 
1229     // Illegal unpacked integer vector types.
1230     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1231       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1232       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1233     }
1234 
1235     // Legalize unpacked bitcasts to REINTERPRET_CAST.
1236     for (auto VT : {MVT::nxv2i16, MVT::nxv4i16, MVT::nxv2i32, MVT::nxv2bf16,
1237                     MVT::nxv2f16, MVT::nxv4f16, MVT::nxv2f32})
1238       setOperationAction(ISD::BITCAST, VT, Custom);
1239 
1240     for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
1241       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1242       setOperationAction(ISD::SELECT, VT, Custom);
1243       setOperationAction(ISD::SETCC, VT, Custom);
1244       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1245       setOperationAction(ISD::TRUNCATE, VT, Custom);
1246       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1247       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1248       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1249 
1250       setOperationAction(ISD::SELECT_CC, VT, Expand);
1251       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1252       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1253       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1254 
1255       // There are no legal MVT::nxv16f## based types.
1256       if (VT != MVT::nxv16i1) {
1257         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1258         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1259       }
1260     }
1261 
1262     // NEON doesn't support masked loads/stores/gathers/scatters, but SVE does
1263     for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v1f64,
1264                     MVT::v2f64, MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1265                     MVT::v2i32, MVT::v4i32, MVT::v1i64, MVT::v2i64}) {
1266       setOperationAction(ISD::MLOAD, VT, Custom);
1267       setOperationAction(ISD::MSTORE, VT, Custom);
1268       setOperationAction(ISD::MGATHER, VT, Custom);
1269       setOperationAction(ISD::MSCATTER, VT, Custom);
1270     }
1271 
1272     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
1273       for (MVT InnerVT : MVT::fp_scalable_vector_valuetypes()) {
1274         // Avoid marking truncating FP stores as legal to prevent the
1275         // DAGCombiner from creating unsupported truncating stores.
1276         setTruncStoreAction(VT, InnerVT, Expand);
1277         // SVE does not have floating-point extending loads.
1278         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1279         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1280         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1281       }
1282     }
1283 
1284     // SVE supports truncating stores of 64 and 128-bit vectors
1285     setTruncStoreAction(MVT::v2i64, MVT::v2i8, Custom);
1286     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Custom);
1287     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Custom);
1288     setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
1289     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
1290 
1291     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1292                     MVT::nxv4f32, MVT::nxv2f64}) {
1293       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1294       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1295       setOperationAction(ISD::MGATHER, VT, Custom);
1296       setOperationAction(ISD::MSCATTER, VT, Custom);
1297       setOperationAction(ISD::MLOAD, VT, Custom);
1298       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1299       setOperationAction(ISD::SELECT, VT, Custom);
1300       setOperationAction(ISD::FADD, VT, Custom);
1301       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1302       setOperationAction(ISD::FDIV, VT, Custom);
1303       setOperationAction(ISD::FMA, VT, Custom);
1304       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1305       setOperationAction(ISD::FMAXNUM, VT, Custom);
1306       setOperationAction(ISD::FMINIMUM, VT, Custom);
1307       setOperationAction(ISD::FMINNUM, VT, Custom);
1308       setOperationAction(ISD::FMUL, VT, Custom);
1309       setOperationAction(ISD::FNEG, VT, Custom);
1310       setOperationAction(ISD::FSUB, VT, Custom);
1311       setOperationAction(ISD::FCEIL, VT, Custom);
1312       setOperationAction(ISD::FFLOOR, VT, Custom);
1313       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1314       setOperationAction(ISD::FRINT, VT, Custom);
1315       setOperationAction(ISD::FROUND, VT, Custom);
1316       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1317       setOperationAction(ISD::FTRUNC, VT, Custom);
1318       setOperationAction(ISD::FSQRT, VT, Custom);
1319       setOperationAction(ISD::FABS, VT, Custom);
1320       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1321       setOperationAction(ISD::FP_ROUND, VT, Custom);
1322       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1323       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1324       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1325       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1326       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1327 
1328       setOperationAction(ISD::SELECT_CC, VT, Expand);
1329     }
1330 
1331     for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
1332       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1333       setOperationAction(ISD::MGATHER, VT, Custom);
1334       setOperationAction(ISD::MSCATTER, VT, Custom);
1335       setOperationAction(ISD::MLOAD, VT, Custom);
1336       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1337     }
1338 
1339     setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
1340 
1341     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1342     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1343 
1344     // NOTE: Currently this has to happen after computeRegisterProperties rather
1345     // than the preferred option of combining it with the addRegisterClass call.
1346     if (Subtarget->useSVEForFixedLengthVectors()) {
1347       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1348         if (useSVEForFixedLengthVectorVT(VT))
1349           addTypeForFixedLengthSVE(VT);
1350       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1351         if (useSVEForFixedLengthVectorVT(VT))
1352           addTypeForFixedLengthSVE(VT);
1353 
1354       // 64bit results can mean a bigger than NEON input.
1355       for (auto VT : {MVT::v8i8, MVT::v4i16})
1356         setOperationAction(ISD::TRUNCATE, VT, Custom);
1357       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1358 
1359       // 128bit results imply a bigger than NEON input.
1360       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1361         setOperationAction(ISD::TRUNCATE, VT, Custom);
1362       for (auto VT : {MVT::v8f16, MVT::v4f32})
1363         setOperationAction(ISD::FP_ROUND, VT, Custom);
1364 
1365       // These operations are not supported on NEON but SVE can do them.
1366       setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1367       setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
1368       setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1369       setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
1370       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1371       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1372       setOperationAction(ISD::MULHS, MVT::v1i64, Custom);
1373       setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
1374       setOperationAction(ISD::MULHU, MVT::v1i64, Custom);
1375       setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
1376       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1377       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1378       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1379       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1380       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1381       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1382       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1383       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1384       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1385       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1386       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1387       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1388       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1389       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1390       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1391       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1392       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1393       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1394       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1395       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1396       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1397       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1398       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1399       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1400       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1401       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1402       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1403       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1404 
1405       // Int operations with no NEON support.
1406       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1407                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1408         setOperationAction(ISD::BITREVERSE, VT, Custom);
1409         setOperationAction(ISD::CTTZ, VT, Custom);
1410         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1411         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1412         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1413       }
1414 
1415       // FP operations with no NEON support.
1416       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
1417                       MVT::v1f64, MVT::v2f64})
1418         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1419 
1420       // Use SVE for vectors with more than 2 elements.
1421       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1422         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1423     }
1424 
1425     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64);
1426     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32);
1427     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16);
1428     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8);
1429   }
1430 
1431   if (Subtarget->hasMOPS() && Subtarget->hasMTE()) {
1432     // Only required for llvm.aarch64.mops.memset.tag
1433     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
1434   }
1435 
1436   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1437 }
1438 
1439 void AArch64TargetLowering::addTypeForNEON(MVT VT) {
1440   assert(VT.isVector() && "VT should be a vector type");
1441 
1442   if (VT.isFloatingPoint()) {
1443     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1444     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1445     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1446   }
1447 
1448   // Mark vector float intrinsics as expand.
1449   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1450     setOperationAction(ISD::FSIN, VT, Expand);
1451     setOperationAction(ISD::FCOS, VT, Expand);
1452     setOperationAction(ISD::FPOW, VT, Expand);
1453     setOperationAction(ISD::FLOG, VT, Expand);
1454     setOperationAction(ISD::FLOG2, VT, Expand);
1455     setOperationAction(ISD::FLOG10, VT, Expand);
1456     setOperationAction(ISD::FEXP, VT, Expand);
1457     setOperationAction(ISD::FEXP2, VT, Expand);
1458   }
1459 
1460   // But we do support custom-lowering for FCOPYSIGN.
1461   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
1462       ((VT == MVT::v4f16 || VT == MVT::v8f16) && Subtarget->hasFullFP16()))
1463     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1464 
1465   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1466   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1467   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1468   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1469   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1470   setOperationAction(ISD::SRA, VT, Custom);
1471   setOperationAction(ISD::SRL, VT, Custom);
1472   setOperationAction(ISD::SHL, VT, Custom);
1473   setOperationAction(ISD::OR, VT, Custom);
1474   setOperationAction(ISD::SETCC, VT, Custom);
1475   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1476 
1477   setOperationAction(ISD::SELECT, VT, Expand);
1478   setOperationAction(ISD::SELECT_CC, VT, Expand);
1479   setOperationAction(ISD::VSELECT, VT, Expand);
1480   for (MVT InnerVT : MVT::all_valuetypes())
1481     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1482 
1483   // CNT supports only B element sizes, then use UADDLP to widen.
1484   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1485     setOperationAction(ISD::CTPOP, VT, Custom);
1486 
1487   setOperationAction(ISD::UDIV, VT, Expand);
1488   setOperationAction(ISD::SDIV, VT, Expand);
1489   setOperationAction(ISD::UREM, VT, Expand);
1490   setOperationAction(ISD::SREM, VT, Expand);
1491   setOperationAction(ISD::FREM, VT, Expand);
1492 
1493   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1494   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1495   setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
1496   setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
1497 
1498   if (!VT.isFloatingPoint())
1499     setOperationAction(ISD::ABS, VT, Legal);
1500 
1501   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1502   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1503     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1504       setOperationAction(Opcode, VT, Legal);
1505 
1506   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1507   if (VT.isFloatingPoint() &&
1508       VT.getVectorElementType() != MVT::bf16 &&
1509       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1510     for (unsigned Opcode :
1511          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1512       setOperationAction(Opcode, VT, Legal);
1513 
1514   if (Subtarget->isLittleEndian()) {
1515     for (unsigned im = (unsigned)ISD::PRE_INC;
1516          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1517       setIndexedLoadAction(im, VT, Legal);
1518       setIndexedStoreAction(im, VT, Legal);
1519     }
1520   }
1521 }
1522 
1523 bool AArch64TargetLowering::shouldExpandGetActiveLaneMask(EVT ResVT,
1524                                                           EVT OpVT) const {
1525   // Only SVE has a 1:1 mapping from intrinsic -> instruction (whilelo).
1526   if (!Subtarget->hasSVE())
1527     return true;
1528 
1529   // We can only support legal predicate result types.
1530   if (ResVT != MVT::nxv2i1 && ResVT != MVT::nxv4i1 && ResVT != MVT::nxv8i1 &&
1531       ResVT != MVT::nxv16i1)
1532     return true;
1533 
1534   // The whilelo instruction only works with i32 or i64 scalar inputs.
1535   if (OpVT != MVT::i32 && OpVT != MVT::i64)
1536     return true;
1537 
1538   return false;
1539 }
1540 
1541 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1542   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1543 
1544   // By default everything must be expanded.
1545   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1546     setOperationAction(Op, VT, Expand);
1547 
1548   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1549   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1550 
1551   if (VT.isFloatingPoint()) {
1552     setCondCodeAction(ISD::SETO, VT, Expand);
1553     setCondCodeAction(ISD::SETOLT, VT, Expand);
1554     setCondCodeAction(ISD::SETLT, VT, Expand);
1555     setCondCodeAction(ISD::SETOLE, VT, Expand);
1556     setCondCodeAction(ISD::SETLE, VT, Expand);
1557     setCondCodeAction(ISD::SETULT, VT, Expand);
1558     setCondCodeAction(ISD::SETULE, VT, Expand);
1559     setCondCodeAction(ISD::SETUGE, VT, Expand);
1560     setCondCodeAction(ISD::SETUGT, VT, Expand);
1561     setCondCodeAction(ISD::SETUEQ, VT, Expand);
1562     setCondCodeAction(ISD::SETUNE, VT, Expand);
1563   }
1564 
1565   // Mark integer truncating stores/extending loads as having custom lowering
1566   if (VT.isInteger()) {
1567     MVT InnerVT = VT.changeVectorElementType(MVT::i8);
1568     while (InnerVT != VT) {
1569       setTruncStoreAction(VT, InnerVT, Custom);
1570       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Custom);
1571       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Custom);
1572       InnerVT = InnerVT.changeVectorElementType(
1573           MVT::getIntegerVT(2 * InnerVT.getScalarSizeInBits()));
1574     }
1575   }
1576 
1577   // Mark floating-point truncating stores/extending loads as having custom
1578   // lowering
1579   if (VT.isFloatingPoint()) {
1580     MVT InnerVT = VT.changeVectorElementType(MVT::f16);
1581     while (InnerVT != VT) {
1582       setTruncStoreAction(VT, InnerVT, Custom);
1583       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Custom);
1584       InnerVT = InnerVT.changeVectorElementType(
1585           MVT::getFloatingPointVT(2 * InnerVT.getScalarSizeInBits()));
1586     }
1587   }
1588 
1589   // Lower fixed length vector operations to scalable equivalents.
1590   setOperationAction(ISD::ABS, VT, Custom);
1591   setOperationAction(ISD::ADD, VT, Custom);
1592   setOperationAction(ISD::AND, VT, Custom);
1593   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1594   setOperationAction(ISD::BITCAST, VT, Custom);
1595   setOperationAction(ISD::BITREVERSE, VT, Custom);
1596   setOperationAction(ISD::BSWAP, VT, Custom);
1597   setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1598   setOperationAction(ISD::CTLZ, VT, Custom);
1599   setOperationAction(ISD::CTPOP, VT, Custom);
1600   setOperationAction(ISD::CTTZ, VT, Custom);
1601   setOperationAction(ISD::FABS, VT, Custom);
1602   setOperationAction(ISD::FADD, VT, Custom);
1603   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1604   setOperationAction(ISD::FCEIL, VT, Custom);
1605   setOperationAction(ISD::FDIV, VT, Custom);
1606   setOperationAction(ISD::FFLOOR, VT, Custom);
1607   setOperationAction(ISD::FMA, VT, Custom);
1608   setOperationAction(ISD::FMAXIMUM, VT, Custom);
1609   setOperationAction(ISD::FMAXNUM, VT, Custom);
1610   setOperationAction(ISD::FMINIMUM, VT, Custom);
1611   setOperationAction(ISD::FMINNUM, VT, Custom);
1612   setOperationAction(ISD::FMUL, VT, Custom);
1613   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1614   setOperationAction(ISD::FNEG, VT, Custom);
1615   setOperationAction(ISD::FP_EXTEND, VT, Custom);
1616   setOperationAction(ISD::FP_ROUND, VT, Custom);
1617   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1618   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1619   setOperationAction(ISD::FRINT, VT, Custom);
1620   setOperationAction(ISD::FROUND, VT, Custom);
1621   setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1622   setOperationAction(ISD::FSQRT, VT, Custom);
1623   setOperationAction(ISD::FSUB, VT, Custom);
1624   setOperationAction(ISD::FTRUNC, VT, Custom);
1625   setOperationAction(ISD::LOAD, VT, Custom);
1626   setOperationAction(ISD::MGATHER, VT, Custom);
1627   setOperationAction(ISD::MLOAD, VT, Custom);
1628   setOperationAction(ISD::MSCATTER, VT, Custom);
1629   setOperationAction(ISD::MSTORE, VT, Custom);
1630   setOperationAction(ISD::MUL, VT, Custom);
1631   setOperationAction(ISD::MULHS, VT, Custom);
1632   setOperationAction(ISD::MULHU, VT, Custom);
1633   setOperationAction(ISD::OR, VT, Custom);
1634   setOperationAction(ISD::SDIV, VT, Custom);
1635   setOperationAction(ISD::SELECT, VT, Custom);
1636   setOperationAction(ISD::SETCC, VT, Custom);
1637   setOperationAction(ISD::SHL, VT, Custom);
1638   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1639   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1640   setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1641   setOperationAction(ISD::SMAX, VT, Custom);
1642   setOperationAction(ISD::SMIN, VT, Custom);
1643   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1644   setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1645   setOperationAction(ISD::SRA, VT, Custom);
1646   setOperationAction(ISD::SRL, VT, Custom);
1647   setOperationAction(ISD::STORE, VT, Custom);
1648   setOperationAction(ISD::SUB, VT, Custom);
1649   setOperationAction(ISD::TRUNCATE, VT, Custom);
1650   setOperationAction(ISD::UDIV, VT, Custom);
1651   setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1652   setOperationAction(ISD::UMAX, VT, Custom);
1653   setOperationAction(ISD::UMIN, VT, Custom);
1654   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1655   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1656   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1657   setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1658   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1659   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1660   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1661   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1662   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1663   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1664   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1665   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1666   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1667   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1668   setOperationAction(ISD::VSELECT, VT, Custom);
1669   setOperationAction(ISD::XOR, VT, Custom);
1670   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1671 }
1672 
1673 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1674   addRegisterClass(VT, &AArch64::FPR64RegClass);
1675   addTypeForNEON(VT);
1676 }
1677 
1678 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1679   addRegisterClass(VT, &AArch64::FPR128RegClass);
1680   addTypeForNEON(VT);
1681 }
1682 
1683 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1684                                               LLVMContext &C, EVT VT) const {
1685   if (!VT.isVector())
1686     return MVT::i32;
1687   if (VT.isScalableVector())
1688     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1689   return VT.changeVectorElementTypeToInteger();
1690 }
1691 
1692 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1693                                const APInt &Demanded,
1694                                TargetLowering::TargetLoweringOpt &TLO,
1695                                unsigned NewOpc) {
1696   uint64_t OldImm = Imm, NewImm, Enc;
1697   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1698 
1699   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1700   // bimm64.
1701   if (Imm == 0 || Imm == Mask ||
1702       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1703     return false;
1704 
1705   unsigned EltSize = Size;
1706   uint64_t DemandedBits = Demanded.getZExtValue();
1707 
1708   // Clear bits that are not demanded.
1709   Imm &= DemandedBits;
1710 
1711   while (true) {
1712     // The goal here is to set the non-demanded bits in a way that minimizes
1713     // the number of switching between 0 and 1. In order to achieve this goal,
1714     // we set the non-demanded bits to the value of the preceding demanded bits.
1715     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1716     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1717     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1718     // The final result is 0b11000011.
1719     uint64_t NonDemandedBits = ~DemandedBits;
1720     uint64_t InvertedImm = ~Imm & DemandedBits;
1721     uint64_t RotatedImm =
1722         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1723         NonDemandedBits;
1724     uint64_t Sum = RotatedImm + NonDemandedBits;
1725     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1726     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1727     NewImm = (Imm | Ones) & Mask;
1728 
1729     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1730     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1731     // we halve the element size and continue the search.
1732     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1733       break;
1734 
1735     // We cannot shrink the element size any further if it is 2-bits.
1736     if (EltSize == 2)
1737       return false;
1738 
1739     EltSize /= 2;
1740     Mask >>= EltSize;
1741     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1742 
1743     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1744     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1745       return false;
1746 
1747     // Merge the upper and lower halves of Imm and DemandedBits.
1748     Imm |= Hi;
1749     DemandedBits |= DemandedBitsHi;
1750   }
1751 
1752   ++NumOptimizedImms;
1753 
1754   // Replicate the element across the register width.
1755   while (EltSize < Size) {
1756     NewImm |= NewImm << EltSize;
1757     EltSize *= 2;
1758   }
1759 
1760   (void)OldImm;
1761   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1762          "demanded bits should never be altered");
1763   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1764 
1765   // Create the new constant immediate node.
1766   EVT VT = Op.getValueType();
1767   SDLoc DL(Op);
1768   SDValue New;
1769 
1770   // If the new constant immediate is all-zeros or all-ones, let the target
1771   // independent DAG combine optimize this node.
1772   if (NewImm == 0 || NewImm == OrigMask) {
1773     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1774                           TLO.DAG.getConstant(NewImm, DL, VT));
1775   // Otherwise, create a machine node so that target independent DAG combine
1776   // doesn't undo this optimization.
1777   } else {
1778     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1779     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1780     New = SDValue(
1781         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1782   }
1783 
1784   return TLO.CombineTo(Op, New);
1785 }
1786 
1787 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1788     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1789     TargetLoweringOpt &TLO) const {
1790   // Delay this optimization to as late as possible.
1791   if (!TLO.LegalOps)
1792     return false;
1793 
1794   if (!EnableOptimizeLogicalImm)
1795     return false;
1796 
1797   EVT VT = Op.getValueType();
1798   if (VT.isVector())
1799     return false;
1800 
1801   unsigned Size = VT.getSizeInBits();
1802   assert((Size == 32 || Size == 64) &&
1803          "i32 or i64 is expected after legalization.");
1804 
1805   // Exit early if we demand all bits.
1806   if (DemandedBits.countPopulation() == Size)
1807     return false;
1808 
1809   unsigned NewOpc;
1810   switch (Op.getOpcode()) {
1811   default:
1812     return false;
1813   case ISD::AND:
1814     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1815     break;
1816   case ISD::OR:
1817     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1818     break;
1819   case ISD::XOR:
1820     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1821     break;
1822   }
1823   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1824   if (!C)
1825     return false;
1826   uint64_t Imm = C->getZExtValue();
1827   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1828 }
1829 
1830 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1831 /// Mask are known to be either zero or one and return them Known.
1832 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1833     const SDValue Op, KnownBits &Known,
1834     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1835   switch (Op.getOpcode()) {
1836   default:
1837     break;
1838   case AArch64ISD::CSEL: {
1839     KnownBits Known2;
1840     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1841     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1842     Known = KnownBits::commonBits(Known, Known2);
1843     break;
1844   }
1845   case AArch64ISD::BICi: {
1846     // Compute the bit cleared value.
1847     uint64_t Mask =
1848         ~(Op->getConstantOperandVal(1) << Op->getConstantOperandVal(2));
1849     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1850     Known &= KnownBits::makeConstant(APInt(Known.getBitWidth(), Mask));
1851     break;
1852   }
1853   case AArch64ISD::VLSHR: {
1854     KnownBits Known2;
1855     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1856     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1857     Known = KnownBits::lshr(Known, Known2);
1858     break;
1859   }
1860   case AArch64ISD::VASHR: {
1861     KnownBits Known2;
1862     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1863     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1864     Known = KnownBits::ashr(Known, Known2);
1865     break;
1866   }
1867   case AArch64ISD::LOADgot:
1868   case AArch64ISD::ADDlow: {
1869     if (!Subtarget->isTargetILP32())
1870       break;
1871     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1872     Known.Zero = APInt::getHighBitsSet(64, 32);
1873     break;
1874   }
1875   case AArch64ISD::ASSERT_ZEXT_BOOL: {
1876     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1877     Known.Zero |= APInt(Known.getBitWidth(), 0xFE);
1878     break;
1879   }
1880   case ISD::INTRINSIC_W_CHAIN: {
1881     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1882     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1883     switch (IntID) {
1884     default: return;
1885     case Intrinsic::aarch64_ldaxr:
1886     case Intrinsic::aarch64_ldxr: {
1887       unsigned BitWidth = Known.getBitWidth();
1888       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1889       unsigned MemBits = VT.getScalarSizeInBits();
1890       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1891       return;
1892     }
1893     }
1894     break;
1895   }
1896   case ISD::INTRINSIC_WO_CHAIN:
1897   case ISD::INTRINSIC_VOID: {
1898     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1899     switch (IntNo) {
1900     default:
1901       break;
1902     case Intrinsic::aarch64_neon_umaxv:
1903     case Intrinsic::aarch64_neon_uminv: {
1904       // Figure out the datatype of the vector operand. The UMINV instruction
1905       // will zero extend the result, so we can mark as known zero all the
1906       // bits larger than the element datatype. 32-bit or larget doesn't need
1907       // this as those are legal types and will be handled by isel directly.
1908       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1909       unsigned BitWidth = Known.getBitWidth();
1910       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1911         assert(BitWidth >= 8 && "Unexpected width!");
1912         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1913         Known.Zero |= Mask;
1914       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1915         assert(BitWidth >= 16 && "Unexpected width!");
1916         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1917         Known.Zero |= Mask;
1918       }
1919       break;
1920     } break;
1921     }
1922   }
1923   }
1924 }
1925 
1926 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1927                                                   EVT) const {
1928   return MVT::i64;
1929 }
1930 
1931 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1932     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1933     bool *Fast) const {
1934   if (Subtarget->requiresStrictAlign())
1935     return false;
1936 
1937   if (Fast) {
1938     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1939     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1940             // See comments in performSTORECombine() for more details about
1941             // these conditions.
1942 
1943             // Code that uses clang vector extensions can mark that it
1944             // wants unaligned accesses to be treated as fast by
1945             // underspecifying alignment to be 1 or 2.
1946             Alignment <= 2 ||
1947 
1948             // Disregard v2i64. Memcpy lowering produces those and splitting
1949             // them regresses performance on micro-benchmarks and olden/bh.
1950             VT == MVT::v2i64;
1951   }
1952   return true;
1953 }
1954 
1955 // Same as above but handling LLTs instead.
1956 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1957     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1958     bool *Fast) const {
1959   if (Subtarget->requiresStrictAlign())
1960     return false;
1961 
1962   if (Fast) {
1963     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1964     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1965             Ty.getSizeInBytes() != 16 ||
1966             // See comments in performSTORECombine() for more details about
1967             // these conditions.
1968 
1969             // Code that uses clang vector extensions can mark that it
1970             // wants unaligned accesses to be treated as fast by
1971             // underspecifying alignment to be 1 or 2.
1972             Alignment <= 2 ||
1973 
1974             // Disregard v2i64. Memcpy lowering produces those and splitting
1975             // them regresses performance on micro-benchmarks and olden/bh.
1976             Ty == LLT::fixed_vector(2, 64);
1977   }
1978   return true;
1979 }
1980 
1981 FastISel *
1982 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1983                                       const TargetLibraryInfo *libInfo) const {
1984   return AArch64::createFastISel(funcInfo, libInfo);
1985 }
1986 
1987 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1988 #define MAKE_CASE(V)                                                           \
1989   case V:                                                                      \
1990     return #V;
1991   switch ((AArch64ISD::NodeType)Opcode) {
1992   case AArch64ISD::FIRST_NUMBER:
1993     break;
1994     MAKE_CASE(AArch64ISD::CALL)
1995     MAKE_CASE(AArch64ISD::ADRP)
1996     MAKE_CASE(AArch64ISD::ADR)
1997     MAKE_CASE(AArch64ISD::ADDlow)
1998     MAKE_CASE(AArch64ISD::LOADgot)
1999     MAKE_CASE(AArch64ISD::RET_FLAG)
2000     MAKE_CASE(AArch64ISD::BRCOND)
2001     MAKE_CASE(AArch64ISD::CSEL)
2002     MAKE_CASE(AArch64ISD::CSINV)
2003     MAKE_CASE(AArch64ISD::CSNEG)
2004     MAKE_CASE(AArch64ISD::CSINC)
2005     MAKE_CASE(AArch64ISD::THREAD_POINTER)
2006     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
2007     MAKE_CASE(AArch64ISD::ABDS_PRED)
2008     MAKE_CASE(AArch64ISD::ABDU_PRED)
2009     MAKE_CASE(AArch64ISD::ADD_PRED)
2010     MAKE_CASE(AArch64ISD::MUL_PRED)
2011     MAKE_CASE(AArch64ISD::MULHS_PRED)
2012     MAKE_CASE(AArch64ISD::MULHU_PRED)
2013     MAKE_CASE(AArch64ISD::SDIV_PRED)
2014     MAKE_CASE(AArch64ISD::SHL_PRED)
2015     MAKE_CASE(AArch64ISD::SMAX_PRED)
2016     MAKE_CASE(AArch64ISD::SMIN_PRED)
2017     MAKE_CASE(AArch64ISD::SRA_PRED)
2018     MAKE_CASE(AArch64ISD::SRL_PRED)
2019     MAKE_CASE(AArch64ISD::SUB_PRED)
2020     MAKE_CASE(AArch64ISD::UDIV_PRED)
2021     MAKE_CASE(AArch64ISD::UMAX_PRED)
2022     MAKE_CASE(AArch64ISD::UMIN_PRED)
2023     MAKE_CASE(AArch64ISD::SRAD_MERGE_OP1)
2024     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
2025     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
2026     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
2027     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
2028     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
2029     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
2030     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
2031     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
2032     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
2033     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
2034     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
2035     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
2036     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
2037     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
2038     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
2039     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
2040     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
2041     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
2042     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
2043     MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
2044     MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
2045     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
2046     MAKE_CASE(AArch64ISD::ADC)
2047     MAKE_CASE(AArch64ISD::SBC)
2048     MAKE_CASE(AArch64ISD::ADDS)
2049     MAKE_CASE(AArch64ISD::SUBS)
2050     MAKE_CASE(AArch64ISD::ADCS)
2051     MAKE_CASE(AArch64ISD::SBCS)
2052     MAKE_CASE(AArch64ISD::ANDS)
2053     MAKE_CASE(AArch64ISD::CCMP)
2054     MAKE_CASE(AArch64ISD::CCMN)
2055     MAKE_CASE(AArch64ISD::FCCMP)
2056     MAKE_CASE(AArch64ISD::FCMP)
2057     MAKE_CASE(AArch64ISD::STRICT_FCMP)
2058     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
2059     MAKE_CASE(AArch64ISD::DUP)
2060     MAKE_CASE(AArch64ISD::DUPLANE8)
2061     MAKE_CASE(AArch64ISD::DUPLANE16)
2062     MAKE_CASE(AArch64ISD::DUPLANE32)
2063     MAKE_CASE(AArch64ISD::DUPLANE64)
2064     MAKE_CASE(AArch64ISD::MOVI)
2065     MAKE_CASE(AArch64ISD::MOVIshift)
2066     MAKE_CASE(AArch64ISD::MOVIedit)
2067     MAKE_CASE(AArch64ISD::MOVImsl)
2068     MAKE_CASE(AArch64ISD::FMOV)
2069     MAKE_CASE(AArch64ISD::MVNIshift)
2070     MAKE_CASE(AArch64ISD::MVNImsl)
2071     MAKE_CASE(AArch64ISD::BICi)
2072     MAKE_CASE(AArch64ISD::ORRi)
2073     MAKE_CASE(AArch64ISD::BSP)
2074     MAKE_CASE(AArch64ISD::EXTR)
2075     MAKE_CASE(AArch64ISD::ZIP1)
2076     MAKE_CASE(AArch64ISD::ZIP2)
2077     MAKE_CASE(AArch64ISD::UZP1)
2078     MAKE_CASE(AArch64ISD::UZP2)
2079     MAKE_CASE(AArch64ISD::TRN1)
2080     MAKE_CASE(AArch64ISD::TRN2)
2081     MAKE_CASE(AArch64ISD::REV16)
2082     MAKE_CASE(AArch64ISD::REV32)
2083     MAKE_CASE(AArch64ISD::REV64)
2084     MAKE_CASE(AArch64ISD::EXT)
2085     MAKE_CASE(AArch64ISD::SPLICE)
2086     MAKE_CASE(AArch64ISD::VSHL)
2087     MAKE_CASE(AArch64ISD::VLSHR)
2088     MAKE_CASE(AArch64ISD::VASHR)
2089     MAKE_CASE(AArch64ISD::VSLI)
2090     MAKE_CASE(AArch64ISD::VSRI)
2091     MAKE_CASE(AArch64ISD::CMEQ)
2092     MAKE_CASE(AArch64ISD::CMGE)
2093     MAKE_CASE(AArch64ISD::CMGT)
2094     MAKE_CASE(AArch64ISD::CMHI)
2095     MAKE_CASE(AArch64ISD::CMHS)
2096     MAKE_CASE(AArch64ISD::FCMEQ)
2097     MAKE_CASE(AArch64ISD::FCMGE)
2098     MAKE_CASE(AArch64ISD::FCMGT)
2099     MAKE_CASE(AArch64ISD::CMEQz)
2100     MAKE_CASE(AArch64ISD::CMGEz)
2101     MAKE_CASE(AArch64ISD::CMGTz)
2102     MAKE_CASE(AArch64ISD::CMLEz)
2103     MAKE_CASE(AArch64ISD::CMLTz)
2104     MAKE_CASE(AArch64ISD::FCMEQz)
2105     MAKE_CASE(AArch64ISD::FCMGEz)
2106     MAKE_CASE(AArch64ISD::FCMGTz)
2107     MAKE_CASE(AArch64ISD::FCMLEz)
2108     MAKE_CASE(AArch64ISD::FCMLTz)
2109     MAKE_CASE(AArch64ISD::SADDV)
2110     MAKE_CASE(AArch64ISD::UADDV)
2111     MAKE_CASE(AArch64ISD::SRHADD)
2112     MAKE_CASE(AArch64ISD::URHADD)
2113     MAKE_CASE(AArch64ISD::SHADD)
2114     MAKE_CASE(AArch64ISD::UHADD)
2115     MAKE_CASE(AArch64ISD::SDOT)
2116     MAKE_CASE(AArch64ISD::UDOT)
2117     MAKE_CASE(AArch64ISD::SMINV)
2118     MAKE_CASE(AArch64ISD::UMINV)
2119     MAKE_CASE(AArch64ISD::SMAXV)
2120     MAKE_CASE(AArch64ISD::UMAXV)
2121     MAKE_CASE(AArch64ISD::SADDV_PRED)
2122     MAKE_CASE(AArch64ISD::UADDV_PRED)
2123     MAKE_CASE(AArch64ISD::SMAXV_PRED)
2124     MAKE_CASE(AArch64ISD::UMAXV_PRED)
2125     MAKE_CASE(AArch64ISD::SMINV_PRED)
2126     MAKE_CASE(AArch64ISD::UMINV_PRED)
2127     MAKE_CASE(AArch64ISD::ORV_PRED)
2128     MAKE_CASE(AArch64ISD::EORV_PRED)
2129     MAKE_CASE(AArch64ISD::ANDV_PRED)
2130     MAKE_CASE(AArch64ISD::CLASTA_N)
2131     MAKE_CASE(AArch64ISD::CLASTB_N)
2132     MAKE_CASE(AArch64ISD::LASTA)
2133     MAKE_CASE(AArch64ISD::LASTB)
2134     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
2135     MAKE_CASE(AArch64ISD::LS64_BUILD)
2136     MAKE_CASE(AArch64ISD::LS64_EXTRACT)
2137     MAKE_CASE(AArch64ISD::TBL)
2138     MAKE_CASE(AArch64ISD::FADD_PRED)
2139     MAKE_CASE(AArch64ISD::FADDA_PRED)
2140     MAKE_CASE(AArch64ISD::FADDV_PRED)
2141     MAKE_CASE(AArch64ISD::FDIV_PRED)
2142     MAKE_CASE(AArch64ISD::FMA_PRED)
2143     MAKE_CASE(AArch64ISD::FMAX_PRED)
2144     MAKE_CASE(AArch64ISD::FMAXV_PRED)
2145     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
2146     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
2147     MAKE_CASE(AArch64ISD::FMIN_PRED)
2148     MAKE_CASE(AArch64ISD::FMINV_PRED)
2149     MAKE_CASE(AArch64ISD::FMINNM_PRED)
2150     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
2151     MAKE_CASE(AArch64ISD::FMUL_PRED)
2152     MAKE_CASE(AArch64ISD::FSUB_PRED)
2153     MAKE_CASE(AArch64ISD::BIC)
2154     MAKE_CASE(AArch64ISD::BIT)
2155     MAKE_CASE(AArch64ISD::CBZ)
2156     MAKE_CASE(AArch64ISD::CBNZ)
2157     MAKE_CASE(AArch64ISD::TBZ)
2158     MAKE_CASE(AArch64ISD::TBNZ)
2159     MAKE_CASE(AArch64ISD::TC_RETURN)
2160     MAKE_CASE(AArch64ISD::PREFETCH)
2161     MAKE_CASE(AArch64ISD::SITOF)
2162     MAKE_CASE(AArch64ISD::UITOF)
2163     MAKE_CASE(AArch64ISD::NVCAST)
2164     MAKE_CASE(AArch64ISD::MRS)
2165     MAKE_CASE(AArch64ISD::SQSHL_I)
2166     MAKE_CASE(AArch64ISD::UQSHL_I)
2167     MAKE_CASE(AArch64ISD::SRSHR_I)
2168     MAKE_CASE(AArch64ISD::URSHR_I)
2169     MAKE_CASE(AArch64ISD::SQSHLU_I)
2170     MAKE_CASE(AArch64ISD::WrapperLarge)
2171     MAKE_CASE(AArch64ISD::LD2post)
2172     MAKE_CASE(AArch64ISD::LD3post)
2173     MAKE_CASE(AArch64ISD::LD4post)
2174     MAKE_CASE(AArch64ISD::ST2post)
2175     MAKE_CASE(AArch64ISD::ST3post)
2176     MAKE_CASE(AArch64ISD::ST4post)
2177     MAKE_CASE(AArch64ISD::LD1x2post)
2178     MAKE_CASE(AArch64ISD::LD1x3post)
2179     MAKE_CASE(AArch64ISD::LD1x4post)
2180     MAKE_CASE(AArch64ISD::ST1x2post)
2181     MAKE_CASE(AArch64ISD::ST1x3post)
2182     MAKE_CASE(AArch64ISD::ST1x4post)
2183     MAKE_CASE(AArch64ISD::LD1DUPpost)
2184     MAKE_CASE(AArch64ISD::LD2DUPpost)
2185     MAKE_CASE(AArch64ISD::LD3DUPpost)
2186     MAKE_CASE(AArch64ISD::LD4DUPpost)
2187     MAKE_CASE(AArch64ISD::LD1LANEpost)
2188     MAKE_CASE(AArch64ISD::LD2LANEpost)
2189     MAKE_CASE(AArch64ISD::LD3LANEpost)
2190     MAKE_CASE(AArch64ISD::LD4LANEpost)
2191     MAKE_CASE(AArch64ISD::ST2LANEpost)
2192     MAKE_CASE(AArch64ISD::ST3LANEpost)
2193     MAKE_CASE(AArch64ISD::ST4LANEpost)
2194     MAKE_CASE(AArch64ISD::SMULL)
2195     MAKE_CASE(AArch64ISD::UMULL)
2196     MAKE_CASE(AArch64ISD::FRECPE)
2197     MAKE_CASE(AArch64ISD::FRECPS)
2198     MAKE_CASE(AArch64ISD::FRSQRTE)
2199     MAKE_CASE(AArch64ISD::FRSQRTS)
2200     MAKE_CASE(AArch64ISD::STG)
2201     MAKE_CASE(AArch64ISD::STZG)
2202     MAKE_CASE(AArch64ISD::ST2G)
2203     MAKE_CASE(AArch64ISD::STZ2G)
2204     MAKE_CASE(AArch64ISD::SUNPKHI)
2205     MAKE_CASE(AArch64ISD::SUNPKLO)
2206     MAKE_CASE(AArch64ISD::UUNPKHI)
2207     MAKE_CASE(AArch64ISD::UUNPKLO)
2208     MAKE_CASE(AArch64ISD::INSR)
2209     MAKE_CASE(AArch64ISD::PTEST)
2210     MAKE_CASE(AArch64ISD::PTRUE)
2211     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
2212     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
2213     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
2214     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
2215     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
2216     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
2217     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
2218     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
2219     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
2220     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
2221     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
2222     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
2223     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
2224     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
2225     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
2226     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
2227     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
2228     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
2229     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
2230     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
2231     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
2232     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
2233     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
2234     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
2235     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
2236     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
2237     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
2238     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
2239     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
2240     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
2241     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
2242     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
2243     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
2244     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
2245     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
2246     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
2247     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
2248     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
2249     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
2250     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
2251     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
2252     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
2253     MAKE_CASE(AArch64ISD::ST1_PRED)
2254     MAKE_CASE(AArch64ISD::SST1_PRED)
2255     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
2256     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
2257     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
2258     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
2259     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
2260     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
2261     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
2262     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
2263     MAKE_CASE(AArch64ISD::LDP)
2264     MAKE_CASE(AArch64ISD::STP)
2265     MAKE_CASE(AArch64ISD::STNP)
2266     MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
2267     MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
2268     MAKE_CASE(AArch64ISD::REVH_MERGE_PASSTHRU)
2269     MAKE_CASE(AArch64ISD::REVW_MERGE_PASSTHRU)
2270     MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
2271     MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
2272     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
2273     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
2274     MAKE_CASE(AArch64ISD::UADDLP)
2275     MAKE_CASE(AArch64ISD::CALL_RVMARKER)
2276     MAKE_CASE(AArch64ISD::ASSERT_ZEXT_BOOL)
2277     MAKE_CASE(AArch64ISD::MOPS_MEMSET)
2278     MAKE_CASE(AArch64ISD::MOPS_MEMSET_TAGGING)
2279     MAKE_CASE(AArch64ISD::MOPS_MEMCOPY)
2280     MAKE_CASE(AArch64ISD::MOPS_MEMMOVE)
2281     MAKE_CASE(AArch64ISD::CALL_BTI)
2282   }
2283 #undef MAKE_CASE
2284   return nullptr;
2285 }
2286 
2287 MachineBasicBlock *
2288 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
2289                                     MachineBasicBlock *MBB) const {
2290   // We materialise the F128CSEL pseudo-instruction as some control flow and a
2291   // phi node:
2292 
2293   // OrigBB:
2294   //     [... previous instrs leading to comparison ...]
2295   //     b.ne TrueBB
2296   //     b EndBB
2297   // TrueBB:
2298   //     ; Fallthrough
2299   // EndBB:
2300   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
2301 
2302   MachineFunction *MF = MBB->getParent();
2303   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2304   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2305   DebugLoc DL = MI.getDebugLoc();
2306   MachineFunction::iterator It = ++MBB->getIterator();
2307 
2308   Register DestReg = MI.getOperand(0).getReg();
2309   Register IfTrueReg = MI.getOperand(1).getReg();
2310   Register IfFalseReg = MI.getOperand(2).getReg();
2311   unsigned CondCode = MI.getOperand(3).getImm();
2312   bool NZCVKilled = MI.getOperand(4).isKill();
2313 
2314   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
2315   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
2316   MF->insert(It, TrueBB);
2317   MF->insert(It, EndBB);
2318 
2319   // Transfer rest of current basic-block to EndBB
2320   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
2321                 MBB->end());
2322   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
2323 
2324   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
2325   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
2326   MBB->addSuccessor(TrueBB);
2327   MBB->addSuccessor(EndBB);
2328 
2329   // TrueBB falls through to the end.
2330   TrueBB->addSuccessor(EndBB);
2331 
2332   if (!NZCVKilled) {
2333     TrueBB->addLiveIn(AArch64::NZCV);
2334     EndBB->addLiveIn(AArch64::NZCV);
2335   }
2336 
2337   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
2338       .addReg(IfTrueReg)
2339       .addMBB(TrueBB)
2340       .addReg(IfFalseReg)
2341       .addMBB(MBB);
2342 
2343   MI.eraseFromParent();
2344   return EndBB;
2345 }
2346 
2347 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
2348        MachineInstr &MI, MachineBasicBlock *BB) const {
2349   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2350              BB->getParent()->getFunction().getPersonalityFn())) &&
2351          "SEH does not use catchret!");
2352   return BB;
2353 }
2354 
2355 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
2356     MachineInstr &MI, MachineBasicBlock *BB) const {
2357   switch (MI.getOpcode()) {
2358   default:
2359 #ifndef NDEBUG
2360     MI.dump();
2361 #endif
2362     llvm_unreachable("Unexpected instruction for custom inserter!");
2363 
2364   case AArch64::F128CSEL:
2365     return EmitF128CSEL(MI, BB);
2366 
2367   case TargetOpcode::STATEPOINT:
2368     // STATEPOINT is a pseudo instruction which has no implicit defs/uses
2369     // while bl call instruction (where statepoint will be lowered at the end)
2370     // has implicit def. Add this implicit dead def here as a workaround.
2371     MI.addOperand(*MI.getMF(), MachineOperand::CreateReg(AArch64::LR, true,
2372                                                          true, false, true));
2373     LLVM_FALLTHROUGH;
2374   case TargetOpcode::STACKMAP:
2375   case TargetOpcode::PATCHPOINT:
2376     return emitPatchPoint(MI, BB);
2377 
2378   case AArch64::CATCHRET:
2379     return EmitLoweredCatchRet(MI, BB);
2380   }
2381 }
2382 
2383 //===----------------------------------------------------------------------===//
2384 // AArch64 Lowering private implementation.
2385 //===----------------------------------------------------------------------===//
2386 
2387 //===----------------------------------------------------------------------===//
2388 // Lowering Code
2389 //===----------------------------------------------------------------------===//
2390 
2391 // Forward declarations of SVE fixed length lowering helpers
2392 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT);
2393 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2394 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2395 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
2396                                                 SelectionDAG &DAG);
2397 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
2398                                              EVT VT);
2399 
2400 /// isZerosVector - Check whether SDNode N is a zero-filled vector.
2401 static bool isZerosVector(const SDNode *N) {
2402   // Look through a bit convert.
2403   while (N->getOpcode() == ISD::BITCAST)
2404     N = N->getOperand(0).getNode();
2405 
2406   if (ISD::isConstantSplatVectorAllZeros(N))
2407     return true;
2408 
2409   if (N->getOpcode() != AArch64ISD::DUP)
2410     return false;
2411 
2412   auto Opnd0 = N->getOperand(0);
2413   auto *CINT = dyn_cast<ConstantSDNode>(Opnd0);
2414   auto *CFP = dyn_cast<ConstantFPSDNode>(Opnd0);
2415   return (CINT && CINT->isZero()) || (CFP && CFP->isZero());
2416 }
2417 
2418 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
2419 /// CC
2420 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
2421   switch (CC) {
2422   default:
2423     llvm_unreachable("Unknown condition code!");
2424   case ISD::SETNE:
2425     return AArch64CC::NE;
2426   case ISD::SETEQ:
2427     return AArch64CC::EQ;
2428   case ISD::SETGT:
2429     return AArch64CC::GT;
2430   case ISD::SETGE:
2431     return AArch64CC::GE;
2432   case ISD::SETLT:
2433     return AArch64CC::LT;
2434   case ISD::SETLE:
2435     return AArch64CC::LE;
2436   case ISD::SETUGT:
2437     return AArch64CC::HI;
2438   case ISD::SETUGE:
2439     return AArch64CC::HS;
2440   case ISD::SETULT:
2441     return AArch64CC::LO;
2442   case ISD::SETULE:
2443     return AArch64CC::LS;
2444   }
2445 }
2446 
2447 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
2448 static void changeFPCCToAArch64CC(ISD::CondCode CC,
2449                                   AArch64CC::CondCode &CondCode,
2450                                   AArch64CC::CondCode &CondCode2) {
2451   CondCode2 = AArch64CC::AL;
2452   switch (CC) {
2453   default:
2454     llvm_unreachable("Unknown FP condition!");
2455   case ISD::SETEQ:
2456   case ISD::SETOEQ:
2457     CondCode = AArch64CC::EQ;
2458     break;
2459   case ISD::SETGT:
2460   case ISD::SETOGT:
2461     CondCode = AArch64CC::GT;
2462     break;
2463   case ISD::SETGE:
2464   case ISD::SETOGE:
2465     CondCode = AArch64CC::GE;
2466     break;
2467   case ISD::SETOLT:
2468     CondCode = AArch64CC::MI;
2469     break;
2470   case ISD::SETOLE:
2471     CondCode = AArch64CC::LS;
2472     break;
2473   case ISD::SETONE:
2474     CondCode = AArch64CC::MI;
2475     CondCode2 = AArch64CC::GT;
2476     break;
2477   case ISD::SETO:
2478     CondCode = AArch64CC::VC;
2479     break;
2480   case ISD::SETUO:
2481     CondCode = AArch64CC::VS;
2482     break;
2483   case ISD::SETUEQ:
2484     CondCode = AArch64CC::EQ;
2485     CondCode2 = AArch64CC::VS;
2486     break;
2487   case ISD::SETUGT:
2488     CondCode = AArch64CC::HI;
2489     break;
2490   case ISD::SETUGE:
2491     CondCode = AArch64CC::PL;
2492     break;
2493   case ISD::SETLT:
2494   case ISD::SETULT:
2495     CondCode = AArch64CC::LT;
2496     break;
2497   case ISD::SETLE:
2498   case ISD::SETULE:
2499     CondCode = AArch64CC::LE;
2500     break;
2501   case ISD::SETNE:
2502   case ISD::SETUNE:
2503     CondCode = AArch64CC::NE;
2504     break;
2505   }
2506 }
2507 
2508 /// Convert a DAG fp condition code to an AArch64 CC.
2509 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2510 /// should be AND'ed instead of OR'ed.
2511 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2512                                      AArch64CC::CondCode &CondCode,
2513                                      AArch64CC::CondCode &CondCode2) {
2514   CondCode2 = AArch64CC::AL;
2515   switch (CC) {
2516   default:
2517     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2518     assert(CondCode2 == AArch64CC::AL);
2519     break;
2520   case ISD::SETONE:
2521     // (a one b)
2522     // == ((a olt b) || (a ogt b))
2523     // == ((a ord b) && (a une b))
2524     CondCode = AArch64CC::VC;
2525     CondCode2 = AArch64CC::NE;
2526     break;
2527   case ISD::SETUEQ:
2528     // (a ueq b)
2529     // == ((a uno b) || (a oeq b))
2530     // == ((a ule b) && (a uge b))
2531     CondCode = AArch64CC::PL;
2532     CondCode2 = AArch64CC::LE;
2533     break;
2534   }
2535 }
2536 
2537 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2538 /// CC usable with the vector instructions. Fewer operations are available
2539 /// without a real NZCV register, so we have to use less efficient combinations
2540 /// to get the same effect.
2541 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2542                                         AArch64CC::CondCode &CondCode,
2543                                         AArch64CC::CondCode &CondCode2,
2544                                         bool &Invert) {
2545   Invert = false;
2546   switch (CC) {
2547   default:
2548     // Mostly the scalar mappings work fine.
2549     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2550     break;
2551   case ISD::SETUO:
2552     Invert = true;
2553     LLVM_FALLTHROUGH;
2554   case ISD::SETO:
2555     CondCode = AArch64CC::MI;
2556     CondCode2 = AArch64CC::GE;
2557     break;
2558   case ISD::SETUEQ:
2559   case ISD::SETULT:
2560   case ISD::SETULE:
2561   case ISD::SETUGT:
2562   case ISD::SETUGE:
2563     // All of the compare-mask comparisons are ordered, but we can switch
2564     // between the two by a double inversion. E.g. ULE == !OGT.
2565     Invert = true;
2566     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2567                           CondCode, CondCode2);
2568     break;
2569   }
2570 }
2571 
2572 static bool isLegalArithImmed(uint64_t C) {
2573   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2574   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2575   LLVM_DEBUG(dbgs() << "Is imm " << C
2576                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2577   return IsLegal;
2578 }
2579 
2580 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
2581 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
2582 // can be set differently by this operation. It comes down to whether
2583 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
2584 // everything is fine. If not then the optimization is wrong. Thus general
2585 // comparisons are only valid if op2 != 0.
2586 //
2587 // So, finally, the only LLVM-native comparisons that don't mention C and V
2588 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
2589 // the absence of information about op2.
2590 static bool isCMN(SDValue Op, ISD::CondCode CC) {
2591   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
2592          (CC == ISD::SETEQ || CC == ISD::SETNE);
2593 }
2594 
2595 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
2596                                       SelectionDAG &DAG, SDValue Chain,
2597                                       bool IsSignaling) {
2598   EVT VT = LHS.getValueType();
2599   assert(VT != MVT::f128);
2600   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
2601   unsigned Opcode =
2602       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
2603   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
2604 }
2605 
2606 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2607                               const SDLoc &dl, SelectionDAG &DAG) {
2608   EVT VT = LHS.getValueType();
2609   const bool FullFP16 =
2610     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2611 
2612   if (VT.isFloatingPoint()) {
2613     assert(VT != MVT::f128);
2614     if (VT == MVT::f16 && !FullFP16) {
2615       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
2616       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
2617       VT = MVT::f32;
2618     }
2619     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
2620   }
2621 
2622   // The CMP instruction is just an alias for SUBS, and representing it as
2623   // SUBS means that it's possible to get CSE with subtract operations.
2624   // A later phase can perform the optimization of setting the destination
2625   // register to WZR/XZR if it ends up being unused.
2626   unsigned Opcode = AArch64ISD::SUBS;
2627 
2628   if (isCMN(RHS, CC)) {
2629     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2630     Opcode = AArch64ISD::ADDS;
2631     RHS = RHS.getOperand(1);
2632   } else if (isCMN(LHS, CC)) {
2633     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2634     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2635     Opcode = AArch64ISD::ADDS;
2636     LHS = LHS.getOperand(1);
2637   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2638     if (LHS.getOpcode() == ISD::AND) {
2639       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2640       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2641       // of the signed comparisons.
2642       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2643                                            DAG.getVTList(VT, MVT_CC),
2644                                            LHS.getOperand(0),
2645                                            LHS.getOperand(1));
2646       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2647       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2648       return ANDSNode.getValue(1);
2649     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2650       // Use result of ANDS
2651       return LHS.getValue(1);
2652     }
2653   }
2654 
2655   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2656       .getValue(1);
2657 }
2658 
2659 /// \defgroup AArch64CCMP CMP;CCMP matching
2660 ///
2661 /// These functions deal with the formation of CMP;CCMP;... sequences.
2662 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2663 /// a comparison. They set the NZCV flags to a predefined value if their
2664 /// predicate is false. This allows to express arbitrary conjunctions, for
2665 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2666 /// expressed as:
2667 ///   cmp A
2668 ///   ccmp B, inv(CB), CA
2669 ///   check for CB flags
2670 ///
2671 /// This naturally lets us implement chains of AND operations with SETCC
2672 /// operands. And we can even implement some other situations by transforming
2673 /// them:
2674 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2675 ///     negating the flags used in a CCMP/FCCMP operations.
2676 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2677 ///     by negating the flags we test for afterwards. i.e.
2678 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2679 ///   - Note that we can only ever negate all previously processed results.
2680 ///     What we can not implement by flipping the flags to test is a negation
2681 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2682 ///     far, so the 2nd sub-tree we emit would also affect the first).
2683 /// With those tools we can implement some OR operations:
2684 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2685 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2686 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2687 ///     elimination rules from earlier to implement the whole thing as a
2688 ///     CCMP/FCCMP chain.
2689 ///
2690 /// As complete example:
2691 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2692 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2693 /// can be reassociated to:
2694 ///     or (and (setCC (cmp C)) setCD (cmp D))
2695 //         (or (setCA (cmp A)) (setCB (cmp B)))
2696 /// can be transformed to:
2697 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2698 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2699 /// which can be implemented as:
2700 ///   cmp C
2701 ///   ccmp D, inv(CD), CC
2702 ///   ccmp A, CA, inv(CD)
2703 ///   ccmp B, CB, inv(CA)
2704 ///   check for CB flags
2705 ///
2706 /// A counterexample is "or (and A B) (and C D)" which translates to
2707 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2708 /// can only implement 1 of the inner (not) operations, but not both!
2709 /// @{
2710 
2711 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2712 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2713                                          ISD::CondCode CC, SDValue CCOp,
2714                                          AArch64CC::CondCode Predicate,
2715                                          AArch64CC::CondCode OutCC,
2716                                          const SDLoc &DL, SelectionDAG &DAG) {
2717   unsigned Opcode = 0;
2718   const bool FullFP16 =
2719     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2720 
2721   if (LHS.getValueType().isFloatingPoint()) {
2722     assert(LHS.getValueType() != MVT::f128);
2723     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2724       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2725       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2726     }
2727     Opcode = AArch64ISD::FCCMP;
2728   } else if (RHS.getOpcode() == ISD::SUB) {
2729     SDValue SubOp0 = RHS.getOperand(0);
2730     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2731       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2732       Opcode = AArch64ISD::CCMN;
2733       RHS = RHS.getOperand(1);
2734     }
2735   }
2736   if (Opcode == 0)
2737     Opcode = AArch64ISD::CCMP;
2738 
2739   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2740   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2741   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2742   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2743   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2744 }
2745 
2746 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2747 /// expressed as a conjunction. See \ref AArch64CCMP.
2748 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2749 ///                     changing the conditions on the SETCC tests.
2750 ///                     (this means we can call emitConjunctionRec() with
2751 ///                      Negate==true on this sub-tree)
2752 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2753 ///                     cannot do the negation naturally. We are required to
2754 ///                     emit the subtree first in this case.
2755 /// \param WillNegate   Is true if are called when the result of this
2756 ///                     subexpression must be negated. This happens when the
2757 ///                     outer expression is an OR. We can use this fact to know
2758 ///                     that we have a double negation (or (or ...) ...) that
2759 ///                     can be implemented for free.
2760 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2761                                bool &MustBeFirst, bool WillNegate,
2762                                unsigned Depth = 0) {
2763   if (!Val.hasOneUse())
2764     return false;
2765   unsigned Opcode = Val->getOpcode();
2766   if (Opcode == ISD::SETCC) {
2767     if (Val->getOperand(0).getValueType() == MVT::f128)
2768       return false;
2769     CanNegate = true;
2770     MustBeFirst = false;
2771     return true;
2772   }
2773   // Protect against exponential runtime and stack overflow.
2774   if (Depth > 6)
2775     return false;
2776   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2777     bool IsOR = Opcode == ISD::OR;
2778     SDValue O0 = Val->getOperand(0);
2779     SDValue O1 = Val->getOperand(1);
2780     bool CanNegateL;
2781     bool MustBeFirstL;
2782     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2783       return false;
2784     bool CanNegateR;
2785     bool MustBeFirstR;
2786     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2787       return false;
2788 
2789     if (MustBeFirstL && MustBeFirstR)
2790       return false;
2791 
2792     if (IsOR) {
2793       // For an OR expression we need to be able to naturally negate at least
2794       // one side or we cannot do the transformation at all.
2795       if (!CanNegateL && !CanNegateR)
2796         return false;
2797       // If we the result of the OR will be negated and we can naturally negate
2798       // the leafs, then this sub-tree as a whole negates naturally.
2799       CanNegate = WillNegate && CanNegateL && CanNegateR;
2800       // If we cannot naturally negate the whole sub-tree, then this must be
2801       // emitted first.
2802       MustBeFirst = !CanNegate;
2803     } else {
2804       assert(Opcode == ISD::AND && "Must be OR or AND");
2805       // We cannot naturally negate an AND operation.
2806       CanNegate = false;
2807       MustBeFirst = MustBeFirstL || MustBeFirstR;
2808     }
2809     return true;
2810   }
2811   return false;
2812 }
2813 
2814 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2815 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2816 /// Tries to transform the given i1 producing node @p Val to a series compare
2817 /// and conditional compare operations. @returns an NZCV flags producing node
2818 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2819 /// transformation was not possible.
2820 /// \p Negate is true if we want this sub-tree being negated just by changing
2821 /// SETCC conditions.
2822 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2823     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2824     AArch64CC::CondCode Predicate) {
2825   // We're at a tree leaf, produce a conditional comparison operation.
2826   unsigned Opcode = Val->getOpcode();
2827   if (Opcode == ISD::SETCC) {
2828     SDValue LHS = Val->getOperand(0);
2829     SDValue RHS = Val->getOperand(1);
2830     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2831     bool isInteger = LHS.getValueType().isInteger();
2832     if (Negate)
2833       CC = getSetCCInverse(CC, LHS.getValueType());
2834     SDLoc DL(Val);
2835     // Determine OutCC and handle FP special case.
2836     if (isInteger) {
2837       OutCC = changeIntCCToAArch64CC(CC);
2838     } else {
2839       assert(LHS.getValueType().isFloatingPoint());
2840       AArch64CC::CondCode ExtraCC;
2841       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2842       // Some floating point conditions can't be tested with a single condition
2843       // code. Construct an additional comparison in this case.
2844       if (ExtraCC != AArch64CC::AL) {
2845         SDValue ExtraCmp;
2846         if (!CCOp.getNode())
2847           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2848         else
2849           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2850                                                ExtraCC, DL, DAG);
2851         CCOp = ExtraCmp;
2852         Predicate = ExtraCC;
2853       }
2854     }
2855 
2856     // Produce a normal comparison if we are first in the chain
2857     if (!CCOp)
2858       return emitComparison(LHS, RHS, CC, DL, DAG);
2859     // Otherwise produce a ccmp.
2860     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2861                                      DAG);
2862   }
2863   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2864 
2865   bool IsOR = Opcode == ISD::OR;
2866 
2867   SDValue LHS = Val->getOperand(0);
2868   bool CanNegateL;
2869   bool MustBeFirstL;
2870   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2871   assert(ValidL && "Valid conjunction/disjunction tree");
2872   (void)ValidL;
2873 
2874   SDValue RHS = Val->getOperand(1);
2875   bool CanNegateR;
2876   bool MustBeFirstR;
2877   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2878   assert(ValidR && "Valid conjunction/disjunction tree");
2879   (void)ValidR;
2880 
2881   // Swap sub-tree that must come first to the right side.
2882   if (MustBeFirstL) {
2883     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2884     std::swap(LHS, RHS);
2885     std::swap(CanNegateL, CanNegateR);
2886     std::swap(MustBeFirstL, MustBeFirstR);
2887   }
2888 
2889   bool NegateR;
2890   bool NegateAfterR;
2891   bool NegateL;
2892   bool NegateAfterAll;
2893   if (Opcode == ISD::OR) {
2894     // Swap the sub-tree that we can negate naturally to the left.
2895     if (!CanNegateL) {
2896       assert(CanNegateR && "at least one side must be negatable");
2897       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2898       assert(!Negate);
2899       std::swap(LHS, RHS);
2900       NegateR = false;
2901       NegateAfterR = true;
2902     } else {
2903       // Negate the left sub-tree if possible, otherwise negate the result.
2904       NegateR = CanNegateR;
2905       NegateAfterR = !CanNegateR;
2906     }
2907     NegateL = true;
2908     NegateAfterAll = !Negate;
2909   } else {
2910     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2911     assert(!Negate && "Valid conjunction/disjunction tree");
2912 
2913     NegateL = false;
2914     NegateR = false;
2915     NegateAfterR = false;
2916     NegateAfterAll = false;
2917   }
2918 
2919   // Emit sub-trees.
2920   AArch64CC::CondCode RHSCC;
2921   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2922   if (NegateAfterR)
2923     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2924   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2925   if (NegateAfterAll)
2926     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2927   return CmpL;
2928 }
2929 
2930 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2931 /// In some cases this is even possible with OR operations in the expression.
2932 /// See \ref AArch64CCMP.
2933 /// \see emitConjunctionRec().
2934 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2935                                AArch64CC::CondCode &OutCC) {
2936   bool DummyCanNegate;
2937   bool DummyMustBeFirst;
2938   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2939     return SDValue();
2940 
2941   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2942 }
2943 
2944 /// @}
2945 
2946 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2947 /// extension operations.
2948 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2949   auto isSupportedExtend = [&](SDValue V) {
2950     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2951       return true;
2952 
2953     if (V.getOpcode() == ISD::AND)
2954       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2955         uint64_t Mask = MaskCst->getZExtValue();
2956         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2957       }
2958 
2959     return false;
2960   };
2961 
2962   if (!Op.hasOneUse())
2963     return 0;
2964 
2965   if (isSupportedExtend(Op))
2966     return 1;
2967 
2968   unsigned Opc = Op.getOpcode();
2969   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2970     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2971       uint64_t Shift = ShiftCst->getZExtValue();
2972       if (isSupportedExtend(Op.getOperand(0)))
2973         return (Shift <= 4) ? 2 : 1;
2974       EVT VT = Op.getValueType();
2975       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2976         return 1;
2977     }
2978 
2979   return 0;
2980 }
2981 
2982 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2983                              SDValue &AArch64cc, SelectionDAG &DAG,
2984                              const SDLoc &dl) {
2985   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2986     EVT VT = RHS.getValueType();
2987     uint64_t C = RHSC->getZExtValue();
2988     if (!isLegalArithImmed(C)) {
2989       // Constant does not fit, try adjusting it by one?
2990       switch (CC) {
2991       default:
2992         break;
2993       case ISD::SETLT:
2994       case ISD::SETGE:
2995         if ((VT == MVT::i32 && C != 0x80000000 &&
2996              isLegalArithImmed((uint32_t)(C - 1))) ||
2997             (VT == MVT::i64 && C != 0x80000000ULL &&
2998              isLegalArithImmed(C - 1ULL))) {
2999           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3000           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
3001           RHS = DAG.getConstant(C, dl, VT);
3002         }
3003         break;
3004       case ISD::SETULT:
3005       case ISD::SETUGE:
3006         if ((VT == MVT::i32 && C != 0 &&
3007              isLegalArithImmed((uint32_t)(C - 1))) ||
3008             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
3009           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3010           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
3011           RHS = DAG.getConstant(C, dl, VT);
3012         }
3013         break;
3014       case ISD::SETLE:
3015       case ISD::SETGT:
3016         if ((VT == MVT::i32 && C != INT32_MAX &&
3017              isLegalArithImmed((uint32_t)(C + 1))) ||
3018             (VT == MVT::i64 && C != INT64_MAX &&
3019              isLegalArithImmed(C + 1ULL))) {
3020           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3021           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
3022           RHS = DAG.getConstant(C, dl, VT);
3023         }
3024         break;
3025       case ISD::SETULE:
3026       case ISD::SETUGT:
3027         if ((VT == MVT::i32 && C != UINT32_MAX &&
3028              isLegalArithImmed((uint32_t)(C + 1))) ||
3029             (VT == MVT::i64 && C != UINT64_MAX &&
3030              isLegalArithImmed(C + 1ULL))) {
3031           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3032           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
3033           RHS = DAG.getConstant(C, dl, VT);
3034         }
3035         break;
3036       }
3037     }
3038   }
3039 
3040   // Comparisons are canonicalized so that the RHS operand is simpler than the
3041   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
3042   // can fold some shift+extend operations on the RHS operand, so swap the
3043   // operands if that can be done.
3044   //
3045   // For example:
3046   //    lsl     w13, w11, #1
3047   //    cmp     w13, w12
3048   // can be turned into:
3049   //    cmp     w12, w11, lsl #1
3050   if (!isa<ConstantSDNode>(RHS) ||
3051       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
3052     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
3053 
3054     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
3055       std::swap(LHS, RHS);
3056       CC = ISD::getSetCCSwappedOperands(CC);
3057     }
3058   }
3059 
3060   SDValue Cmp;
3061   AArch64CC::CondCode AArch64CC;
3062   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
3063     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
3064 
3065     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
3066     // For the i8 operand, the largest immediate is 255, so this can be easily
3067     // encoded in the compare instruction. For the i16 operand, however, the
3068     // largest immediate cannot be encoded in the compare.
3069     // Therefore, use a sign extending load and cmn to avoid materializing the
3070     // -1 constant. For example,
3071     // movz w1, #65535
3072     // ldrh w0, [x0, #0]
3073     // cmp w0, w1
3074     // >
3075     // ldrsh w0, [x0, #0]
3076     // cmn w0, #1
3077     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
3078     // if and only if (sext LHS) == (sext RHS). The checks are in place to
3079     // ensure both the LHS and RHS are truly zero extended and to make sure the
3080     // transformation is profitable.
3081     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
3082         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
3083         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
3084         LHS.getNode()->hasNUsesOfValue(1, 0)) {
3085       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
3086       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
3087         SDValue SExt =
3088             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
3089                         DAG.getValueType(MVT::i16));
3090         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
3091                                                    RHS.getValueType()),
3092                              CC, dl, DAG);
3093         AArch64CC = changeIntCCToAArch64CC(CC);
3094       }
3095     }
3096 
3097     if (!Cmp && (RHSC->isZero() || RHSC->isOne())) {
3098       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
3099         if ((CC == ISD::SETNE) ^ RHSC->isZero())
3100           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
3101       }
3102     }
3103   }
3104 
3105   if (!Cmp) {
3106     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3107     AArch64CC = changeIntCCToAArch64CC(CC);
3108   }
3109   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
3110   return Cmp;
3111 }
3112 
3113 static std::pair<SDValue, SDValue>
3114 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
3115   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
3116          "Unsupported value type");
3117   SDValue Value, Overflow;
3118   SDLoc DL(Op);
3119   SDValue LHS = Op.getOperand(0);
3120   SDValue RHS = Op.getOperand(1);
3121   unsigned Opc = 0;
3122   switch (Op.getOpcode()) {
3123   default:
3124     llvm_unreachable("Unknown overflow instruction!");
3125   case ISD::SADDO:
3126     Opc = AArch64ISD::ADDS;
3127     CC = AArch64CC::VS;
3128     break;
3129   case ISD::UADDO:
3130     Opc = AArch64ISD::ADDS;
3131     CC = AArch64CC::HS;
3132     break;
3133   case ISD::SSUBO:
3134     Opc = AArch64ISD::SUBS;
3135     CC = AArch64CC::VS;
3136     break;
3137   case ISD::USUBO:
3138     Opc = AArch64ISD::SUBS;
3139     CC = AArch64CC::LO;
3140     break;
3141   // Multiply needs a little bit extra work.
3142   case ISD::SMULO:
3143   case ISD::UMULO: {
3144     CC = AArch64CC::NE;
3145     bool IsSigned = Op.getOpcode() == ISD::SMULO;
3146     if (Op.getValueType() == MVT::i32) {
3147       // Extend to 64-bits, then perform a 64-bit multiply.
3148       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3149       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
3150       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
3151       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3152       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3153 
3154       // Check that the result fits into a 32-bit integer.
3155       SDVTList VTs = DAG.getVTList(MVT::i64, MVT_CC);
3156       if (IsSigned) {
3157         // cmp xreg, wreg, sxtw
3158         SDValue SExtMul = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Value);
3159         Overflow =
3160             DAG.getNode(AArch64ISD::SUBS, DL, VTs, Mul, SExtMul).getValue(1);
3161       } else {
3162         // tst xreg, #0xffffffff00000000
3163         SDValue UpperBits = DAG.getConstant(0xFFFFFFFF00000000, DL, MVT::i64);
3164         Overflow =
3165             DAG.getNode(AArch64ISD::ANDS, DL, VTs, Mul, UpperBits).getValue(1);
3166       }
3167       break;
3168     }
3169     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
3170     // For the 64 bit multiply
3171     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3172     if (IsSigned) {
3173       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
3174       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
3175                                       DAG.getConstant(63, DL, MVT::i64));
3176       // It is important that LowerBits is last, otherwise the arithmetic
3177       // shift will not be folded into the compare (SUBS).
3178       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3179       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
3180                      .getValue(1);
3181     } else {
3182       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
3183       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3184       Overflow =
3185           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
3186                       DAG.getConstant(0, DL, MVT::i64),
3187                       UpperBits).getValue(1);
3188     }
3189     break;
3190   }
3191   } // switch (...)
3192 
3193   if (Opc) {
3194     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
3195 
3196     // Emit the AArch64 operation with overflow check.
3197     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
3198     Overflow = Value.getValue(1);
3199   }
3200   return std::make_pair(Value, Overflow);
3201 }
3202 
3203 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
3204   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3205     return LowerToScalableOp(Op, DAG);
3206 
3207   SDValue Sel = Op.getOperand(0);
3208   SDValue Other = Op.getOperand(1);
3209   SDLoc dl(Sel);
3210 
3211   // If the operand is an overflow checking operation, invert the condition
3212   // code and kill the Not operation. I.e., transform:
3213   // (xor (overflow_op_bool, 1))
3214   //   -->
3215   // (csel 1, 0, invert(cc), overflow_op_bool)
3216   // ... which later gets transformed to just a cset instruction with an
3217   // inverted condition code, rather than a cset + eor sequence.
3218   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
3219     // Only lower legal XALUO ops.
3220     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
3221       return SDValue();
3222 
3223     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3224     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3225     AArch64CC::CondCode CC;
3226     SDValue Value, Overflow;
3227     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
3228     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3229     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
3230                        CCVal, Overflow);
3231   }
3232   // If neither operand is a SELECT_CC, give up.
3233   if (Sel.getOpcode() != ISD::SELECT_CC)
3234     std::swap(Sel, Other);
3235   if (Sel.getOpcode() != ISD::SELECT_CC)
3236     return Op;
3237 
3238   // The folding we want to perform is:
3239   // (xor x, (select_cc a, b, cc, 0, -1) )
3240   //   -->
3241   // (csel x, (xor x, -1), cc ...)
3242   //
3243   // The latter will get matched to a CSINV instruction.
3244 
3245   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
3246   SDValue LHS = Sel.getOperand(0);
3247   SDValue RHS = Sel.getOperand(1);
3248   SDValue TVal = Sel.getOperand(2);
3249   SDValue FVal = Sel.getOperand(3);
3250 
3251   // FIXME: This could be generalized to non-integer comparisons.
3252   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
3253     return Op;
3254 
3255   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3256   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3257 
3258   // The values aren't constants, this isn't the pattern we're looking for.
3259   if (!CFVal || !CTVal)
3260     return Op;
3261 
3262   // We can commute the SELECT_CC by inverting the condition.  This
3263   // might be needed to make this fit into a CSINV pattern.
3264   if (CTVal->isAllOnes() && CFVal->isZero()) {
3265     std::swap(TVal, FVal);
3266     std::swap(CTVal, CFVal);
3267     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
3268   }
3269 
3270   // If the constants line up, perform the transform!
3271   if (CTVal->isZero() && CFVal->isAllOnes()) {
3272     SDValue CCVal;
3273     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3274 
3275     FVal = Other;
3276     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
3277                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
3278 
3279     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
3280                        CCVal, Cmp);
3281   }
3282 
3283   return Op;
3284 }
3285 
3286 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
3287   EVT VT = Op.getValueType();
3288 
3289   // Let legalize expand this if it isn't a legal type yet.
3290   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3291     return SDValue();
3292 
3293   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3294 
3295   unsigned Opc;
3296   bool ExtraOp = false;
3297   switch (Op.getOpcode()) {
3298   default:
3299     llvm_unreachable("Invalid code");
3300   case ISD::ADDC:
3301     Opc = AArch64ISD::ADDS;
3302     break;
3303   case ISD::SUBC:
3304     Opc = AArch64ISD::SUBS;
3305     break;
3306   case ISD::ADDE:
3307     Opc = AArch64ISD::ADCS;
3308     ExtraOp = true;
3309     break;
3310   case ISD::SUBE:
3311     Opc = AArch64ISD::SBCS;
3312     ExtraOp = true;
3313     break;
3314   }
3315 
3316   if (!ExtraOp)
3317     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
3318   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
3319                      Op.getOperand(2));
3320 }
3321 
3322 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
3323   // Let legalize expand this if it isn't a legal type yet.
3324   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3325     return SDValue();
3326 
3327   SDLoc dl(Op);
3328   AArch64CC::CondCode CC;
3329   // The actual operation that sets the overflow or carry flag.
3330   SDValue Value, Overflow;
3331   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
3332 
3333   // We use 0 and 1 as false and true values.
3334   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3335   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3336 
3337   // We use an inverted condition, because the conditional select is inverted
3338   // too. This will allow it to be selected to a single instruction:
3339   // CSINC Wd, WZR, WZR, invert(cond).
3340   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3341   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
3342                          CCVal, Overflow);
3343 
3344   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3345   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3346 }
3347 
3348 // Prefetch operands are:
3349 // 1: Address to prefetch
3350 // 2: bool isWrite
3351 // 3: int locality (0 = no locality ... 3 = extreme locality)
3352 // 4: bool isDataCache
3353 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
3354   SDLoc DL(Op);
3355   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3356   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
3357   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3358 
3359   bool IsStream = !Locality;
3360   // When the locality number is set
3361   if (Locality) {
3362     // The front-end should have filtered out the out-of-range values
3363     assert(Locality <= 3 && "Prefetch locality out-of-range");
3364     // The locality degree is the opposite of the cache speed.
3365     // Put the number the other way around.
3366     // The encoding starts at 0 for level 1
3367     Locality = 3 - Locality;
3368   }
3369 
3370   // built the mask value encoding the expected behavior.
3371   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
3372                    (!IsData << 3) |     // IsDataCache bit
3373                    (Locality << 1) |    // Cache level bits
3374                    (unsigned)IsStream;  // Stream bit
3375   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
3376                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
3377 }
3378 
3379 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
3380                                               SelectionDAG &DAG) const {
3381   EVT VT = Op.getValueType();
3382   if (VT.isScalableVector())
3383     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
3384 
3385   if (useSVEForFixedLengthVectorVT(VT))
3386     return LowerFixedLengthFPExtendToSVE(Op, DAG);
3387 
3388   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
3389   return SDValue();
3390 }
3391 
3392 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
3393                                              SelectionDAG &DAG) const {
3394   if (Op.getValueType().isScalableVector())
3395     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
3396 
3397   bool IsStrict = Op->isStrictFPOpcode();
3398   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3399   EVT SrcVT = SrcVal.getValueType();
3400 
3401   if (useSVEForFixedLengthVectorVT(SrcVT))
3402     return LowerFixedLengthFPRoundToSVE(Op, DAG);
3403 
3404   if (SrcVT != MVT::f128) {
3405     // Expand cases where the input is a vector bigger than NEON.
3406     if (useSVEForFixedLengthVectorVT(SrcVT))
3407       return SDValue();
3408 
3409     // It's legal except when f128 is involved
3410     return Op;
3411   }
3412 
3413   return SDValue();
3414 }
3415 
3416 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
3417                                                     SelectionDAG &DAG) const {
3418   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3419   // Any additional optimization in this function should be recorded
3420   // in the cost tables.
3421   EVT InVT = Op.getOperand(0).getValueType();
3422   EVT VT = Op.getValueType();
3423 
3424   if (VT.isScalableVector()) {
3425     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3426                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3427                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3428     return LowerToPredicatedOp(Op, DAG, Opcode);
3429   }
3430 
3431   if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
3432     return LowerFixedLengthFPToIntToSVE(Op, DAG);
3433 
3434   unsigned NumElts = InVT.getVectorNumElements();
3435 
3436   // f16 conversions are promoted to f32 when full fp16 is not supported.
3437   if (InVT.getVectorElementType() == MVT::f16 &&
3438       !Subtarget->hasFullFP16()) {
3439     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3440     SDLoc dl(Op);
3441     return DAG.getNode(
3442         Op.getOpcode(), dl, Op.getValueType(),
3443         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3444   }
3445 
3446   uint64_t VTSize = VT.getFixedSizeInBits();
3447   uint64_t InVTSize = InVT.getFixedSizeInBits();
3448   if (VTSize < InVTSize) {
3449     SDLoc dl(Op);
3450     SDValue Cv =
3451         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3452                     Op.getOperand(0));
3453     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3454   }
3455 
3456   if (VTSize > InVTSize) {
3457     SDLoc dl(Op);
3458     MVT ExtVT =
3459         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3460                          VT.getVectorNumElements());
3461     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3462     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3463   }
3464 
3465   // Type changing conversions are illegal.
3466   return Op;
3467 }
3468 
3469 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3470                                               SelectionDAG &DAG) const {
3471   bool IsStrict = Op->isStrictFPOpcode();
3472   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3473 
3474   if (SrcVal.getValueType().isVector())
3475     return LowerVectorFP_TO_INT(Op, DAG);
3476 
3477   // f16 conversions are promoted to f32 when full fp16 is not supported.
3478   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3479     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3480     SDLoc dl(Op);
3481     return DAG.getNode(
3482         Op.getOpcode(), dl, Op.getValueType(),
3483         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3484   }
3485 
3486   if (SrcVal.getValueType() != MVT::f128) {
3487     // It's legal except when f128 is involved
3488     return Op;
3489   }
3490 
3491   return SDValue();
3492 }
3493 
3494 SDValue
3495 AArch64TargetLowering::LowerVectorFP_TO_INT_SAT(SDValue Op,
3496                                                 SelectionDAG &DAG) const {
3497   // AArch64 FP-to-int conversions saturate to the destination element size, so
3498   // we can lower common saturating conversions to simple instructions.
3499   SDValue SrcVal = Op.getOperand(0);
3500   EVT SrcVT = SrcVal.getValueType();
3501   EVT DstVT = Op.getValueType();
3502   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3503 
3504   uint64_t SrcElementWidth = SrcVT.getScalarSizeInBits();
3505   uint64_t DstElementWidth = DstVT.getScalarSizeInBits();
3506   uint64_t SatWidth = SatVT.getScalarSizeInBits();
3507   assert(SatWidth <= DstElementWidth &&
3508          "Saturation width cannot exceed result width");
3509 
3510   // TODO: Consider lowering to SVE operations, as in LowerVectorFP_TO_INT.
3511   // Currently, the `llvm.fpto[su]i.sat.*` instrinsics don't accept scalable
3512   // types, so this is hard to reach.
3513   if (DstVT.isScalableVector())
3514     return SDValue();
3515 
3516   EVT SrcElementVT = SrcVT.getVectorElementType();
3517 
3518   // In the absence of FP16 support, promote f16 to f32 and saturate the result.
3519   if (SrcElementVT == MVT::f16 &&
3520       (!Subtarget->hasFullFP16() || DstElementWidth > 16)) {
3521     MVT F32VT = MVT::getVectorVT(MVT::f32, SrcVT.getVectorNumElements());
3522     SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), F32VT, SrcVal);
3523     SrcVT = F32VT;
3524     SrcElementVT = MVT::f32;
3525     SrcElementWidth = 32;
3526   } else if (SrcElementVT != MVT::f64 && SrcElementVT != MVT::f32 &&
3527              SrcElementVT != MVT::f16)
3528     return SDValue();
3529 
3530   SDLoc DL(Op);
3531   // Cases that we can emit directly.
3532   if (SrcElementWidth == DstElementWidth && SrcElementWidth == SatWidth)
3533     return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
3534                        DAG.getValueType(DstVT.getScalarType()));
3535 
3536   // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
3537   // result. This is only valid if the legal cvt is larger than the saturate
3538   // width. For double, as we don't have MIN/MAX, it can be simpler to scalarize
3539   // (at least until sqxtn is selected).
3540   if (SrcElementWidth < SatWidth || SrcElementVT == MVT::f64)
3541     return SDValue();
3542 
3543   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
3544   SDValue NativeCvt = DAG.getNode(Op.getOpcode(), DL, IntVT, SrcVal,
3545                                   DAG.getValueType(IntVT.getScalarType()));
3546   SDValue Sat;
3547   if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
3548     SDValue MinC = DAG.getConstant(
3549         APInt::getSignedMaxValue(SatWidth).sextOrSelf(SrcElementWidth), DL,
3550         IntVT);
3551     SDValue Min = DAG.getNode(ISD::SMIN, DL, IntVT, NativeCvt, MinC);
3552     SDValue MaxC = DAG.getConstant(
3553         APInt::getSignedMinValue(SatWidth).sextOrSelf(SrcElementWidth), DL,
3554         IntVT);
3555     Sat = DAG.getNode(ISD::SMAX, DL, IntVT, Min, MaxC);
3556   } else {
3557     SDValue MinC = DAG.getConstant(
3558         APInt::getAllOnesValue(SatWidth).zextOrSelf(SrcElementWidth), DL,
3559         IntVT);
3560     Sat = DAG.getNode(ISD::UMIN, DL, IntVT, NativeCvt, MinC);
3561   }
3562 
3563   return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
3564 }
3565 
3566 SDValue AArch64TargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
3567                                                   SelectionDAG &DAG) const {
3568   // AArch64 FP-to-int conversions saturate to the destination register size, so
3569   // we can lower common saturating conversions to simple instructions.
3570   SDValue SrcVal = Op.getOperand(0);
3571   EVT SrcVT = SrcVal.getValueType();
3572 
3573   if (SrcVT.isVector())
3574     return LowerVectorFP_TO_INT_SAT(Op, DAG);
3575 
3576   EVT DstVT = Op.getValueType();
3577   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3578   uint64_t SatWidth = SatVT.getScalarSizeInBits();
3579   uint64_t DstWidth = DstVT.getScalarSizeInBits();
3580   assert(SatWidth <= DstWidth && "Saturation width cannot exceed result width");
3581 
3582   // In the absence of FP16 support, promote f16 to f32 and saturate the result.
3583   if (SrcVT == MVT::f16 && !Subtarget->hasFullFP16()) {
3584     SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, SrcVal);
3585     SrcVT = MVT::f32;
3586   } else if (SrcVT != MVT::f64 && SrcVT != MVT::f32 && SrcVT != MVT::f16)
3587     return SDValue();
3588 
3589   SDLoc DL(Op);
3590   // Cases that we can emit directly.
3591   if ((SrcVT == MVT::f64 || SrcVT == MVT::f32 ||
3592        (SrcVT == MVT::f16 && Subtarget->hasFullFP16())) &&
3593       DstVT == SatVT && (DstVT == MVT::i64 || DstVT == MVT::i32))
3594     return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
3595                        DAG.getValueType(DstVT));
3596 
3597   // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
3598   // result. This is only valid if the legal cvt is larger than the saturate
3599   // width.
3600   if (DstWidth < SatWidth)
3601     return SDValue();
3602 
3603   SDValue NativeCvt =
3604       DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal, DAG.getValueType(DstVT));
3605   SDValue Sat;
3606   if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
3607     SDValue MinC = DAG.getConstant(
3608         APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth), DL, DstVT);
3609     SDValue Min = DAG.getNode(ISD::SMIN, DL, DstVT, NativeCvt, MinC);
3610     SDValue MaxC = DAG.getConstant(
3611         APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth), DL, DstVT);
3612     Sat = DAG.getNode(ISD::SMAX, DL, DstVT, Min, MaxC);
3613   } else {
3614     SDValue MinC = DAG.getConstant(
3615         APInt::getAllOnesValue(SatWidth).zextOrSelf(DstWidth), DL, DstVT);
3616     Sat = DAG.getNode(ISD::UMIN, DL, DstVT, NativeCvt, MinC);
3617   }
3618 
3619   return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
3620 }
3621 
3622 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3623                                                     SelectionDAG &DAG) const {
3624   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3625   // Any additional optimization in this function should be recorded
3626   // in the cost tables.
3627   EVT VT = Op.getValueType();
3628   SDLoc dl(Op);
3629   SDValue In = Op.getOperand(0);
3630   EVT InVT = In.getValueType();
3631   unsigned Opc = Op.getOpcode();
3632   bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
3633 
3634   if (VT.isScalableVector()) {
3635     if (InVT.getVectorElementType() == MVT::i1) {
3636       // We can't directly extend an SVE predicate; extend it first.
3637       unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3638       EVT CastVT = getPromotedVTForPredicate(InVT);
3639       In = DAG.getNode(CastOpc, dl, CastVT, In);
3640       return DAG.getNode(Opc, dl, VT, In);
3641     }
3642 
3643     unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
3644                                : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
3645     return LowerToPredicatedOp(Op, DAG, Opcode);
3646   }
3647 
3648   if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
3649     return LowerFixedLengthIntToFPToSVE(Op, DAG);
3650 
3651   uint64_t VTSize = VT.getFixedSizeInBits();
3652   uint64_t InVTSize = InVT.getFixedSizeInBits();
3653   if (VTSize < InVTSize) {
3654     MVT CastVT =
3655         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3656                          InVT.getVectorNumElements());
3657     In = DAG.getNode(Opc, dl, CastVT, In);
3658     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3659   }
3660 
3661   if (VTSize > InVTSize) {
3662     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3663     EVT CastVT = VT.changeVectorElementTypeToInteger();
3664     In = DAG.getNode(CastOpc, dl, CastVT, In);
3665     return DAG.getNode(Opc, dl, VT, In);
3666   }
3667 
3668   return Op;
3669 }
3670 
3671 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3672                                             SelectionDAG &DAG) const {
3673   if (Op.getValueType().isVector())
3674     return LowerVectorINT_TO_FP(Op, DAG);
3675 
3676   bool IsStrict = Op->isStrictFPOpcode();
3677   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3678 
3679   // f16 conversions are promoted to f32 when full fp16 is not supported.
3680   if (Op.getValueType() == MVT::f16 &&
3681       !Subtarget->hasFullFP16()) {
3682     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3683     SDLoc dl(Op);
3684     return DAG.getNode(
3685         ISD::FP_ROUND, dl, MVT::f16,
3686         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3687         DAG.getIntPtrConstant(0, dl));
3688   }
3689 
3690   // i128 conversions are libcalls.
3691   if (SrcVal.getValueType() == MVT::i128)
3692     return SDValue();
3693 
3694   // Other conversions are legal, unless it's to the completely software-based
3695   // fp128.
3696   if (Op.getValueType() != MVT::f128)
3697     return Op;
3698   return SDValue();
3699 }
3700 
3701 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3702                                             SelectionDAG &DAG) const {
3703   // For iOS, we want to call an alternative entry point: __sincos_stret,
3704   // which returns the values in two S / D registers.
3705   SDLoc dl(Op);
3706   SDValue Arg = Op.getOperand(0);
3707   EVT ArgVT = Arg.getValueType();
3708   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3709 
3710   ArgListTy Args;
3711   ArgListEntry Entry;
3712 
3713   Entry.Node = Arg;
3714   Entry.Ty = ArgTy;
3715   Entry.IsSExt = false;
3716   Entry.IsZExt = false;
3717   Args.push_back(Entry);
3718 
3719   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3720                                         : RTLIB::SINCOS_STRET_F32;
3721   const char *LibcallName = getLibcallName(LC);
3722   SDValue Callee =
3723       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3724 
3725   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3726   TargetLowering::CallLoweringInfo CLI(DAG);
3727   CLI.setDebugLoc(dl)
3728       .setChain(DAG.getEntryNode())
3729       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3730 
3731   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3732   return CallResult.first;
3733 }
3734 
3735 static MVT getSVEContainerType(EVT ContentTy);
3736 
3737 SDValue AArch64TargetLowering::LowerBITCAST(SDValue Op,
3738                                             SelectionDAG &DAG) const {
3739   EVT OpVT = Op.getValueType();
3740   EVT ArgVT = Op.getOperand(0).getValueType();
3741 
3742   if (useSVEForFixedLengthVectorVT(OpVT))
3743     return LowerFixedLengthBitcastToSVE(Op, DAG);
3744 
3745   if (OpVT.isScalableVector()) {
3746     if (isTypeLegal(OpVT) && !isTypeLegal(ArgVT)) {
3747       assert(OpVT.isFloatingPoint() && !ArgVT.isFloatingPoint() &&
3748              "Expected int->fp bitcast!");
3749       SDValue ExtResult =
3750           DAG.getNode(ISD::ANY_EXTEND, SDLoc(Op), getSVEContainerType(ArgVT),
3751                       Op.getOperand(0));
3752       return getSVESafeBitCast(OpVT, ExtResult, DAG);
3753     }
3754     return getSVESafeBitCast(OpVT, Op.getOperand(0), DAG);
3755   }
3756 
3757   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3758     return SDValue();
3759 
3760   // Bitcasts between f16 and bf16 are legal.
3761   if (ArgVT == MVT::f16 || ArgVT == MVT::bf16)
3762     return Op;
3763 
3764   assert(ArgVT == MVT::i16);
3765   SDLoc DL(Op);
3766 
3767   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3768   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3769   return SDValue(
3770       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3771                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3772       0);
3773 }
3774 
3775 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3776   if (OrigVT.getSizeInBits() >= 64)
3777     return OrigVT;
3778 
3779   assert(OrigVT.isSimple() && "Expecting a simple value type");
3780 
3781   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3782   switch (OrigSimpleTy) {
3783   default: llvm_unreachable("Unexpected Vector Type");
3784   case MVT::v2i8:
3785   case MVT::v2i16:
3786      return MVT::v2i32;
3787   case MVT::v4i8:
3788     return  MVT::v4i16;
3789   }
3790 }
3791 
3792 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3793                                                  const EVT &OrigTy,
3794                                                  const EVT &ExtTy,
3795                                                  unsigned ExtOpcode) {
3796   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3797   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3798   // 64-bits we need to insert a new extension so that it will be 64-bits.
3799   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3800   if (OrigTy.getSizeInBits() >= 64)
3801     return N;
3802 
3803   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3804   EVT NewVT = getExtensionTo64Bits(OrigTy);
3805 
3806   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3807 }
3808 
3809 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3810                                    bool isSigned) {
3811   EVT VT = N->getValueType(0);
3812 
3813   if (N->getOpcode() != ISD::BUILD_VECTOR)
3814     return false;
3815 
3816   for (const SDValue &Elt : N->op_values()) {
3817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3818       unsigned EltSize = VT.getScalarSizeInBits();
3819       unsigned HalfSize = EltSize / 2;
3820       if (isSigned) {
3821         if (!isIntN(HalfSize, C->getSExtValue()))
3822           return false;
3823       } else {
3824         if (!isUIntN(HalfSize, C->getZExtValue()))
3825           return false;
3826       }
3827       continue;
3828     }
3829     return false;
3830   }
3831 
3832   return true;
3833 }
3834 
3835 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3836   if (N->getOpcode() == ISD::SIGN_EXTEND ||
3837       N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
3838     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3839                                              N->getOperand(0)->getValueType(0),
3840                                              N->getValueType(0),
3841                                              N->getOpcode());
3842 
3843   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3844   EVT VT = N->getValueType(0);
3845   SDLoc dl(N);
3846   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3847   unsigned NumElts = VT.getVectorNumElements();
3848   MVT TruncVT = MVT::getIntegerVT(EltSize);
3849   SmallVector<SDValue, 8> Ops;
3850   for (unsigned i = 0; i != NumElts; ++i) {
3851     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3852     const APInt &CInt = C->getAPIntValue();
3853     // Element types smaller than 32 bits are not legal, so use i32 elements.
3854     // The values are implicitly truncated so sext vs. zext doesn't matter.
3855     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3856   }
3857   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3858 }
3859 
3860 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3861   return N->getOpcode() == ISD::SIGN_EXTEND ||
3862          N->getOpcode() == ISD::ANY_EXTEND ||
3863          isExtendedBUILD_VECTOR(N, DAG, true);
3864 }
3865 
3866 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3867   return N->getOpcode() == ISD::ZERO_EXTEND ||
3868          N->getOpcode() == ISD::ANY_EXTEND ||
3869          isExtendedBUILD_VECTOR(N, DAG, false);
3870 }
3871 
3872 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3873   unsigned Opcode = N->getOpcode();
3874   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3875     SDNode *N0 = N->getOperand(0).getNode();
3876     SDNode *N1 = N->getOperand(1).getNode();
3877     return N0->hasOneUse() && N1->hasOneUse() &&
3878       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3879   }
3880   return false;
3881 }
3882 
3883 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3884   unsigned Opcode = N->getOpcode();
3885   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3886     SDNode *N0 = N->getOperand(0).getNode();
3887     SDNode *N1 = N->getOperand(1).getNode();
3888     return N0->hasOneUse() && N1->hasOneUse() &&
3889       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3890   }
3891   return false;
3892 }
3893 
3894 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3895                                                 SelectionDAG &DAG) const {
3896   // The rounding mode is in bits 23:22 of the FPSCR.
3897   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3898   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3899   // so that the shift + and get folded into a bitfield extract.
3900   SDLoc dl(Op);
3901 
3902   SDValue Chain = Op.getOperand(0);
3903   SDValue FPCR_64 = DAG.getNode(
3904       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3905       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3906   Chain = FPCR_64.getValue(1);
3907   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3908   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3909                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3910   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3911                               DAG.getConstant(22, dl, MVT::i32));
3912   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3913                             DAG.getConstant(3, dl, MVT::i32));
3914   return DAG.getMergeValues({AND, Chain}, dl);
3915 }
3916 
3917 SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op,
3918                                                  SelectionDAG &DAG) const {
3919   SDLoc DL(Op);
3920   SDValue Chain = Op->getOperand(0);
3921   SDValue RMValue = Op->getOperand(1);
3922 
3923   // The rounding mode is in bits 23:22 of the FPCR.
3924   // The llvm.set.rounding argument value to the rounding mode in FPCR mapping
3925   // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
3926   // ((arg - 1) & 3) << 22).
3927   //
3928   // The argument of llvm.set.rounding must be within the segment [0, 3], so
3929   // NearestTiesToAway (4) is not handled here. It is responsibility of the code
3930   // generated llvm.set.rounding to ensure this condition.
3931 
3932   // Calculate new value of FPCR[23:22].
3933   RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
3934                         DAG.getConstant(1, DL, MVT::i32));
3935   RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
3936                         DAG.getConstant(0x3, DL, MVT::i32));
3937   RMValue =
3938       DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
3939                   DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32));
3940   RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue);
3941 
3942   // Get current value of FPCR.
3943   SDValue Ops[] = {
3944       Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)};
3945   SDValue FPCR =
3946       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops);
3947   Chain = FPCR.getValue(1);
3948   FPCR = FPCR.getValue(0);
3949 
3950   // Put new rounding mode into FPSCR[23:22].
3951   const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos);
3952   FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR,
3953                      DAG.getConstant(RMMask, DL, MVT::i64));
3954   FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue);
3955   SDValue Ops2[] = {
3956       Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64),
3957       FPCR};
3958   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
3959 }
3960 
3961 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3962   EVT VT = Op.getValueType();
3963 
3964   // If SVE is available then i64 vector multiplications can also be made legal.
3965   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3966 
3967   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3968     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3969 
3970   // Multiplications are only custom-lowered for 128-bit vectors so that
3971   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3972   assert(VT.is128BitVector() && VT.isInteger() &&
3973          "unexpected type for custom-lowering ISD::MUL");
3974   SDNode *N0 = Op.getOperand(0).getNode();
3975   SDNode *N1 = Op.getOperand(1).getNode();
3976   unsigned NewOpc = 0;
3977   bool isMLA = false;
3978   bool isN0SExt = isSignExtended(N0, DAG);
3979   bool isN1SExt = isSignExtended(N1, DAG);
3980   if (isN0SExt && isN1SExt)
3981     NewOpc = AArch64ISD::SMULL;
3982   else {
3983     bool isN0ZExt = isZeroExtended(N0, DAG);
3984     bool isN1ZExt = isZeroExtended(N1, DAG);
3985     if (isN0ZExt && isN1ZExt)
3986       NewOpc = AArch64ISD::UMULL;
3987     else if (isN1SExt || isN1ZExt) {
3988       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3989       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3990       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3991         NewOpc = AArch64ISD::SMULL;
3992         isMLA = true;
3993       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3994         NewOpc =  AArch64ISD::UMULL;
3995         isMLA = true;
3996       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3997         std::swap(N0, N1);
3998         NewOpc =  AArch64ISD::UMULL;
3999         isMLA = true;
4000       }
4001     }
4002 
4003     if (!NewOpc) {
4004       if (VT == MVT::v2i64)
4005         // Fall through to expand this.  It is not legal.
4006         return SDValue();
4007       else
4008         // Other vector multiplications are legal.
4009         return Op;
4010     }
4011   }
4012 
4013   // Legalize to a S/UMULL instruction
4014   SDLoc DL(Op);
4015   SDValue Op0;
4016   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
4017   if (!isMLA) {
4018     Op0 = skipExtensionForVectorMULL(N0, DAG);
4019     assert(Op0.getValueType().is64BitVector() &&
4020            Op1.getValueType().is64BitVector() &&
4021            "unexpected types for extended operands to VMULL");
4022     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4023   }
4024   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
4025   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
4026   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
4027   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
4028   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
4029   EVT Op1VT = Op1.getValueType();
4030   return DAG.getNode(N0->getOpcode(), DL, VT,
4031                      DAG.getNode(NewOpc, DL, VT,
4032                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4033                      DAG.getNode(NewOpc, DL, VT,
4034                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4035 }
4036 
4037 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
4038                                int Pattern) {
4039   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
4040                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
4041 }
4042 
4043 static SDValue lowerConvertToSVBool(SDValue Op, SelectionDAG &DAG) {
4044   SDLoc DL(Op);
4045   EVT OutVT = Op.getValueType();
4046   SDValue InOp = Op.getOperand(1);
4047   EVT InVT = InOp.getValueType();
4048 
4049   // Return the operand if the cast isn't changing type,
4050   // i.e. <n x 16 x i1> -> <n x 16 x i1>
4051   if (InVT == OutVT)
4052     return InOp;
4053 
4054   SDValue Reinterpret =
4055       DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, InOp);
4056 
4057   // If the argument converted to an svbool is a ptrue or a comparison, the
4058   // lanes introduced by the widening are zero by construction.
4059   switch (InOp.getOpcode()) {
4060   case AArch64ISD::SETCC_MERGE_ZERO:
4061     return Reinterpret;
4062   case ISD::INTRINSIC_WO_CHAIN:
4063     if (InOp.getConstantOperandVal(0) == Intrinsic::aarch64_sve_ptrue)
4064       return Reinterpret;
4065   }
4066 
4067   // Otherwise, zero the newly introduced lanes.
4068   SDValue Mask = getPTrue(DAG, DL, InVT, AArch64SVEPredPattern::all);
4069   SDValue MaskReinterpret =
4070       DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, Mask);
4071   return DAG.getNode(ISD::AND, DL, OutVT, Reinterpret, MaskReinterpret);
4072 }
4073 
4074 SDValue AArch64TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4075                                                       SelectionDAG &DAG) const {
4076   unsigned IntNo = Op.getConstantOperandVal(1);
4077   switch (IntNo) {
4078   default:
4079     return SDValue(); // Don't custom lower most intrinsics.
4080   case Intrinsic::aarch64_mops_memset_tag: {
4081     auto Node = cast<MemIntrinsicSDNode>(Op.getNode());
4082     SDLoc DL(Op);
4083     SDValue Chain = Node->getChain();
4084     SDValue Dst = Op.getOperand(2);
4085     SDValue Val = Op.getOperand(3);
4086     Val = DAG.getAnyExtOrTrunc(Val, DL, MVT::i64);
4087     SDValue Size = Op.getOperand(4);
4088     auto Alignment = Node->getMemOperand()->getAlign();
4089     bool IsVol = Node->isVolatile();
4090     auto DstPtrInfo = Node->getPointerInfo();
4091 
4092     const auto &SDI =
4093         static_cast<const AArch64SelectionDAGInfo &>(DAG.getSelectionDAGInfo());
4094     SDValue MS =
4095         SDI.EmitMOPS(AArch64ISD::MOPS_MEMSET_TAGGING, DAG, DL, Chain, Dst, Val,
4096                      Size, Alignment, IsVol, DstPtrInfo, MachinePointerInfo{});
4097 
4098     // MOPS_MEMSET_TAGGING has 3 results (DstWb, SizeWb, Chain) whereas the
4099     // intrinsic has 2. So hide SizeWb using MERGE_VALUES. Otherwise
4100     // LowerOperationWrapper will complain that the number of results has
4101     // changed.
4102     return DAG.getMergeValues({MS.getValue(0), MS.getValue(2)}, DL);
4103   }
4104   }
4105 }
4106 
4107 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4108                                                      SelectionDAG &DAG) const {
4109   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4110   SDLoc dl(Op);
4111   switch (IntNo) {
4112   default: return SDValue();    // Don't custom lower most intrinsics.
4113   case Intrinsic::thread_pointer: {
4114     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4115     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
4116   }
4117   case Intrinsic::aarch64_neon_abs: {
4118     EVT Ty = Op.getValueType();
4119     if (Ty == MVT::i64) {
4120       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
4121                                    Op.getOperand(1));
4122       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
4123       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
4124     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
4125       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
4126     } else {
4127       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
4128     }
4129   }
4130   case Intrinsic::aarch64_neon_smax:
4131     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
4132                        Op.getOperand(1), Op.getOperand(2));
4133   case Intrinsic::aarch64_neon_umax:
4134     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
4135                        Op.getOperand(1), Op.getOperand(2));
4136   case Intrinsic::aarch64_neon_smin:
4137     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
4138                        Op.getOperand(1), Op.getOperand(2));
4139   case Intrinsic::aarch64_neon_umin:
4140     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
4141                        Op.getOperand(1), Op.getOperand(2));
4142 
4143   case Intrinsic::aarch64_sve_sunpkhi:
4144     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
4145                        Op.getOperand(1));
4146   case Intrinsic::aarch64_sve_sunpklo:
4147     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
4148                        Op.getOperand(1));
4149   case Intrinsic::aarch64_sve_uunpkhi:
4150     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
4151                        Op.getOperand(1));
4152   case Intrinsic::aarch64_sve_uunpklo:
4153     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
4154                        Op.getOperand(1));
4155   case Intrinsic::aarch64_sve_clasta_n:
4156     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
4157                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4158   case Intrinsic::aarch64_sve_clastb_n:
4159     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
4160                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4161   case Intrinsic::aarch64_sve_lasta:
4162     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
4163                        Op.getOperand(1), Op.getOperand(2));
4164   case Intrinsic::aarch64_sve_lastb:
4165     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
4166                        Op.getOperand(1), Op.getOperand(2));
4167   case Intrinsic::aarch64_sve_rev:
4168     return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(),
4169                        Op.getOperand(1));
4170   case Intrinsic::aarch64_sve_tbl:
4171     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
4172                        Op.getOperand(1), Op.getOperand(2));
4173   case Intrinsic::aarch64_sve_trn1:
4174     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
4175                        Op.getOperand(1), Op.getOperand(2));
4176   case Intrinsic::aarch64_sve_trn2:
4177     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
4178                        Op.getOperand(1), Op.getOperand(2));
4179   case Intrinsic::aarch64_sve_uzp1:
4180     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
4181                        Op.getOperand(1), Op.getOperand(2));
4182   case Intrinsic::aarch64_sve_uzp2:
4183     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
4184                        Op.getOperand(1), Op.getOperand(2));
4185   case Intrinsic::aarch64_sve_zip1:
4186     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
4187                        Op.getOperand(1), Op.getOperand(2));
4188   case Intrinsic::aarch64_sve_zip2:
4189     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
4190                        Op.getOperand(1), Op.getOperand(2));
4191   case Intrinsic::aarch64_sve_splice:
4192     return DAG.getNode(AArch64ISD::SPLICE, dl, Op.getValueType(),
4193                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4194   case Intrinsic::aarch64_sve_ptrue:
4195     return getPTrue(DAG, dl, Op.getValueType(),
4196                     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
4197   case Intrinsic::aarch64_sve_clz:
4198     return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
4199                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4200   case Intrinsic::aarch64_sve_cnt: {
4201     SDValue Data = Op.getOperand(3);
4202     // CTPOP only supports integer operands.
4203     if (Data.getValueType().isFloatingPoint())
4204       Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
4205     return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
4206                        Op.getOperand(2), Data, Op.getOperand(1));
4207   }
4208   case Intrinsic::aarch64_sve_dupq_lane:
4209     return LowerDUPQLane(Op, DAG);
4210   case Intrinsic::aarch64_sve_convert_from_svbool:
4211     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
4212                        Op.getOperand(1));
4213   case Intrinsic::aarch64_sve_convert_to_svbool:
4214     return lowerConvertToSVBool(Op, DAG);
4215   case Intrinsic::aarch64_sve_fneg:
4216     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
4217                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4218   case Intrinsic::aarch64_sve_frintp:
4219     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
4220                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4221   case Intrinsic::aarch64_sve_frintm:
4222     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
4223                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4224   case Intrinsic::aarch64_sve_frinti:
4225     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
4226                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4227   case Intrinsic::aarch64_sve_frintx:
4228     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
4229                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4230   case Intrinsic::aarch64_sve_frinta:
4231     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
4232                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4233   case Intrinsic::aarch64_sve_frintn:
4234     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
4235                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4236   case Intrinsic::aarch64_sve_frintz:
4237     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
4238                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4239   case Intrinsic::aarch64_sve_ucvtf:
4240     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
4241                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4242                        Op.getOperand(1));
4243   case Intrinsic::aarch64_sve_scvtf:
4244     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
4245                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4246                        Op.getOperand(1));
4247   case Intrinsic::aarch64_sve_fcvtzu:
4248     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
4249                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4250                        Op.getOperand(1));
4251   case Intrinsic::aarch64_sve_fcvtzs:
4252     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
4253                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4254                        Op.getOperand(1));
4255   case Intrinsic::aarch64_sve_fsqrt:
4256     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
4257                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4258   case Intrinsic::aarch64_sve_frecpx:
4259     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
4260                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4261   case Intrinsic::aarch64_sve_frecpe_x:
4262     return DAG.getNode(AArch64ISD::FRECPE, dl, Op.getValueType(),
4263                        Op.getOperand(1));
4264   case Intrinsic::aarch64_sve_frecps_x:
4265     return DAG.getNode(AArch64ISD::FRECPS, dl, Op.getValueType(),
4266                        Op.getOperand(1), Op.getOperand(2));
4267   case Intrinsic::aarch64_sve_frsqrte_x:
4268     return DAG.getNode(AArch64ISD::FRSQRTE, dl, Op.getValueType(),
4269                        Op.getOperand(1));
4270   case Intrinsic::aarch64_sve_frsqrts_x:
4271     return DAG.getNode(AArch64ISD::FRSQRTS, dl, Op.getValueType(),
4272                        Op.getOperand(1), Op.getOperand(2));
4273   case Intrinsic::aarch64_sve_fabs:
4274     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
4275                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4276   case Intrinsic::aarch64_sve_abs:
4277     return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
4278                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4279   case Intrinsic::aarch64_sve_neg:
4280     return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
4281                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4282   case Intrinsic::aarch64_sve_insr: {
4283     SDValue Scalar = Op.getOperand(2);
4284     EVT ScalarTy = Scalar.getValueType();
4285     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
4286       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
4287 
4288     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
4289                        Op.getOperand(1), Scalar);
4290   }
4291   case Intrinsic::aarch64_sve_rbit:
4292     return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
4293                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4294                        Op.getOperand(1));
4295   case Intrinsic::aarch64_sve_revb:
4296     return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
4297                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4298   case Intrinsic::aarch64_sve_revh:
4299     return DAG.getNode(AArch64ISD::REVH_MERGE_PASSTHRU, dl, Op.getValueType(),
4300                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4301   case Intrinsic::aarch64_sve_revw:
4302     return DAG.getNode(AArch64ISD::REVW_MERGE_PASSTHRU, dl, Op.getValueType(),
4303                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4304   case Intrinsic::aarch64_sve_sxtb:
4305     return DAG.getNode(
4306         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4307         Op.getOperand(2), Op.getOperand(3),
4308         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
4309         Op.getOperand(1));
4310   case Intrinsic::aarch64_sve_sxth:
4311     return DAG.getNode(
4312         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4313         Op.getOperand(2), Op.getOperand(3),
4314         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
4315         Op.getOperand(1));
4316   case Intrinsic::aarch64_sve_sxtw:
4317     return DAG.getNode(
4318         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4319         Op.getOperand(2), Op.getOperand(3),
4320         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
4321         Op.getOperand(1));
4322   case Intrinsic::aarch64_sve_uxtb:
4323     return DAG.getNode(
4324         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4325         Op.getOperand(2), Op.getOperand(3),
4326         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
4327         Op.getOperand(1));
4328   case Intrinsic::aarch64_sve_uxth:
4329     return DAG.getNode(
4330         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4331         Op.getOperand(2), Op.getOperand(3),
4332         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
4333         Op.getOperand(1));
4334   case Intrinsic::aarch64_sve_uxtw:
4335     return DAG.getNode(
4336         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4337         Op.getOperand(2), Op.getOperand(3),
4338         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
4339         Op.getOperand(1));
4340 
4341   case Intrinsic::localaddress: {
4342     const auto &MF = DAG.getMachineFunction();
4343     const auto *RegInfo = Subtarget->getRegisterInfo();
4344     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
4345     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
4346                               Op.getSimpleValueType());
4347   }
4348 
4349   case Intrinsic::eh_recoverfp: {
4350     // FIXME: This needs to be implemented to correctly handle highly aligned
4351     // stack objects. For now we simply return the incoming FP. Refer D53541
4352     // for more details.
4353     SDValue FnOp = Op.getOperand(1);
4354     SDValue IncomingFPOp = Op.getOperand(2);
4355     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
4356     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
4357     if (!Fn)
4358       report_fatal_error(
4359           "llvm.eh.recoverfp must take a function as the first argument");
4360     return IncomingFPOp;
4361   }
4362 
4363   case Intrinsic::aarch64_neon_vsri:
4364   case Intrinsic::aarch64_neon_vsli: {
4365     EVT Ty = Op.getValueType();
4366 
4367     if (!Ty.isVector())
4368       report_fatal_error("Unexpected type for aarch64_neon_vsli");
4369 
4370     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
4371 
4372     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
4373     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
4374     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
4375                        Op.getOperand(3));
4376   }
4377 
4378   case Intrinsic::aarch64_neon_srhadd:
4379   case Intrinsic::aarch64_neon_urhadd:
4380   case Intrinsic::aarch64_neon_shadd:
4381   case Intrinsic::aarch64_neon_uhadd: {
4382     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
4383                         IntNo == Intrinsic::aarch64_neon_shadd);
4384     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
4385                           IntNo == Intrinsic::aarch64_neon_urhadd);
4386     unsigned Opcode =
4387         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
4388                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
4389     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4390                        Op.getOperand(2));
4391   }
4392   case Intrinsic::aarch64_neon_sabd:
4393   case Intrinsic::aarch64_neon_uabd: {
4394     unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uabd ? ISD::ABDU
4395                                                             : ISD::ABDS;
4396     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4397                        Op.getOperand(2));
4398   }
4399   case Intrinsic::aarch64_neon_uaddlp: {
4400     unsigned Opcode = AArch64ISD::UADDLP;
4401     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1));
4402   }
4403   case Intrinsic::aarch64_neon_sdot:
4404   case Intrinsic::aarch64_neon_udot:
4405   case Intrinsic::aarch64_sve_sdot:
4406   case Intrinsic::aarch64_sve_udot: {
4407     unsigned Opcode = (IntNo == Intrinsic::aarch64_neon_udot ||
4408                        IntNo == Intrinsic::aarch64_sve_udot)
4409                           ? AArch64ISD::UDOT
4410                           : AArch64ISD::SDOT;
4411     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4412                        Op.getOperand(2), Op.getOperand(3));
4413   }
4414   case Intrinsic::get_active_lane_mask: {
4415     SDValue ID =
4416         DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, MVT::i64);
4417     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), ID,
4418                        Op.getOperand(1), Op.getOperand(2));
4419   }
4420   }
4421 }
4422 
4423 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const {
4424   if (VT.getVectorElementType() == MVT::i8 ||
4425       VT.getVectorElementType() == MVT::i16) {
4426     EltTy = MVT::i32;
4427     return true;
4428   }
4429   return false;
4430 }
4431 
4432 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
4433   if (VT.getVectorElementType() == MVT::i32 &&
4434       VT.getVectorElementCount().getKnownMinValue() >= 4 &&
4435       !VT.isFixedLengthVector())
4436     return true;
4437 
4438   return false;
4439 }
4440 
4441 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
4442   return ExtVal.getValueType().isScalableVector() ||
4443          useSVEForFixedLengthVectorVT(ExtVal.getValueType(),
4444                                       /*OverrideNEON=*/true);
4445 }
4446 
4447 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
4448   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
4449       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
4450        AArch64ISD::GLD1_MERGE_ZERO},
4451       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
4452        AArch64ISD::GLD1_UXTW_MERGE_ZERO},
4453       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
4454        AArch64ISD::GLD1_MERGE_ZERO},
4455       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
4456        AArch64ISD::GLD1_SXTW_MERGE_ZERO},
4457       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
4458        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
4459       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
4460        AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
4461       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
4462        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
4463       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
4464        AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
4465   };
4466   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
4467   return AddrModes.find(Key)->second;
4468 }
4469 
4470 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
4471   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
4472       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
4473        AArch64ISD::SST1_PRED},
4474       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
4475        AArch64ISD::SST1_UXTW_PRED},
4476       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
4477        AArch64ISD::SST1_PRED},
4478       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
4479        AArch64ISD::SST1_SXTW_PRED},
4480       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
4481        AArch64ISD::SST1_SCALED_PRED},
4482       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
4483        AArch64ISD::SST1_UXTW_SCALED_PRED},
4484       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
4485        AArch64ISD::SST1_SCALED_PRED},
4486       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
4487        AArch64ISD::SST1_SXTW_SCALED_PRED},
4488   };
4489   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
4490   return AddrModes.find(Key)->second;
4491 }
4492 
4493 unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
4494   switch (Opcode) {
4495   default:
4496     llvm_unreachable("unimplemented opcode");
4497     return Opcode;
4498   case AArch64ISD::GLD1_MERGE_ZERO:
4499     return AArch64ISD::GLD1S_MERGE_ZERO;
4500   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
4501     return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
4502   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
4503     return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
4504   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
4505     return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
4506   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
4507     return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
4508   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
4509     return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
4510   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
4511     return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
4512   }
4513 }
4514 
4515 bool getGatherScatterIndexIsExtended(SDValue Index) {
4516   unsigned Opcode = Index.getOpcode();
4517   if (Opcode == ISD::SIGN_EXTEND_INREG)
4518     return true;
4519 
4520   if (Opcode == ISD::AND) {
4521     SDValue Splat = Index.getOperand(1);
4522     if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
4523       return false;
4524     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
4525     if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
4526       return false;
4527     return true;
4528   }
4529 
4530   return false;
4531 }
4532 
4533 // If the base pointer of a masked gather or scatter is null, we
4534 // may be able to swap BasePtr & Index and use the vector + register
4535 // or vector + immediate addressing mode, e.g.
4536 // VECTOR + REGISTER:
4537 //    getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices)
4538 // -> getelementptr %offset, <vscale x N x T> %indices
4539 // VECTOR + IMMEDIATE:
4540 //    getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices)
4541 // -> getelementptr #x, <vscale x N x T> %indices
4542 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT,
4543                                  unsigned &Opcode, bool IsGather,
4544                                  SelectionDAG &DAG) {
4545   if (!isNullConstant(BasePtr))
4546     return;
4547 
4548   // FIXME: This will not match for fixed vector type codegen as the nodes in
4549   // question will have fixed<->scalable conversions around them. This should be
4550   // moved to a DAG combine or complex pattern so that is executes after all of
4551   // the fixed vector insert and extracts have been removed. This deficiency
4552   // will result in a sub-optimal addressing mode being used, i.e. an ADD not
4553   // being folded into the scatter/gather.
4554   ConstantSDNode *Offset = nullptr;
4555   if (Index.getOpcode() == ISD::ADD)
4556     if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) {
4557       if (isa<ConstantSDNode>(SplatVal))
4558         Offset = cast<ConstantSDNode>(SplatVal);
4559       else {
4560         BasePtr = SplatVal;
4561         Index = Index->getOperand(0);
4562         return;
4563       }
4564     }
4565 
4566   unsigned NewOp =
4567       IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED;
4568 
4569   if (!Offset) {
4570     std::swap(BasePtr, Index);
4571     Opcode = NewOp;
4572     return;
4573   }
4574 
4575   uint64_t OffsetVal = Offset->getZExtValue();
4576   unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8;
4577   auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64);
4578 
4579   if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) {
4580     // Index is out of range for the immediate addressing mode
4581     BasePtr = ConstOffset;
4582     Index = Index->getOperand(0);
4583     return;
4584   }
4585 
4586   // Immediate is in range
4587   Opcode = NewOp;
4588   BasePtr = Index->getOperand(0);
4589   Index = ConstOffset;
4590 }
4591 
4592 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
4593                                             SelectionDAG &DAG) const {
4594   SDLoc DL(Op);
4595   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
4596   assert(MGT && "Can only custom lower gather load nodes");
4597 
4598   bool IsFixedLength = MGT->getMemoryVT().isFixedLengthVector();
4599 
4600   SDValue Index = MGT->getIndex();
4601   SDValue Chain = MGT->getChain();
4602   SDValue PassThru = MGT->getPassThru();
4603   SDValue Mask = MGT->getMask();
4604   SDValue BasePtr = MGT->getBasePtr();
4605   ISD::LoadExtType ExtTy = MGT->getExtensionType();
4606 
4607   ISD::MemIndexType IndexType = MGT->getIndexType();
4608   bool IsScaled =
4609       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4610   bool IsSigned =
4611       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4612   bool IdxNeedsExtend =
4613       getGatherScatterIndexIsExtended(Index) ||
4614       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4615   bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD;
4616 
4617   EVT VT = PassThru.getSimpleValueType();
4618   EVT IndexVT = Index.getSimpleValueType();
4619   EVT MemVT = MGT->getMemoryVT();
4620   SDValue InputVT = DAG.getValueType(MemVT);
4621 
4622   if (VT.getVectorElementType() == MVT::bf16 &&
4623       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4624     return SDValue();
4625 
4626   if (IsFixedLength) {
4627     assert(Subtarget->useSVEForFixedLengthVectors() &&
4628            "Cannot lower when not using SVE for fixed vectors");
4629     if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
4630       IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
4631       MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
4632     } else {
4633       MemVT = getContainerForFixedLengthVector(DAG, MemVT);
4634       IndexVT = MemVT.changeTypeToInteger();
4635     }
4636     InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
4637     Mask = DAG.getNode(
4638         ISD::SIGN_EXTEND, DL,
4639         VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
4640   }
4641 
4642   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
4643     PassThru = SDValue();
4644 
4645   if (VT.isFloatingPoint() && !IsFixedLength) {
4646     // Handle FP data by using an integer gather and casting the result.
4647     if (PassThru) {
4648       EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4649       PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG);
4650     }
4651     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4652   }
4653 
4654   SDVTList VTs = DAG.getVTList(IndexVT, MVT::Other);
4655 
4656   if (getGatherScatterIndexIsExtended(Index))
4657     Index = Index.getOperand(0);
4658 
4659   unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend);
4660   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4661                               /*isGather=*/true, DAG);
4662 
4663   if (ResNeedsSignExtend)
4664     Opcode = getSignExtendedGatherOpcode(Opcode);
4665 
4666   if (IsFixedLength) {
4667     if (Index.getSimpleValueType().isFixedLengthVector())
4668       Index = convertToScalableVector(DAG, IndexVT, Index);
4669     if (BasePtr.getSimpleValueType().isFixedLengthVector())
4670       BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
4671     Mask = convertFixedMaskToScalableVector(Mask, DAG);
4672   }
4673 
4674   SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT};
4675   SDValue Result = DAG.getNode(Opcode, DL, VTs, Ops);
4676   Chain = Result.getValue(1);
4677 
4678   if (IsFixedLength) {
4679     Result = convertFromScalableVector(
4680         DAG, VT.changeVectorElementType(IndexVT.getVectorElementType()),
4681         Result);
4682     Result = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Result);
4683     Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
4684 
4685     if (PassThru)
4686       Result = DAG.getSelect(DL, VT, MGT->getMask(), Result, PassThru);
4687   } else {
4688     if (PassThru)
4689       Result = DAG.getSelect(DL, IndexVT, Mask, Result, PassThru);
4690 
4691     if (VT.isFloatingPoint())
4692       Result = getSVESafeBitCast(VT, Result, DAG);
4693   }
4694 
4695   return DAG.getMergeValues({Result, Chain}, DL);
4696 }
4697 
4698 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
4699                                              SelectionDAG &DAG) const {
4700   SDLoc DL(Op);
4701   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
4702   assert(MSC && "Can only custom lower scatter store nodes");
4703 
4704   bool IsFixedLength = MSC->getMemoryVT().isFixedLengthVector();
4705 
4706   SDValue Index = MSC->getIndex();
4707   SDValue Chain = MSC->getChain();
4708   SDValue StoreVal = MSC->getValue();
4709   SDValue Mask = MSC->getMask();
4710   SDValue BasePtr = MSC->getBasePtr();
4711 
4712   ISD::MemIndexType IndexType = MSC->getIndexType();
4713   bool IsScaled =
4714       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4715   bool IsSigned =
4716       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4717   bool NeedsExtend =
4718       getGatherScatterIndexIsExtended(Index) ||
4719       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4720 
4721   EVT VT = StoreVal.getSimpleValueType();
4722   EVT IndexVT = Index.getSimpleValueType();
4723   SDVTList VTs = DAG.getVTList(MVT::Other);
4724   EVT MemVT = MSC->getMemoryVT();
4725   SDValue InputVT = DAG.getValueType(MemVT);
4726 
4727   if (VT.getVectorElementType() == MVT::bf16 &&
4728       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4729     return SDValue();
4730 
4731   if (IsFixedLength) {
4732     assert(Subtarget->useSVEForFixedLengthVectors() &&
4733            "Cannot lower when not using SVE for fixed vectors");
4734     if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
4735       IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
4736       MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
4737     } else {
4738       MemVT = getContainerForFixedLengthVector(DAG, MemVT);
4739       IndexVT = MemVT.changeTypeToInteger();
4740     }
4741     InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
4742 
4743     StoreVal =
4744         DAG.getNode(ISD::BITCAST, DL, VT.changeTypeToInteger(), StoreVal);
4745     StoreVal = DAG.getNode(
4746         ISD::ANY_EXTEND, DL,
4747         VT.changeVectorElementType(IndexVT.getVectorElementType()), StoreVal);
4748     StoreVal = convertToScalableVector(DAG, IndexVT, StoreVal);
4749     Mask = DAG.getNode(
4750         ISD::SIGN_EXTEND, DL,
4751         VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
4752   } else if (VT.isFloatingPoint()) {
4753     // Handle FP data by casting the data so an integer scatter can be used.
4754     EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4755     StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG);
4756     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4757   }
4758 
4759   if (getGatherScatterIndexIsExtended(Index))
4760     Index = Index.getOperand(0);
4761 
4762   unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend);
4763   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4764                               /*isGather=*/false, DAG);
4765 
4766   if (IsFixedLength) {
4767     if (Index.getSimpleValueType().isFixedLengthVector())
4768       Index = convertToScalableVector(DAG, IndexVT, Index);
4769     if (BasePtr.getSimpleValueType().isFixedLengthVector())
4770       BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
4771     Mask = convertFixedMaskToScalableVector(Mask, DAG);
4772   }
4773 
4774   SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
4775   return DAG.getNode(Opcode, DL, VTs, Ops);
4776 }
4777 
4778 SDValue AArch64TargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
4779   SDLoc DL(Op);
4780   MaskedLoadSDNode *LoadNode = cast<MaskedLoadSDNode>(Op);
4781   assert(LoadNode && "Expected custom lowering of a masked load node");
4782   EVT VT = Op->getValueType(0);
4783 
4784   if (useSVEForFixedLengthVectorVT(VT, true))
4785     return LowerFixedLengthVectorMLoadToSVE(Op, DAG);
4786 
4787   SDValue PassThru = LoadNode->getPassThru();
4788   SDValue Mask = LoadNode->getMask();
4789 
4790   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
4791     return Op;
4792 
4793   SDValue Load = DAG.getMaskedLoad(
4794       VT, DL, LoadNode->getChain(), LoadNode->getBasePtr(),
4795       LoadNode->getOffset(), Mask, DAG.getUNDEF(VT), LoadNode->getMemoryVT(),
4796       LoadNode->getMemOperand(), LoadNode->getAddressingMode(),
4797       LoadNode->getExtensionType());
4798 
4799   SDValue Result = DAG.getSelect(DL, VT, Mask, Load, PassThru);
4800 
4801   return DAG.getMergeValues({Result, Load.getValue(1)}, DL);
4802 }
4803 
4804 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
4805 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
4806                                         EVT VT, EVT MemVT,
4807                                         SelectionDAG &DAG) {
4808   assert(VT.isVector() && "VT should be a vector type");
4809   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
4810 
4811   SDValue Value = ST->getValue();
4812 
4813   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
4814   // the word lane which represent the v4i8 subvector.  It optimizes the store
4815   // to:
4816   //
4817   //   xtn  v0.8b, v0.8h
4818   //   str  s0, [x0]
4819 
4820   SDValue Undef = DAG.getUNDEF(MVT::i16);
4821   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
4822                                         {Undef, Undef, Undef, Undef});
4823 
4824   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
4825                                  Value, UndefVec);
4826   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
4827 
4828   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
4829   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
4830                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
4831 
4832   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
4833                       ST->getBasePtr(), ST->getMemOperand());
4834 }
4835 
4836 // Custom lowering for any store, vector or scalar and/or default or with
4837 // a truncate operations.  Currently only custom lower truncate operation
4838 // from vector v4i16 to v4i8 or volatile stores of i128.
4839 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
4840                                           SelectionDAG &DAG) const {
4841   SDLoc Dl(Op);
4842   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
4843   assert (StoreNode && "Can only custom lower store nodes");
4844 
4845   SDValue Value = StoreNode->getValue();
4846 
4847   EVT VT = Value.getValueType();
4848   EVT MemVT = StoreNode->getMemoryVT();
4849 
4850   if (VT.isVector()) {
4851     if (useSVEForFixedLengthVectorVT(VT, true))
4852       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
4853 
4854     unsigned AS = StoreNode->getAddressSpace();
4855     Align Alignment = StoreNode->getAlign();
4856     if (Alignment < MemVT.getStoreSize() &&
4857         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment,
4858                                         StoreNode->getMemOperand()->getFlags(),
4859                                         nullptr)) {
4860       return scalarizeVectorStore(StoreNode, DAG);
4861     }
4862 
4863     if (StoreNode->isTruncatingStore() && VT == MVT::v4i16 &&
4864         MemVT == MVT::v4i8) {
4865       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
4866     }
4867     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
4868     // the custom lowering, as there are no un-paired non-temporal stores and
4869     // legalization will break up 256 bit inputs.
4870     ElementCount EC = MemVT.getVectorElementCount();
4871     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
4872         EC.isKnownEven() &&
4873         ((MemVT.getScalarSizeInBits() == 8u ||
4874           MemVT.getScalarSizeInBits() == 16u ||
4875           MemVT.getScalarSizeInBits() == 32u ||
4876           MemVT.getScalarSizeInBits() == 64u))) {
4877       SDValue Lo =
4878           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4879                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4880                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
4881       SDValue Hi =
4882           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4883                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4884                       StoreNode->getValue(),
4885                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
4886       SDValue Result = DAG.getMemIntrinsicNode(
4887           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
4888           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4889           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4890       return Result;
4891     }
4892   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
4893     return LowerStore128(Op, DAG);
4894   } else if (MemVT == MVT::i64x8) {
4895     SDValue Value = StoreNode->getValue();
4896     assert(Value->getValueType(0) == MVT::i64x8);
4897     SDValue Chain = StoreNode->getChain();
4898     SDValue Base = StoreNode->getBasePtr();
4899     EVT PtrVT = Base.getValueType();
4900     for (unsigned i = 0; i < 8; i++) {
4901       SDValue Part = DAG.getNode(AArch64ISD::LS64_EXTRACT, Dl, MVT::i64,
4902                                  Value, DAG.getConstant(i, Dl, MVT::i32));
4903       SDValue Ptr = DAG.getNode(ISD::ADD, Dl, PtrVT, Base,
4904                                 DAG.getConstant(i * 8, Dl, PtrVT));
4905       Chain = DAG.getStore(Chain, Dl, Part, Ptr, StoreNode->getPointerInfo(),
4906                            StoreNode->getOriginalAlign());
4907     }
4908     return Chain;
4909   }
4910 
4911   return SDValue();
4912 }
4913 
4914 /// Lower atomic or volatile 128-bit stores to a single STP instruction.
4915 SDValue AArch64TargetLowering::LowerStore128(SDValue Op,
4916                                              SelectionDAG &DAG) const {
4917   MemSDNode *StoreNode = cast<MemSDNode>(Op);
4918   assert(StoreNode->getMemoryVT() == MVT::i128);
4919   assert(StoreNode->isVolatile() || StoreNode->isAtomic());
4920   assert(!StoreNode->isAtomic() ||
4921          StoreNode->getMergedOrdering() == AtomicOrdering::Unordered ||
4922          StoreNode->getMergedOrdering() == AtomicOrdering::Monotonic);
4923 
4924   SDValue Value = StoreNode->getOpcode() == ISD::STORE
4925                       ? StoreNode->getOperand(1)
4926                       : StoreNode->getOperand(2);
4927   SDLoc DL(Op);
4928   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
4929                            DAG.getConstant(0, DL, MVT::i64));
4930   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
4931                            DAG.getConstant(1, DL, MVT::i64));
4932   SDValue Result = DAG.getMemIntrinsicNode(
4933       AArch64ISD::STP, DL, DAG.getVTList(MVT::Other),
4934       {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4935       StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4936   return Result;
4937 }
4938 
4939 SDValue AArch64TargetLowering::LowerLOAD(SDValue Op,
4940                                          SelectionDAG &DAG) const {
4941   SDLoc DL(Op);
4942   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
4943   assert(LoadNode && "Expected custom lowering of a load node");
4944 
4945   if (LoadNode->getMemoryVT() == MVT::i64x8) {
4946     SmallVector<SDValue, 8> Ops;
4947     SDValue Base = LoadNode->getBasePtr();
4948     SDValue Chain = LoadNode->getChain();
4949     EVT PtrVT = Base.getValueType();
4950     for (unsigned i = 0; i < 8; i++) {
4951       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
4952                                 DAG.getConstant(i * 8, DL, PtrVT));
4953       SDValue Part = DAG.getLoad(MVT::i64, DL, Chain, Ptr,
4954                                  LoadNode->getPointerInfo(),
4955                                  LoadNode->getOriginalAlign());
4956       Ops.push_back(Part);
4957       Chain = SDValue(Part.getNode(), 1);
4958     }
4959     SDValue Loaded = DAG.getNode(AArch64ISD::LS64_BUILD, DL, MVT::i64x8, Ops);
4960     return DAG.getMergeValues({Loaded, Chain}, DL);
4961   }
4962 
4963   // Custom lowering for extending v4i8 vector loads.
4964   EVT VT = Op->getValueType(0);
4965   assert((VT == MVT::v4i16 || VT == MVT::v4i32) && "Expected v4i16 or v4i32");
4966 
4967   if (LoadNode->getMemoryVT() != MVT::v4i8)
4968     return SDValue();
4969 
4970   unsigned ExtType;
4971   if (LoadNode->getExtensionType() == ISD::SEXTLOAD)
4972     ExtType = ISD::SIGN_EXTEND;
4973   else if (LoadNode->getExtensionType() == ISD::ZEXTLOAD ||
4974            LoadNode->getExtensionType() == ISD::EXTLOAD)
4975     ExtType = ISD::ZERO_EXTEND;
4976   else
4977     return SDValue();
4978 
4979   SDValue Load = DAG.getLoad(MVT::f32, DL, LoadNode->getChain(),
4980                              LoadNode->getBasePtr(), MachinePointerInfo());
4981   SDValue Chain = Load.getValue(1);
4982   SDValue Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f32, Load);
4983   SDValue BC = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Vec);
4984   SDValue Ext = DAG.getNode(ExtType, DL, MVT::v8i16, BC);
4985   Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Ext,
4986                     DAG.getConstant(0, DL, MVT::i64));
4987   if (VT == MVT::v4i32)
4988     Ext = DAG.getNode(ExtType, DL, MVT::v4i32, Ext);
4989   return DAG.getMergeValues({Ext, Chain}, DL);
4990 }
4991 
4992 // Generate SUBS and CSEL for integer abs.
4993 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
4994   MVT VT = Op.getSimpleValueType();
4995 
4996   if (VT.isVector())
4997     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
4998 
4999   SDLoc DL(Op);
5000   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
5001                             Op.getOperand(0));
5002   // Generate SUBS & CSEL.
5003   SDValue Cmp =
5004       DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
5005                   Op.getOperand(0), DAG.getConstant(0, DL, VT));
5006   return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
5007                      DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
5008                      Cmp.getValue(1));
5009 }
5010 
5011 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
5012                                               SelectionDAG &DAG) const {
5013   LLVM_DEBUG(dbgs() << "Custom lowering: ");
5014   LLVM_DEBUG(Op.dump());
5015 
5016   switch (Op.getOpcode()) {
5017   default:
5018     llvm_unreachable("unimplemented operand");
5019     return SDValue();
5020   case ISD::BITCAST:
5021     return LowerBITCAST(Op, DAG);
5022   case ISD::GlobalAddress:
5023     return LowerGlobalAddress(Op, DAG);
5024   case ISD::GlobalTLSAddress:
5025     return LowerGlobalTLSAddress(Op, DAG);
5026   case ISD::SETCC:
5027   case ISD::STRICT_FSETCC:
5028   case ISD::STRICT_FSETCCS:
5029     return LowerSETCC(Op, DAG);
5030   case ISD::BR_CC:
5031     return LowerBR_CC(Op, DAG);
5032   case ISD::SELECT:
5033     return LowerSELECT(Op, DAG);
5034   case ISD::SELECT_CC:
5035     return LowerSELECT_CC(Op, DAG);
5036   case ISD::JumpTable:
5037     return LowerJumpTable(Op, DAG);
5038   case ISD::BR_JT:
5039     return LowerBR_JT(Op, DAG);
5040   case ISD::ConstantPool:
5041     return LowerConstantPool(Op, DAG);
5042   case ISD::BlockAddress:
5043     return LowerBlockAddress(Op, DAG);
5044   case ISD::VASTART:
5045     return LowerVASTART(Op, DAG);
5046   case ISD::VACOPY:
5047     return LowerVACOPY(Op, DAG);
5048   case ISD::VAARG:
5049     return LowerVAARG(Op, DAG);
5050   case ISD::ADDC:
5051   case ISD::ADDE:
5052   case ISD::SUBC:
5053   case ISD::SUBE:
5054     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5055   case ISD::SADDO:
5056   case ISD::UADDO:
5057   case ISD::SSUBO:
5058   case ISD::USUBO:
5059   case ISD::SMULO:
5060   case ISD::UMULO:
5061     return LowerXALUO(Op, DAG);
5062   case ISD::FADD:
5063     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
5064   case ISD::FSUB:
5065     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
5066   case ISD::FMUL:
5067     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
5068   case ISD::FMA:
5069     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
5070   case ISD::FDIV:
5071     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
5072   case ISD::FNEG:
5073     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
5074   case ISD::FCEIL:
5075     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
5076   case ISD::FFLOOR:
5077     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
5078   case ISD::FNEARBYINT:
5079     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
5080   case ISD::FRINT:
5081     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
5082   case ISD::FROUND:
5083     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
5084   case ISD::FROUNDEVEN:
5085     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
5086   case ISD::FTRUNC:
5087     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
5088   case ISD::FSQRT:
5089     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
5090   case ISD::FABS:
5091     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
5092   case ISD::FP_ROUND:
5093   case ISD::STRICT_FP_ROUND:
5094     return LowerFP_ROUND(Op, DAG);
5095   case ISD::FP_EXTEND:
5096     return LowerFP_EXTEND(Op, DAG);
5097   case ISD::FRAMEADDR:
5098     return LowerFRAMEADDR(Op, DAG);
5099   case ISD::SPONENTRY:
5100     return LowerSPONENTRY(Op, DAG);
5101   case ISD::RETURNADDR:
5102     return LowerRETURNADDR(Op, DAG);
5103   case ISD::ADDROFRETURNADDR:
5104     return LowerADDROFRETURNADDR(Op, DAG);
5105   case ISD::CONCAT_VECTORS:
5106     return LowerCONCAT_VECTORS(Op, DAG);
5107   case ISD::INSERT_VECTOR_ELT:
5108     return LowerINSERT_VECTOR_ELT(Op, DAG);
5109   case ISD::EXTRACT_VECTOR_ELT:
5110     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5111   case ISD::BUILD_VECTOR:
5112     return LowerBUILD_VECTOR(Op, DAG);
5113   case ISD::VECTOR_SHUFFLE:
5114     return LowerVECTOR_SHUFFLE(Op, DAG);
5115   case ISD::SPLAT_VECTOR:
5116     return LowerSPLAT_VECTOR(Op, DAG);
5117   case ISD::EXTRACT_SUBVECTOR:
5118     return LowerEXTRACT_SUBVECTOR(Op, DAG);
5119   case ISD::INSERT_SUBVECTOR:
5120     return LowerINSERT_SUBVECTOR(Op, DAG);
5121   case ISD::SDIV:
5122   case ISD::UDIV:
5123     return LowerDIV(Op, DAG);
5124   case ISD::SMIN:
5125   case ISD::UMIN:
5126   case ISD::SMAX:
5127   case ISD::UMAX:
5128     return LowerMinMax(Op, DAG);
5129   case ISD::SRA:
5130   case ISD::SRL:
5131   case ISD::SHL:
5132     return LowerVectorSRA_SRL_SHL(Op, DAG);
5133   case ISD::SHL_PARTS:
5134   case ISD::SRL_PARTS:
5135   case ISD::SRA_PARTS:
5136     return LowerShiftParts(Op, DAG);
5137   case ISD::CTPOP:
5138     return LowerCTPOP(Op, DAG);
5139   case ISD::FCOPYSIGN:
5140     return LowerFCOPYSIGN(Op, DAG);
5141   case ISD::OR:
5142     return LowerVectorOR(Op, DAG);
5143   case ISD::XOR:
5144     return LowerXOR(Op, DAG);
5145   case ISD::PREFETCH:
5146     return LowerPREFETCH(Op, DAG);
5147   case ISD::SINT_TO_FP:
5148   case ISD::UINT_TO_FP:
5149   case ISD::STRICT_SINT_TO_FP:
5150   case ISD::STRICT_UINT_TO_FP:
5151     return LowerINT_TO_FP(Op, DAG);
5152   case ISD::FP_TO_SINT:
5153   case ISD::FP_TO_UINT:
5154   case ISD::STRICT_FP_TO_SINT:
5155   case ISD::STRICT_FP_TO_UINT:
5156     return LowerFP_TO_INT(Op, DAG);
5157   case ISD::FP_TO_SINT_SAT:
5158   case ISD::FP_TO_UINT_SAT:
5159     return LowerFP_TO_INT_SAT(Op, DAG);
5160   case ISD::FSINCOS:
5161     return LowerFSINCOS(Op, DAG);
5162   case ISD::FLT_ROUNDS_:
5163     return LowerFLT_ROUNDS_(Op, DAG);
5164   case ISD::SET_ROUNDING:
5165     return LowerSET_ROUNDING(Op, DAG);
5166   case ISD::MUL:
5167     return LowerMUL(Op, DAG);
5168   case ISD::MULHS:
5169     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHS_PRED,
5170                                /*OverrideNEON=*/true);
5171   case ISD::MULHU:
5172     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHU_PRED,
5173                                /*OverrideNEON=*/true);
5174   case ISD::INTRINSIC_W_CHAIN:
5175     return LowerINTRINSIC_W_CHAIN(Op, DAG);
5176   case ISD::INTRINSIC_WO_CHAIN:
5177     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5178   case ISD::ATOMIC_STORE:
5179     if (cast<MemSDNode>(Op)->getMemoryVT() == MVT::i128) {
5180       assert(Subtarget->hasLSE2());
5181       return LowerStore128(Op, DAG);
5182     }
5183     return SDValue();
5184   case ISD::STORE:
5185     return LowerSTORE(Op, DAG);
5186   case ISD::MSTORE:
5187     return LowerFixedLengthVectorMStoreToSVE(Op, DAG);
5188   case ISD::MGATHER:
5189     return LowerMGATHER(Op, DAG);
5190   case ISD::MSCATTER:
5191     return LowerMSCATTER(Op, DAG);
5192   case ISD::VECREDUCE_SEQ_FADD:
5193     return LowerVECREDUCE_SEQ_FADD(Op, DAG);
5194   case ISD::VECREDUCE_ADD:
5195   case ISD::VECREDUCE_AND:
5196   case ISD::VECREDUCE_OR:
5197   case ISD::VECREDUCE_XOR:
5198   case ISD::VECREDUCE_SMAX:
5199   case ISD::VECREDUCE_SMIN:
5200   case ISD::VECREDUCE_UMAX:
5201   case ISD::VECREDUCE_UMIN:
5202   case ISD::VECREDUCE_FADD:
5203   case ISD::VECREDUCE_FMAX:
5204   case ISD::VECREDUCE_FMIN:
5205     return LowerVECREDUCE(Op, DAG);
5206   case ISD::ATOMIC_LOAD_SUB:
5207     return LowerATOMIC_LOAD_SUB(Op, DAG);
5208   case ISD::ATOMIC_LOAD_AND:
5209     return LowerATOMIC_LOAD_AND(Op, DAG);
5210   case ISD::DYNAMIC_STACKALLOC:
5211     return LowerDYNAMIC_STACKALLOC(Op, DAG);
5212   case ISD::VSCALE:
5213     return LowerVSCALE(Op, DAG);
5214   case ISD::ANY_EXTEND:
5215   case ISD::SIGN_EXTEND:
5216   case ISD::ZERO_EXTEND:
5217     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
5218   case ISD::SIGN_EXTEND_INREG: {
5219     // Only custom lower when ExtraVT has a legal byte based element type.
5220     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5221     EVT ExtraEltVT = ExtraVT.getVectorElementType();
5222     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
5223         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
5224       return SDValue();
5225 
5226     return LowerToPredicatedOp(Op, DAG,
5227                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
5228   }
5229   case ISD::TRUNCATE:
5230     return LowerTRUNCATE(Op, DAG);
5231   case ISD::MLOAD:
5232     return LowerMLOAD(Op, DAG);
5233   case ISD::LOAD:
5234     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
5235       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
5236     return LowerLOAD(Op, DAG);
5237   case ISD::ADD:
5238     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
5239   case ISD::AND:
5240     return LowerToScalableOp(Op, DAG);
5241   case ISD::SUB:
5242     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
5243   case ISD::FMAXIMUM:
5244     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED);
5245   case ISD::FMAXNUM:
5246     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
5247   case ISD::FMINIMUM:
5248     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED);
5249   case ISD::FMINNUM:
5250     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
5251   case ISD::VSELECT:
5252     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
5253   case ISD::ABS:
5254     return LowerABS(Op, DAG);
5255   case ISD::ABDS:
5256     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABDS_PRED);
5257   case ISD::ABDU:
5258     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABDU_PRED);
5259   case ISD::BITREVERSE:
5260     return LowerBitreverse(Op, DAG);
5261   case ISD::BSWAP:
5262     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
5263   case ISD::CTLZ:
5264     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU,
5265                                /*OverrideNEON=*/true);
5266   case ISD::CTTZ:
5267     return LowerCTTZ(Op, DAG);
5268   case ISD::VECTOR_SPLICE:
5269     return LowerVECTOR_SPLICE(Op, DAG);
5270   }
5271 }
5272 
5273 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
5274   return !Subtarget->useSVEForFixedLengthVectors();
5275 }
5276 
5277 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
5278     EVT VT, bool OverrideNEON) const {
5279   if (!Subtarget->useSVEForFixedLengthVectors())
5280     return false;
5281 
5282   if (!VT.isFixedLengthVector())
5283     return false;
5284 
5285   // Don't use SVE for vectors we cannot scalarize if required.
5286   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
5287   // Fixed length predicates should be promoted to i8.
5288   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
5289   case MVT::i1:
5290   default:
5291     return false;
5292   case MVT::i8:
5293   case MVT::i16:
5294   case MVT::i32:
5295   case MVT::i64:
5296   case MVT::f16:
5297   case MVT::f32:
5298   case MVT::f64:
5299     break;
5300   }
5301 
5302   // All SVE implementations support NEON sized vectors.
5303   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
5304     return true;
5305 
5306   // Ensure NEON MVTs only belong to a single register class.
5307   if (VT.getFixedSizeInBits() <= 128)
5308     return false;
5309 
5310   // Don't use SVE for types that don't fit.
5311   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
5312     return false;
5313 
5314   // TODO: Perhaps an artificial restriction, but worth having whilst getting
5315   // the base fixed length SVE support in place.
5316   if (!VT.isPow2VectorType())
5317     return false;
5318 
5319   return true;
5320 }
5321 
5322 //===----------------------------------------------------------------------===//
5323 //                      Calling Convention Implementation
5324 //===----------------------------------------------------------------------===//
5325 
5326 /// Selects the correct CCAssignFn for a given CallingConvention value.
5327 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
5328                                                      bool IsVarArg) const {
5329   switch (CC) {
5330   default:
5331     report_fatal_error("Unsupported calling convention.");
5332   case CallingConv::WebKit_JS:
5333     return CC_AArch64_WebKit_JS;
5334   case CallingConv::GHC:
5335     return CC_AArch64_GHC;
5336   case CallingConv::C:
5337   case CallingConv::Fast:
5338   case CallingConv::PreserveMost:
5339   case CallingConv::CXX_FAST_TLS:
5340   case CallingConv::Swift:
5341   case CallingConv::SwiftTail:
5342   case CallingConv::Tail:
5343     if (Subtarget->isTargetWindows() && IsVarArg)
5344       return CC_AArch64_Win64_VarArg;
5345     if (!Subtarget->isTargetDarwin())
5346       return CC_AArch64_AAPCS;
5347     if (!IsVarArg)
5348       return CC_AArch64_DarwinPCS;
5349     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
5350                                       : CC_AArch64_DarwinPCS_VarArg;
5351    case CallingConv::Win64:
5352     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
5353    case CallingConv::CFGuard_Check:
5354      return CC_AArch64_Win64_CFGuard_Check;
5355    case CallingConv::AArch64_VectorCall:
5356    case CallingConv::AArch64_SVE_VectorCall:
5357      return CC_AArch64_AAPCS;
5358   }
5359 }
5360 
5361 CCAssignFn *
5362 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
5363   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
5364                                       : RetCC_AArch64_AAPCS;
5365 }
5366 
5367 SDValue AArch64TargetLowering::LowerFormalArguments(
5368     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
5369     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5370     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5371   MachineFunction &MF = DAG.getMachineFunction();
5372   MachineFrameInfo &MFI = MF.getFrameInfo();
5373   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
5374 
5375   // Assign locations to all of the incoming arguments.
5376   SmallVector<CCValAssign, 16> ArgLocs;
5377   DenseMap<unsigned, SDValue> CopiedRegs;
5378   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5379 
5380   // At this point, Ins[].VT may already be promoted to i32. To correctly
5381   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
5382   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
5383   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
5384   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
5385   // LocVT.
5386   unsigned NumArgs = Ins.size();
5387   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
5388   unsigned CurArgIdx = 0;
5389   for (unsigned i = 0; i != NumArgs; ++i) {
5390     MVT ValVT = Ins[i].VT;
5391     if (Ins[i].isOrigArg()) {
5392       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
5393       CurArgIdx = Ins[i].getOrigArgIndex();
5394 
5395       // Get type of the original argument.
5396       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
5397                                   /*AllowUnknown*/ true);
5398       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
5399       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5400       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
5401         ValVT = MVT::i8;
5402       else if (ActualMVT == MVT::i16)
5403         ValVT = MVT::i16;
5404     }
5405     bool UseVarArgCC = false;
5406     if (IsWin64)
5407       UseVarArgCC = isVarArg;
5408     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
5409     bool Res =
5410         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
5411     assert(!Res && "Call operand has unhandled type");
5412     (void)Res;
5413   }
5414   SmallVector<SDValue, 16> ArgValues;
5415   unsigned ExtraArgLocs = 0;
5416   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5417     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
5418 
5419     if (Ins[i].Flags.isByVal()) {
5420       // Byval is used for HFAs in the PCS, but the system should work in a
5421       // non-compliant manner for larger structs.
5422       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5423       int Size = Ins[i].Flags.getByValSize();
5424       unsigned NumRegs = (Size + 7) / 8;
5425 
5426       // FIXME: This works on big-endian for composite byvals, which are the common
5427       // case. It should also work for fundamental types too.
5428       unsigned FrameIdx =
5429         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
5430       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
5431       InVals.push_back(FrameIdxN);
5432 
5433       continue;
5434     }
5435 
5436     if (Ins[i].Flags.isSwiftAsync())
5437       MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
5438 
5439     SDValue ArgValue;
5440     if (VA.isRegLoc()) {
5441       // Arguments stored in registers.
5442       EVT RegVT = VA.getLocVT();
5443       const TargetRegisterClass *RC;
5444 
5445       if (RegVT == MVT::i32)
5446         RC = &AArch64::GPR32RegClass;
5447       else if (RegVT == MVT::i64)
5448         RC = &AArch64::GPR64RegClass;
5449       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
5450         RC = &AArch64::FPR16RegClass;
5451       else if (RegVT == MVT::f32)
5452         RC = &AArch64::FPR32RegClass;
5453       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
5454         RC = &AArch64::FPR64RegClass;
5455       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
5456         RC = &AArch64::FPR128RegClass;
5457       else if (RegVT.isScalableVector() &&
5458                RegVT.getVectorElementType() == MVT::i1)
5459         RC = &AArch64::PPRRegClass;
5460       else if (RegVT.isScalableVector())
5461         RC = &AArch64::ZPRRegClass;
5462       else
5463         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
5464 
5465       // Transform the arguments in physical registers into virtual ones.
5466       Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
5467       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
5468 
5469       // If this is an 8, 16 or 32-bit value, it is really passed promoted
5470       // to 64 bits.  Insert an assert[sz]ext to capture this, then
5471       // truncate to the right size.
5472       switch (VA.getLocInfo()) {
5473       default:
5474         llvm_unreachable("Unknown loc info!");
5475       case CCValAssign::Full:
5476         break;
5477       case CCValAssign::Indirect:
5478         assert(VA.getValVT().isScalableVector() &&
5479                "Only scalable vectors can be passed indirectly");
5480         break;
5481       case CCValAssign::BCvt:
5482         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
5483         break;
5484       case CCValAssign::AExt:
5485       case CCValAssign::SExt:
5486       case CCValAssign::ZExt:
5487         break;
5488       case CCValAssign::AExtUpper:
5489         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
5490                                DAG.getConstant(32, DL, RegVT));
5491         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
5492         break;
5493       }
5494     } else { // VA.isRegLoc()
5495       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
5496       unsigned ArgOffset = VA.getLocMemOffset();
5497       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
5498                               ? VA.getLocVT().getSizeInBits()
5499                               : VA.getValVT().getSizeInBits()) / 8;
5500 
5501       uint32_t BEAlign = 0;
5502       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
5503           !Ins[i].Flags.isInConsecutiveRegs())
5504         BEAlign = 8 - ArgSize;
5505 
5506       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
5507 
5508       // Create load nodes to retrieve arguments from the stack.
5509       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
5510 
5511       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
5512       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5513       MVT MemVT = VA.getValVT();
5514 
5515       switch (VA.getLocInfo()) {
5516       default:
5517         break;
5518       case CCValAssign::Trunc:
5519       case CCValAssign::BCvt:
5520         MemVT = VA.getLocVT();
5521         break;
5522       case CCValAssign::Indirect:
5523         assert(VA.getValVT().isScalableVector() &&
5524                "Only scalable vectors can be passed indirectly");
5525         MemVT = VA.getLocVT();
5526         break;
5527       case CCValAssign::SExt:
5528         ExtType = ISD::SEXTLOAD;
5529         break;
5530       case CCValAssign::ZExt:
5531         ExtType = ISD::ZEXTLOAD;
5532         break;
5533       case CCValAssign::AExt:
5534         ExtType = ISD::EXTLOAD;
5535         break;
5536       }
5537 
5538       ArgValue =
5539           DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
5540                          MachinePointerInfo::getFixedStack(MF, FI), MemVT);
5541     }
5542 
5543     if (VA.getLocInfo() == CCValAssign::Indirect) {
5544       assert(VA.getValVT().isScalableVector() &&
5545            "Only scalable vectors can be passed indirectly");
5546 
5547       uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize();
5548       unsigned NumParts = 1;
5549       if (Ins[i].Flags.isInConsecutiveRegs()) {
5550         assert(!Ins[i].Flags.isInConsecutiveRegsLast());
5551         while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
5552           ++NumParts;
5553       }
5554 
5555       MVT PartLoad = VA.getValVT();
5556       SDValue Ptr = ArgValue;
5557 
5558       // Ensure we generate all loads for each tuple part, whilst updating the
5559       // pointer after each load correctly using vscale.
5560       while (NumParts > 0) {
5561         ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
5562         InVals.push_back(ArgValue);
5563         NumParts--;
5564         if (NumParts > 0) {
5565           SDValue BytesIncrement = DAG.getVScale(
5566               DL, Ptr.getValueType(),
5567               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
5568           SDNodeFlags Flags;
5569           Flags.setNoUnsignedWrap(true);
5570           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5571                             BytesIncrement, Flags);
5572           ExtraArgLocs++;
5573           i++;
5574         }
5575       }
5576     } else {
5577       if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
5578         ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
5579                                ArgValue, DAG.getValueType(MVT::i32));
5580 
5581       // i1 arguments are zero-extended to i8 by the caller. Emit a
5582       // hint to reflect this.
5583       if (Ins[i].isOrigArg()) {
5584         Argument *OrigArg = MF.getFunction().getArg(Ins[i].getOrigArgIndex());
5585         if (OrigArg->getType()->isIntegerTy(1)) {
5586           if (!Ins[i].Flags.isZExt()) {
5587             ArgValue = DAG.getNode(AArch64ISD::ASSERT_ZEXT_BOOL, DL,
5588                                    ArgValue.getValueType(), ArgValue);
5589           }
5590         }
5591       }
5592 
5593       InVals.push_back(ArgValue);
5594     }
5595   }
5596   assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
5597 
5598   // varargs
5599   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5600   if (isVarArg) {
5601     if (!Subtarget->isTargetDarwin() || IsWin64) {
5602       // The AAPCS variadic function ABI is identical to the non-variadic
5603       // one. As a result there may be more arguments in registers and we should
5604       // save them for future reference.
5605       // Win64 variadic functions also pass arguments in registers, but all float
5606       // arguments are passed in integer registers.
5607       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
5608     }
5609 
5610     // This will point to the next argument passed via stack.
5611     unsigned StackOffset = CCInfo.getNextStackOffset();
5612     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
5613     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
5614     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
5615 
5616     if (MFI.hasMustTailInVarArgFunc()) {
5617       SmallVector<MVT, 2> RegParmTypes;
5618       RegParmTypes.push_back(MVT::i64);
5619       RegParmTypes.push_back(MVT::f128);
5620       // Compute the set of forwarded registers. The rest are scratch.
5621       SmallVectorImpl<ForwardedRegister> &Forwards =
5622                                        FuncInfo->getForwardedMustTailRegParms();
5623       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
5624                                                CC_AArch64_AAPCS);
5625 
5626       // Conservatively forward X8, since it might be used for aggregate return.
5627       if (!CCInfo.isAllocated(AArch64::X8)) {
5628         Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
5629         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
5630       }
5631     }
5632   }
5633 
5634   // On Windows, InReg pointers must be returned, so record the pointer in a
5635   // virtual register at the start of the function so it can be returned in the
5636   // epilogue.
5637   if (IsWin64) {
5638     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
5639       if (Ins[I].Flags.isInReg()) {
5640         assert(!FuncInfo->getSRetReturnReg());
5641 
5642         MVT PtrTy = getPointerTy(DAG.getDataLayout());
5643         Register Reg =
5644             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
5645         FuncInfo->setSRetReturnReg(Reg);
5646 
5647         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
5648         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
5649         break;
5650       }
5651     }
5652   }
5653 
5654   unsigned StackArgSize = CCInfo.getNextStackOffset();
5655   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
5656   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
5657     // This is a non-standard ABI so by fiat I say we're allowed to make full
5658     // use of the stack area to be popped, which must be aligned to 16 bytes in
5659     // any case:
5660     StackArgSize = alignTo(StackArgSize, 16);
5661 
5662     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
5663     // a multiple of 16.
5664     FuncInfo->setArgumentStackToRestore(StackArgSize);
5665 
5666     // This realignment carries over to the available bytes below. Our own
5667     // callers will guarantee the space is free by giving an aligned value to
5668     // CALLSEQ_START.
5669   }
5670   // Even if we're not expected to free up the space, it's useful to know how
5671   // much is there while considering tail calls (because we can reuse it).
5672   FuncInfo->setBytesInStackArgArea(StackArgSize);
5673 
5674   if (Subtarget->hasCustomCallingConv())
5675     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
5676 
5677   return Chain;
5678 }
5679 
5680 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
5681                                                 SelectionDAG &DAG,
5682                                                 const SDLoc &DL,
5683                                                 SDValue &Chain) const {
5684   MachineFunction &MF = DAG.getMachineFunction();
5685   MachineFrameInfo &MFI = MF.getFrameInfo();
5686   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5687   auto PtrVT = getPointerTy(DAG.getDataLayout());
5688   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
5689 
5690   SmallVector<SDValue, 8> MemOps;
5691 
5692   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
5693                                           AArch64::X3, AArch64::X4, AArch64::X5,
5694                                           AArch64::X6, AArch64::X7 };
5695   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
5696   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
5697 
5698   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
5699   int GPRIdx = 0;
5700   if (GPRSaveSize != 0) {
5701     if (IsWin64) {
5702       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
5703       if (GPRSaveSize & 15)
5704         // The extra size here, if triggered, will always be 8.
5705         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
5706     } else
5707       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
5708 
5709     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
5710 
5711     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
5712       Register VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
5713       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
5714       SDValue Store =
5715           DAG.getStore(Val.getValue(1), DL, Val, FIN,
5716                        IsWin64 ? MachinePointerInfo::getFixedStack(
5717                                      MF, GPRIdx, (i - FirstVariadicGPR) * 8)
5718                                : MachinePointerInfo::getStack(MF, i * 8));
5719       MemOps.push_back(Store);
5720       FIN =
5721           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
5722     }
5723   }
5724   FuncInfo->setVarArgsGPRIndex(GPRIdx);
5725   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
5726 
5727   if (Subtarget->hasFPARMv8() && !IsWin64) {
5728     static const MCPhysReg FPRArgRegs[] = {
5729         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
5730         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
5731     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
5732     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
5733 
5734     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
5735     int FPRIdx = 0;
5736     if (FPRSaveSize != 0) {
5737       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
5738 
5739       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
5740 
5741       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
5742         Register VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
5743         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
5744 
5745         SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
5746                                      MachinePointerInfo::getStack(MF, i * 16));
5747         MemOps.push_back(Store);
5748         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
5749                           DAG.getConstant(16, DL, PtrVT));
5750       }
5751     }
5752     FuncInfo->setVarArgsFPRIndex(FPRIdx);
5753     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
5754   }
5755 
5756   if (!MemOps.empty()) {
5757     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5758   }
5759 }
5760 
5761 /// LowerCallResult - Lower the result values of a call into the
5762 /// appropriate copies out of appropriate physical registers.
5763 SDValue AArch64TargetLowering::LowerCallResult(
5764     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5765     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5766     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
5767     SDValue ThisVal) const {
5768   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5769   // Assign locations to each value returned by this call.
5770   SmallVector<CCValAssign, 16> RVLocs;
5771   DenseMap<unsigned, SDValue> CopiedRegs;
5772   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5773                  *DAG.getContext());
5774   CCInfo.AnalyzeCallResult(Ins, RetCC);
5775 
5776   // Copy all of the result registers out of their specified physreg.
5777   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5778     CCValAssign VA = RVLocs[i];
5779 
5780     // Pass 'this' value directly from the argument to return value, to avoid
5781     // reg unit interference
5782     if (i == 0 && isThisReturn) {
5783       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
5784              "unexpected return calling convention register assignment");
5785       InVals.push_back(ThisVal);
5786       continue;
5787     }
5788 
5789     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
5790     // allows one use of a physreg per block.
5791     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
5792     if (!Val) {
5793       Val =
5794           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
5795       Chain = Val.getValue(1);
5796       InFlag = Val.getValue(2);
5797       CopiedRegs[VA.getLocReg()] = Val;
5798     }
5799 
5800     switch (VA.getLocInfo()) {
5801     default:
5802       llvm_unreachable("Unknown loc info!");
5803     case CCValAssign::Full:
5804       break;
5805     case CCValAssign::BCvt:
5806       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
5807       break;
5808     case CCValAssign::AExtUpper:
5809       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
5810                         DAG.getConstant(32, DL, VA.getLocVT()));
5811       LLVM_FALLTHROUGH;
5812     case CCValAssign::AExt:
5813       LLVM_FALLTHROUGH;
5814     case CCValAssign::ZExt:
5815       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
5816       break;
5817     }
5818 
5819     InVals.push_back(Val);
5820   }
5821 
5822   return Chain;
5823 }
5824 
5825 /// Return true if the calling convention is one that we can guarantee TCO for.
5826 static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
5827   return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
5828          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
5829 }
5830 
5831 /// Return true if we might ever do TCO for calls with this calling convention.
5832 static bool mayTailCallThisCC(CallingConv::ID CC) {
5833   switch (CC) {
5834   case CallingConv::C:
5835   case CallingConv::AArch64_SVE_VectorCall:
5836   case CallingConv::PreserveMost:
5837   case CallingConv::Swift:
5838   case CallingConv::SwiftTail:
5839   case CallingConv::Tail:
5840   case CallingConv::Fast:
5841     return true;
5842   default:
5843     return false;
5844   }
5845 }
5846 
5847 static void analyzeCallOperands(const AArch64TargetLowering &TLI,
5848                                 const AArch64Subtarget *Subtarget,
5849                                 const TargetLowering::CallLoweringInfo &CLI,
5850                                 CCState &CCInfo) {
5851   const SelectionDAG &DAG = CLI.DAG;
5852   CallingConv::ID CalleeCC = CLI.CallConv;
5853   bool IsVarArg = CLI.IsVarArg;
5854   const SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
5855   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
5856 
5857   unsigned NumArgs = Outs.size();
5858   for (unsigned i = 0; i != NumArgs; ++i) {
5859     MVT ArgVT = Outs[i].VT;
5860     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5861 
5862     bool UseVarArgCC = false;
5863     if (IsVarArg) {
5864       // On Windows, the fixed arguments in a vararg call are passed in GPRs
5865       // too, so use the vararg CC to force them to integer registers.
5866       if (IsCalleeWin64) {
5867         UseVarArgCC = true;
5868       } else {
5869         UseVarArgCC = !Outs[i].IsFixed;
5870       }
5871     } else {
5872       // Get type of the original argument.
5873       EVT ActualVT =
5874           TLI.getValueType(DAG.getDataLayout(), CLI.Args[Outs[i].OrigArgIndex].Ty,
5875                        /*AllowUnknown*/ true);
5876       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ArgVT;
5877       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5878       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
5879         ArgVT = MVT::i8;
5880       else if (ActualMVT == MVT::i16)
5881         ArgVT = MVT::i16;
5882     }
5883 
5884     CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CalleeCC, UseVarArgCC);
5885     bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
5886     assert(!Res && "Call operand has unhandled type");
5887     (void)Res;
5888   }
5889 }
5890 
5891 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
5892     const CallLoweringInfo &CLI) const {
5893   CallingConv::ID CalleeCC = CLI.CallConv;
5894   if (!mayTailCallThisCC(CalleeCC))
5895     return false;
5896 
5897   SDValue Callee = CLI.Callee;
5898   bool IsVarArg = CLI.IsVarArg;
5899   const SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
5900   const SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
5901   const SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
5902   const SelectionDAG &DAG = CLI.DAG;
5903   MachineFunction &MF = DAG.getMachineFunction();
5904   const Function &CallerF = MF.getFunction();
5905   CallingConv::ID CallerCC = CallerF.getCallingConv();
5906 
5907   // Functions using the C or Fast calling convention that have an SVE signature
5908   // preserve more registers and should assume the SVE_VectorCall CC.
5909   // The check for matching callee-saved regs will determine whether it is
5910   // eligible for TCO.
5911   if ((CallerCC == CallingConv::C || CallerCC == CallingConv::Fast) &&
5912       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
5913     CallerCC = CallingConv::AArch64_SVE_VectorCall;
5914 
5915   bool CCMatch = CallerCC == CalleeCC;
5916 
5917   // When using the Windows calling convention on a non-windows OS, we want
5918   // to back up and restore X18 in such functions; we can't do a tail call
5919   // from those functions.
5920   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
5921       CalleeCC != CallingConv::Win64)
5922     return false;
5923 
5924   // Byval parameters hand the function a pointer directly into the stack area
5925   // we want to reuse during a tail call. Working around this *is* possible (see
5926   // X86) but less efficient and uglier in LowerCall.
5927   for (Function::const_arg_iterator i = CallerF.arg_begin(),
5928                                     e = CallerF.arg_end();
5929        i != e; ++i) {
5930     if (i->hasByValAttr())
5931       return false;
5932 
5933     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
5934     // In this case, it is necessary to save/restore X0 in the callee. Tail
5935     // call opt interferes with this. So we disable tail call opt when the
5936     // caller has an argument with "inreg" attribute.
5937 
5938     // FIXME: Check whether the callee also has an "inreg" argument.
5939     if (i->hasInRegAttr())
5940       return false;
5941   }
5942 
5943   if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
5944     return CCMatch;
5945 
5946   // Externally-defined functions with weak linkage should not be
5947   // tail-called on AArch64 when the OS does not support dynamic
5948   // pre-emption of symbols, as the AAELF spec requires normal calls
5949   // to undefined weak functions to be replaced with a NOP or jump to the
5950   // next instruction. The behaviour of branch instructions in this
5951   // situation (as used for tail calls) is implementation-defined, so we
5952   // cannot rely on the linker replacing the tail call with a return.
5953   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5954     const GlobalValue *GV = G->getGlobal();
5955     const Triple &TT = getTargetMachine().getTargetTriple();
5956     if (GV->hasExternalWeakLinkage() &&
5957         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
5958       return false;
5959   }
5960 
5961   // Now we search for cases where we can use a tail call without changing the
5962   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
5963   // concept.
5964 
5965   // I want anyone implementing a new calling convention to think long and hard
5966   // about this assert.
5967   assert((!IsVarArg || CalleeCC == CallingConv::C) &&
5968          "Unexpected variadic calling convention");
5969 
5970   LLVMContext &C = *DAG.getContext();
5971   // Check that the call results are passed in the same way.
5972   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
5973                                   CCAssignFnForCall(CalleeCC, IsVarArg),
5974                                   CCAssignFnForCall(CallerCC, IsVarArg)))
5975     return false;
5976   // The callee has to preserve all registers the caller needs to preserve.
5977   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5978   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5979   if (!CCMatch) {
5980     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5981     if (Subtarget->hasCustomCallingConv()) {
5982       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
5983       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
5984     }
5985     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5986       return false;
5987   }
5988 
5989   // Nothing more to check if the callee is taking no arguments
5990   if (Outs.empty())
5991     return true;
5992 
5993   SmallVector<CCValAssign, 16> ArgLocs;
5994   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
5995 
5996   analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
5997 
5998   if (IsVarArg && !(CLI.CB && CLI.CB->isMustTailCall())) {
5999     // When we are musttail, additional checks have been done and we can safely ignore this check
6000     // At least two cases here: if caller is fastcc then we can't have any
6001     // memory arguments (we'd be expected to clean up the stack afterwards). If
6002     // caller is C then we could potentially use its argument area.
6003 
6004     // FIXME: for now we take the most conservative of these in both cases:
6005     // disallow all variadic memory operands.
6006     for (const CCValAssign &ArgLoc : ArgLocs)
6007       if (!ArgLoc.isRegLoc())
6008         return false;
6009   }
6010 
6011   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6012 
6013   // If any of the arguments is passed indirectly, it must be SVE, so the
6014   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
6015   // allocate space on the stack. That is why we determine this explicitly here
6016   // the call cannot be a tailcall.
6017   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
6018         assert((A.getLocInfo() != CCValAssign::Indirect ||
6019                 A.getValVT().isScalableVector()) &&
6020                "Expected value to be scalable");
6021         return A.getLocInfo() == CCValAssign::Indirect;
6022       }))
6023     return false;
6024 
6025   // If the stack arguments for this call do not fit into our own save area then
6026   // the call cannot be made tail.
6027   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
6028     return false;
6029 
6030   const MachineRegisterInfo &MRI = MF.getRegInfo();
6031   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
6032     return false;
6033 
6034   return true;
6035 }
6036 
6037 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
6038                                                    SelectionDAG &DAG,
6039                                                    MachineFrameInfo &MFI,
6040                                                    int ClobberedFI) const {
6041   SmallVector<SDValue, 8> ArgChains;
6042   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
6043   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
6044 
6045   // Include the original chain at the beginning of the list. When this is
6046   // used by target LowerCall hooks, this helps legalize find the
6047   // CALLSEQ_BEGIN node.
6048   ArgChains.push_back(Chain);
6049 
6050   // Add a chain value for each stack argument corresponding
6051   for (SDNode *U : DAG.getEntryNode().getNode()->uses())
6052     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6053       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6054         if (FI->getIndex() < 0) {
6055           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
6056           int64_t InLastByte = InFirstByte;
6057           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
6058 
6059           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
6060               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
6061             ArgChains.push_back(SDValue(L, 1));
6062         }
6063 
6064   // Build a tokenfactor for all the chains.
6065   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6066 }
6067 
6068 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
6069                                                    bool TailCallOpt) const {
6070   return (CallCC == CallingConv::Fast && TailCallOpt) ||
6071          CallCC == CallingConv::Tail || CallCC == CallingConv::SwiftTail;
6072 }
6073 
6074 // Check if the value is zero-extended from i1 to i8
6075 static bool checkZExtBool(SDValue Arg, const SelectionDAG &DAG) {
6076   unsigned SizeInBits = Arg.getValueType().getSizeInBits();
6077   if (SizeInBits < 8)
6078     return false;
6079 
6080   APInt LowBits(SizeInBits, 0xFF);
6081   APInt RequredZero(SizeInBits, 0xFE);
6082   KnownBits Bits = DAG.computeKnownBits(Arg, LowBits, 4);
6083   bool ZExtBool = (Bits.Zero & RequredZero) == RequredZero;
6084   return ZExtBool;
6085 }
6086 
6087 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
6088 /// and add input and output parameter nodes.
6089 SDValue
6090 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
6091                                  SmallVectorImpl<SDValue> &InVals) const {
6092   SelectionDAG &DAG = CLI.DAG;
6093   SDLoc &DL = CLI.DL;
6094   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
6095   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
6096   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
6097   SDValue Chain = CLI.Chain;
6098   SDValue Callee = CLI.Callee;
6099   bool &IsTailCall = CLI.IsTailCall;
6100   CallingConv::ID &CallConv = CLI.CallConv;
6101   bool IsVarArg = CLI.IsVarArg;
6102 
6103   MachineFunction &MF = DAG.getMachineFunction();
6104   MachineFunction::CallSiteInfo CSInfo;
6105   bool IsThisReturn = false;
6106 
6107   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6108   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
6109   bool IsSibCall = false;
6110   bool GuardWithBTI = false;
6111 
6112   if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
6113       !Subtarget->noBTIAtReturnTwice()) {
6114     GuardWithBTI = FuncInfo->branchTargetEnforcement();
6115   }
6116 
6117   // Check callee args/returns for SVE registers and set calling convention
6118   // accordingly.
6119   if (CallConv == CallingConv::C || CallConv == CallingConv::Fast) {
6120     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
6121       return Out.VT.isScalableVector();
6122     });
6123     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
6124       return In.VT.isScalableVector();
6125     });
6126 
6127     if (CalleeInSVE || CalleeOutSVE)
6128       CallConv = CallingConv::AArch64_SVE_VectorCall;
6129   }
6130 
6131   if (IsTailCall) {
6132     // Check if it's really possible to do a tail call.
6133     IsTailCall = isEligibleForTailCallOptimization(CLI);
6134 
6135     // A sibling call is one where we're under the usual C ABI and not planning
6136     // to change that but can still do a tail call:
6137     if (!TailCallOpt && IsTailCall && CallConv != CallingConv::Tail &&
6138         CallConv != CallingConv::SwiftTail)
6139       IsSibCall = true;
6140 
6141     if (IsTailCall)
6142       ++NumTailCalls;
6143   }
6144 
6145   if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
6146     report_fatal_error("failed to perform tail call elimination on a call "
6147                        "site marked musttail");
6148 
6149   // Analyze operands of the call, assigning locations to each operand.
6150   SmallVector<CCValAssign, 16> ArgLocs;
6151   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6152 
6153   if (IsVarArg) {
6154     unsigned NumArgs = Outs.size();
6155 
6156     for (unsigned i = 0; i != NumArgs; ++i) {
6157       if (!Outs[i].IsFixed && Outs[i].VT.isScalableVector())
6158         report_fatal_error("Passing SVE types to variadic functions is "
6159                            "currently not supported");
6160     }
6161   }
6162 
6163   analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
6164 
6165   // Get a count of how many bytes are to be pushed on the stack.
6166   unsigned NumBytes = CCInfo.getNextStackOffset();
6167 
6168   if (IsSibCall) {
6169     // Since we're not changing the ABI to make this a tail call, the memory
6170     // operands are already available in the caller's incoming argument space.
6171     NumBytes = 0;
6172   }
6173 
6174   // FPDiff is the byte offset of the call's argument area from the callee's.
6175   // Stores to callee stack arguments will be placed in FixedStackSlots offset
6176   // by this amount for a tail call. In a sibling call it must be 0 because the
6177   // caller will deallocate the entire stack and the callee still expects its
6178   // arguments to begin at SP+0. Completely unused for non-tail calls.
6179   int FPDiff = 0;
6180 
6181   if (IsTailCall && !IsSibCall) {
6182     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
6183 
6184     // Since callee will pop argument stack as a tail call, we must keep the
6185     // popped size 16-byte aligned.
6186     NumBytes = alignTo(NumBytes, 16);
6187 
6188     // FPDiff will be negative if this tail call requires more space than we
6189     // would automatically have in our incoming argument space. Positive if we
6190     // can actually shrink the stack.
6191     FPDiff = NumReusableBytes - NumBytes;
6192 
6193     // Update the required reserved area if this is the tail call requiring the
6194     // most argument stack space.
6195     if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
6196       FuncInfo->setTailCallReservedStack(-FPDiff);
6197 
6198     // The stack pointer must be 16-byte aligned at all times it's used for a
6199     // memory operation, which in practice means at *all* times and in
6200     // particular across call boundaries. Therefore our own arguments started at
6201     // a 16-byte aligned SP and the delta applied for the tail call should
6202     // satisfy the same constraint.
6203     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
6204   }
6205 
6206   // Adjust the stack pointer for the new arguments...
6207   // These operations are automatically eliminated by the prolog/epilog pass
6208   if (!IsSibCall)
6209     Chain = DAG.getCALLSEQ_START(Chain, IsTailCall ? 0 : NumBytes, 0, DL);
6210 
6211   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
6212                                         getPointerTy(DAG.getDataLayout()));
6213 
6214   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6215   SmallSet<unsigned, 8> RegsUsed;
6216   SmallVector<SDValue, 8> MemOpChains;
6217   auto PtrVT = getPointerTy(DAG.getDataLayout());
6218 
6219   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
6220     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
6221     for (const auto &F : Forwards) {
6222       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
6223        RegsToPass.emplace_back(F.PReg, Val);
6224     }
6225   }
6226 
6227   // Walk the register/memloc assignments, inserting copies/loads.
6228   unsigned ExtraArgLocs = 0;
6229   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
6230     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
6231     SDValue Arg = OutVals[i];
6232     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6233 
6234     // Promote the value if needed.
6235     switch (VA.getLocInfo()) {
6236     default:
6237       llvm_unreachable("Unknown loc info!");
6238     case CCValAssign::Full:
6239       break;
6240     case CCValAssign::SExt:
6241       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
6242       break;
6243     case CCValAssign::ZExt:
6244       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
6245       break;
6246     case CCValAssign::AExt:
6247       if (Outs[i].ArgVT == MVT::i1) {
6248         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
6249         //
6250         // Check if we actually have to do this, because the value may
6251         // already be zero-extended.
6252         //
6253         // We cannot just emit a (zext i8 (trunc (assert-zext i8)))
6254         // and rely on DAGCombiner to fold this, because the following
6255         // (anyext i32) is combined with (zext i8) in DAG.getNode:
6256         //
6257         //   (ext (zext x)) -> (zext x)
6258         //
6259         // This will give us (zext i32), which we cannot remove, so
6260         // try to check this beforehand.
6261         if (!checkZExtBool(Arg, DAG)) {
6262           Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
6263           Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
6264         }
6265       }
6266       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
6267       break;
6268     case CCValAssign::AExtUpper:
6269       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
6270       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
6271       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
6272                         DAG.getConstant(32, DL, VA.getLocVT()));
6273       break;
6274     case CCValAssign::BCvt:
6275       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
6276       break;
6277     case CCValAssign::Trunc:
6278       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6279       break;
6280     case CCValAssign::FPExt:
6281       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
6282       break;
6283     case CCValAssign::Indirect:
6284       assert(VA.getValVT().isScalableVector() &&
6285              "Only scalable vectors can be passed indirectly");
6286 
6287       uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize();
6288       uint64_t PartSize = StoreSize;
6289       unsigned NumParts = 1;
6290       if (Outs[i].Flags.isInConsecutiveRegs()) {
6291         assert(!Outs[i].Flags.isInConsecutiveRegsLast());
6292         while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
6293           ++NumParts;
6294         StoreSize *= NumParts;
6295       }
6296 
6297       MachineFrameInfo &MFI = MF.getFrameInfo();
6298       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
6299       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
6300       int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
6301       MFI.setStackID(FI, TargetStackID::ScalableVector);
6302 
6303       MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6304       SDValue Ptr = DAG.getFrameIndex(
6305           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
6306       SDValue SpillSlot = Ptr;
6307 
6308       // Ensure we generate all stores for each tuple part, whilst updating the
6309       // pointer after each store correctly using vscale.
6310       while (NumParts) {
6311         Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
6312         NumParts--;
6313         if (NumParts > 0) {
6314           SDValue BytesIncrement = DAG.getVScale(
6315               DL, Ptr.getValueType(),
6316               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
6317           SDNodeFlags Flags;
6318           Flags.setNoUnsignedWrap(true);
6319 
6320           MPI = MachinePointerInfo(MPI.getAddrSpace());
6321           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6322                             BytesIncrement, Flags);
6323           ExtraArgLocs++;
6324           i++;
6325         }
6326       }
6327 
6328       Arg = SpillSlot;
6329       break;
6330     }
6331 
6332     if (VA.isRegLoc()) {
6333       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
6334           Outs[0].VT == MVT::i64) {
6335         assert(VA.getLocVT() == MVT::i64 &&
6336                "unexpected calling convention register assignment");
6337         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
6338                "unexpected use of 'returned'");
6339         IsThisReturn = true;
6340       }
6341       if (RegsUsed.count(VA.getLocReg())) {
6342         // If this register has already been used then we're trying to pack
6343         // parts of an [N x i32] into an X-register. The extension type will
6344         // take care of putting the two halves in the right place but we have to
6345         // combine them.
6346         SDValue &Bits =
6347             llvm::find_if(RegsToPass,
6348                           [=](const std::pair<unsigned, SDValue> &Elt) {
6349                             return Elt.first == VA.getLocReg();
6350                           })
6351                 ->second;
6352         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
6353         // Call site info is used for function's parameter entry value
6354         // tracking. For now we track only simple cases when parameter
6355         // is transferred through whole register.
6356         llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
6357           return ArgReg.Reg == VA.getLocReg();
6358         });
6359       } else {
6360         RegsToPass.emplace_back(VA.getLocReg(), Arg);
6361         RegsUsed.insert(VA.getLocReg());
6362         const TargetOptions &Options = DAG.getTarget().Options;
6363         if (Options.EmitCallSiteInfo)
6364           CSInfo.emplace_back(VA.getLocReg(), i);
6365       }
6366     } else {
6367       assert(VA.isMemLoc());
6368 
6369       SDValue DstAddr;
6370       MachinePointerInfo DstInfo;
6371 
6372       // FIXME: This works on big-endian for composite byvals, which are the
6373       // common case. It should also work for fundamental types too.
6374       uint32_t BEAlign = 0;
6375       unsigned OpSize;
6376       if (VA.getLocInfo() == CCValAssign::Indirect ||
6377           VA.getLocInfo() == CCValAssign::Trunc)
6378         OpSize = VA.getLocVT().getFixedSizeInBits();
6379       else
6380         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
6381                                  : VA.getValVT().getSizeInBits();
6382       OpSize = (OpSize + 7) / 8;
6383       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
6384           !Flags.isInConsecutiveRegs()) {
6385         if (OpSize < 8)
6386           BEAlign = 8 - OpSize;
6387       }
6388       unsigned LocMemOffset = VA.getLocMemOffset();
6389       int32_t Offset = LocMemOffset + BEAlign;
6390       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
6391       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
6392 
6393       if (IsTailCall) {
6394         Offset = Offset + FPDiff;
6395         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
6396 
6397         DstAddr = DAG.getFrameIndex(FI, PtrVT);
6398         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
6399 
6400         // Make sure any stack arguments overlapping with where we're storing
6401         // are loaded before this eventual operation. Otherwise they'll be
6402         // clobbered.
6403         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
6404       } else {
6405         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
6406 
6407         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
6408         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
6409       }
6410 
6411       if (Outs[i].Flags.isByVal()) {
6412         SDValue SizeNode =
6413             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
6414         SDValue Cpy = DAG.getMemcpy(
6415             Chain, DL, DstAddr, Arg, SizeNode,
6416             Outs[i].Flags.getNonZeroByValAlign(),
6417             /*isVol = */ false, /*AlwaysInline = */ false,
6418             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
6419 
6420         MemOpChains.push_back(Cpy);
6421       } else {
6422         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
6423         // promoted to a legal register type i32, we should truncate Arg back to
6424         // i1/i8/i16.
6425         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
6426             VA.getValVT() == MVT::i16)
6427           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
6428 
6429         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
6430         MemOpChains.push_back(Store);
6431       }
6432     }
6433   }
6434 
6435   if (!MemOpChains.empty())
6436     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
6437 
6438   // Build a sequence of copy-to-reg nodes chained together with token chain
6439   // and flag operands which copy the outgoing args into the appropriate regs.
6440   SDValue InFlag;
6441   for (auto &RegToPass : RegsToPass) {
6442     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
6443                              RegToPass.second, InFlag);
6444     InFlag = Chain.getValue(1);
6445   }
6446 
6447   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
6448   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
6449   // node so that legalize doesn't hack it.
6450   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
6451     auto GV = G->getGlobal();
6452     unsigned OpFlags =
6453         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
6454     if (OpFlags & AArch64II::MO_GOT) {
6455       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
6456       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
6457     } else {
6458       const GlobalValue *GV = G->getGlobal();
6459       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
6460     }
6461   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
6462     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6463         Subtarget->isTargetMachO()) {
6464       const char *Sym = S->getSymbol();
6465       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
6466       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
6467     } else {
6468       const char *Sym = S->getSymbol();
6469       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
6470     }
6471   }
6472 
6473   // We don't usually want to end the call-sequence here because we would tidy
6474   // the frame up *after* the call, however in the ABI-changing tail-call case
6475   // we've carefully laid out the parameters so that when sp is reset they'll be
6476   // in the correct location.
6477   if (IsTailCall && !IsSibCall) {
6478     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
6479                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
6480     InFlag = Chain.getValue(1);
6481   }
6482 
6483   std::vector<SDValue> Ops;
6484   Ops.push_back(Chain);
6485   Ops.push_back(Callee);
6486 
6487   if (IsTailCall) {
6488     // Each tail call may have to adjust the stack by a different amount, so
6489     // this information must travel along with the operation for eventual
6490     // consumption by emitEpilogue.
6491     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
6492   }
6493 
6494   // Add argument registers to the end of the list so that they are known live
6495   // into the call.
6496   for (auto &RegToPass : RegsToPass)
6497     Ops.push_back(DAG.getRegister(RegToPass.first,
6498                                   RegToPass.second.getValueType()));
6499 
6500   // Add a register mask operand representing the call-preserved registers.
6501   const uint32_t *Mask;
6502   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6503   if (IsThisReturn) {
6504     // For 'this' returns, use the X0-preserving mask if applicable
6505     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
6506     if (!Mask) {
6507       IsThisReturn = false;
6508       Mask = TRI->getCallPreservedMask(MF, CallConv);
6509     }
6510   } else
6511     Mask = TRI->getCallPreservedMask(MF, CallConv);
6512 
6513   if (Subtarget->hasCustomCallingConv())
6514     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
6515 
6516   if (TRI->isAnyArgRegReserved(MF))
6517     TRI->emitReservedArgRegCallError(MF);
6518 
6519   assert(Mask && "Missing call preserved mask for calling convention");
6520   Ops.push_back(DAG.getRegisterMask(Mask));
6521 
6522   if (InFlag.getNode())
6523     Ops.push_back(InFlag);
6524 
6525   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6526 
6527   // If we're doing a tall call, use a TC_RETURN here rather than an
6528   // actual call instruction.
6529   if (IsTailCall) {
6530     MF.getFrameInfo().setHasTailCall();
6531     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
6532     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
6533     return Ret;
6534   }
6535 
6536   unsigned CallOpc = AArch64ISD::CALL;
6537   // Calls with operand bundle "clang.arc.attachedcall" are special. They should
6538   // be expanded to the call, directly followed by a special marker sequence and
6539   // a call to an ObjC library function.  Use CALL_RVMARKER to do that.
6540   if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
6541     assert(!IsTailCall &&
6542            "tail calls cannot be marked with clang.arc.attachedcall");
6543     CallOpc = AArch64ISD::CALL_RVMARKER;
6544 
6545     // Add a target global address for the retainRV/claimRV runtime function
6546     // just before the call target.
6547     Function *ARCFn = *objcarc::getAttachedARCFunction(CLI.CB);
6548     auto GA = DAG.getTargetGlobalAddress(ARCFn, DL, PtrVT);
6549     Ops.insert(Ops.begin() + 1, GA);
6550   } else if (GuardWithBTI)
6551     CallOpc = AArch64ISD::CALL_BTI;
6552 
6553   // Returns a chain and a flag for retval copy to use.
6554   Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
6555   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
6556   InFlag = Chain.getValue(1);
6557   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
6558 
6559   uint64_t CalleePopBytes =
6560       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
6561 
6562   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
6563                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
6564                              InFlag, DL);
6565   if (!Ins.empty())
6566     InFlag = Chain.getValue(1);
6567 
6568   // Handle result values, copying them out of physregs into vregs that we
6569   // return.
6570   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
6571                          InVals, IsThisReturn,
6572                          IsThisReturn ? OutVals[0] : SDValue());
6573 }
6574 
6575 bool AArch64TargetLowering::CanLowerReturn(
6576     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
6577     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
6578   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
6579   SmallVector<CCValAssign, 16> RVLocs;
6580   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6581   return CCInfo.CheckReturn(Outs, RetCC);
6582 }
6583 
6584 SDValue
6585 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6586                                    bool isVarArg,
6587                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
6588                                    const SmallVectorImpl<SDValue> &OutVals,
6589                                    const SDLoc &DL, SelectionDAG &DAG) const {
6590   auto &MF = DAG.getMachineFunction();
6591   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6592 
6593   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
6594   SmallVector<CCValAssign, 16> RVLocs;
6595   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
6596   CCInfo.AnalyzeReturn(Outs, RetCC);
6597 
6598   // Copy the result values into the output registers.
6599   SDValue Flag;
6600   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
6601   SmallSet<unsigned, 4> RegsUsed;
6602   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
6603        ++i, ++realRVLocIdx) {
6604     CCValAssign &VA = RVLocs[i];
6605     assert(VA.isRegLoc() && "Can only return in registers!");
6606     SDValue Arg = OutVals[realRVLocIdx];
6607 
6608     switch (VA.getLocInfo()) {
6609     default:
6610       llvm_unreachable("Unknown loc info!");
6611     case CCValAssign::Full:
6612       if (Outs[i].ArgVT == MVT::i1) {
6613         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
6614         // value. This is strictly redundant on Darwin (which uses "zeroext
6615         // i1"), but will be optimised out before ISel.
6616         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
6617         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
6618       }
6619       break;
6620     case CCValAssign::BCvt:
6621       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
6622       break;
6623     case CCValAssign::AExt:
6624     case CCValAssign::ZExt:
6625       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6626       break;
6627     case CCValAssign::AExtUpper:
6628       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
6629       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6630       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
6631                         DAG.getConstant(32, DL, VA.getLocVT()));
6632       break;
6633     }
6634 
6635     if (RegsUsed.count(VA.getLocReg())) {
6636       SDValue &Bits =
6637           llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
6638             return Elt.first == VA.getLocReg();
6639           })->second;
6640       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
6641     } else {
6642       RetVals.emplace_back(VA.getLocReg(), Arg);
6643       RegsUsed.insert(VA.getLocReg());
6644     }
6645   }
6646 
6647   SmallVector<SDValue, 4> RetOps(1, Chain);
6648   for (auto &RetVal : RetVals) {
6649     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
6650     Flag = Chain.getValue(1);
6651     RetOps.push_back(
6652         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
6653   }
6654 
6655   // Windows AArch64 ABIs require that for returning structs by value we copy
6656   // the sret argument into X0 for the return.
6657   // We saved the argument into a virtual register in the entry block,
6658   // so now we copy the value out and into X0.
6659   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
6660     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
6661                                      getPointerTy(MF.getDataLayout()));
6662 
6663     unsigned RetValReg = AArch64::X0;
6664     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
6665     Flag = Chain.getValue(1);
6666 
6667     RetOps.push_back(
6668       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
6669   }
6670 
6671   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6672   const MCPhysReg *I = TRI->getCalleeSavedRegsViaCopy(&MF);
6673   if (I) {
6674     for (; *I; ++I) {
6675       if (AArch64::GPR64RegClass.contains(*I))
6676         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6677       else if (AArch64::FPR64RegClass.contains(*I))
6678         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6679       else
6680         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6681     }
6682   }
6683 
6684   RetOps[0] = Chain; // Update chain.
6685 
6686   // Add the flag if we have it.
6687   if (Flag.getNode())
6688     RetOps.push_back(Flag);
6689 
6690   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
6691 }
6692 
6693 //===----------------------------------------------------------------------===//
6694 //  Other Lowering Code
6695 //===----------------------------------------------------------------------===//
6696 
6697 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
6698                                              SelectionDAG &DAG,
6699                                              unsigned Flag) const {
6700   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
6701                                     N->getOffset(), Flag);
6702 }
6703 
6704 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
6705                                              SelectionDAG &DAG,
6706                                              unsigned Flag) const {
6707   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
6708 }
6709 
6710 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
6711                                              SelectionDAG &DAG,
6712                                              unsigned Flag) const {
6713   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
6714                                    N->getOffset(), Flag);
6715 }
6716 
6717 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
6718                                              SelectionDAG &DAG,
6719                                              unsigned Flag) const {
6720   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
6721 }
6722 
6723 // (loadGOT sym)
6724 template <class NodeTy>
6725 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
6726                                       unsigned Flags) const {
6727   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
6728   SDLoc DL(N);
6729   EVT Ty = getPointerTy(DAG.getDataLayout());
6730   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
6731   // FIXME: Once remat is capable of dealing with instructions with register
6732   // operands, expand this into two nodes instead of using a wrapper node.
6733   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
6734 }
6735 
6736 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
6737 template <class NodeTy>
6738 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
6739                                             unsigned Flags) const {
6740   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
6741   SDLoc DL(N);
6742   EVT Ty = getPointerTy(DAG.getDataLayout());
6743   const unsigned char MO_NC = AArch64II::MO_NC;
6744   return DAG.getNode(
6745       AArch64ISD::WrapperLarge, DL, Ty,
6746       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
6747       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
6748       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
6749       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
6750 }
6751 
6752 // (addlow (adrp %hi(sym)) %lo(sym))
6753 template <class NodeTy>
6754 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
6755                                        unsigned Flags) const {
6756   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
6757   SDLoc DL(N);
6758   EVT Ty = getPointerTy(DAG.getDataLayout());
6759   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
6760   SDValue Lo = getTargetNode(N, Ty, DAG,
6761                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
6762   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
6763   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
6764 }
6765 
6766 // (adr sym)
6767 template <class NodeTy>
6768 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
6769                                            unsigned Flags) const {
6770   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
6771   SDLoc DL(N);
6772   EVT Ty = getPointerTy(DAG.getDataLayout());
6773   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
6774   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
6775 }
6776 
6777 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
6778                                                   SelectionDAG &DAG) const {
6779   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
6780   const GlobalValue *GV = GN->getGlobal();
6781   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6782 
6783   if (OpFlags != AArch64II::MO_NO_FLAG)
6784     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
6785            "unexpected offset in global node");
6786 
6787   // This also catches the large code model case for Darwin, and tiny code
6788   // model with got relocations.
6789   if ((OpFlags & AArch64II::MO_GOT) != 0) {
6790     return getGOT(GN, DAG, OpFlags);
6791   }
6792 
6793   SDValue Result;
6794   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6795     Result = getAddrLarge(GN, DAG, OpFlags);
6796   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6797     Result = getAddrTiny(GN, DAG, OpFlags);
6798   } else {
6799     Result = getAddr(GN, DAG, OpFlags);
6800   }
6801   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6802   SDLoc DL(GN);
6803   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
6804     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
6805                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
6806   return Result;
6807 }
6808 
6809 /// Convert a TLS address reference into the correct sequence of loads
6810 /// and calls to compute the variable's address (for Darwin, currently) and
6811 /// return an SDValue containing the final node.
6812 
6813 /// Darwin only has one TLS scheme which must be capable of dealing with the
6814 /// fully general situation, in the worst case. This means:
6815 ///     + "extern __thread" declaration.
6816 ///     + Defined in a possibly unknown dynamic library.
6817 ///
6818 /// The general system is that each __thread variable has a [3 x i64] descriptor
6819 /// which contains information used by the runtime to calculate the address. The
6820 /// only part of this the compiler needs to know about is the first xword, which
6821 /// contains a function pointer that must be called with the address of the
6822 /// entire descriptor in "x0".
6823 ///
6824 /// Since this descriptor may be in a different unit, in general even the
6825 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
6826 /// is:
6827 ///     adrp x0, _var@TLVPPAGE
6828 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
6829 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
6830 ///                                      ; the function pointer
6831 ///     blr x1                           ; Uses descriptor address in x0
6832 ///     ; Address of _var is now in x0.
6833 ///
6834 /// If the address of _var's descriptor *is* known to the linker, then it can
6835 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
6836 /// a slight efficiency gain.
6837 SDValue
6838 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
6839                                                    SelectionDAG &DAG) const {
6840   assert(Subtarget->isTargetDarwin() &&
6841          "This function expects a Darwin target");
6842 
6843   SDLoc DL(Op);
6844   MVT PtrVT = getPointerTy(DAG.getDataLayout());
6845   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6846   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6847 
6848   SDValue TLVPAddr =
6849       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6850   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
6851 
6852   // The first entry in the descriptor is a function pointer that we must call
6853   // to obtain the address of the variable.
6854   SDValue Chain = DAG.getEntryNode();
6855   SDValue FuncTLVGet = DAG.getLoad(
6856       PtrMemVT, DL, Chain, DescAddr,
6857       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
6858       Align(PtrMemVT.getSizeInBits() / 8),
6859       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6860   Chain = FuncTLVGet.getValue(1);
6861 
6862   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
6863   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
6864 
6865   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6866   MFI.setAdjustsStack(true);
6867 
6868   // TLS calls preserve all registers except those that absolutely must be
6869   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
6870   // silly).
6871   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6872   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
6873   if (Subtarget->hasCustomCallingConv())
6874     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
6875 
6876   // Finally, we can make the call. This is just a degenerate version of a
6877   // normal AArch64 call node: x0 takes the address of the descriptor, and
6878   // returns the address of the variable in this thread.
6879   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
6880   Chain =
6881       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
6882                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
6883                   DAG.getRegisterMask(Mask), Chain.getValue(1));
6884   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
6885 }
6886 
6887 /// Convert a thread-local variable reference into a sequence of instructions to
6888 /// compute the variable's address for the local exec TLS model of ELF targets.
6889 /// The sequence depends on the maximum TLS area size.
6890 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
6891                                                     SDValue ThreadBase,
6892                                                     const SDLoc &DL,
6893                                                     SelectionDAG &DAG) const {
6894   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6895   SDValue TPOff, Addr;
6896 
6897   switch (DAG.getTarget().Options.TLSSize) {
6898   default:
6899     llvm_unreachable("Unexpected TLS size");
6900 
6901   case 12: {
6902     // mrs   x0, TPIDR_EL0
6903     // add   x0, x0, :tprel_lo12:a
6904     SDValue Var = DAG.getTargetGlobalAddress(
6905         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
6906     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6907                                       Var,
6908                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6909                    0);
6910   }
6911 
6912   case 24: {
6913     // mrs   x0, TPIDR_EL0
6914     // add   x0, x0, :tprel_hi12:a
6915     // add   x0, x0, :tprel_lo12_nc:a
6916     SDValue HiVar = DAG.getTargetGlobalAddress(
6917         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6918     SDValue LoVar = DAG.getTargetGlobalAddress(
6919         GV, DL, PtrVT, 0,
6920         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6921     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6922                                       HiVar,
6923                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6924                    0);
6925     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
6926                                       LoVar,
6927                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6928                    0);
6929   }
6930 
6931   case 32: {
6932     // mrs   x1, TPIDR_EL0
6933     // movz  x0, #:tprel_g1:a
6934     // movk  x0, #:tprel_g0_nc:a
6935     // add   x0, x1, x0
6936     SDValue HiVar = DAG.getTargetGlobalAddress(
6937         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
6938     SDValue LoVar = DAG.getTargetGlobalAddress(
6939         GV, DL, PtrVT, 0,
6940         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6941     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6942                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6943                     0);
6944     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6945                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6946                     0);
6947     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6948   }
6949 
6950   case 48: {
6951     // mrs   x1, TPIDR_EL0
6952     // movz  x0, #:tprel_g2:a
6953     // movk  x0, #:tprel_g1_nc:a
6954     // movk  x0, #:tprel_g0_nc:a
6955     // add   x0, x1, x0
6956     SDValue HiVar = DAG.getTargetGlobalAddress(
6957         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
6958     SDValue MiVar = DAG.getTargetGlobalAddress(
6959         GV, DL, PtrVT, 0,
6960         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
6961     SDValue LoVar = DAG.getTargetGlobalAddress(
6962         GV, DL, PtrVT, 0,
6963         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6964     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6965                                        DAG.getTargetConstant(32, DL, MVT::i32)),
6966                     0);
6967     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
6968                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6969                     0);
6970     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6971                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6972                     0);
6973     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6974   }
6975   }
6976 }
6977 
6978 /// When accessing thread-local variables under either the general-dynamic or
6979 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
6980 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
6981 /// is a function pointer to carry out the resolution.
6982 ///
6983 /// The sequence is:
6984 ///    adrp  x0, :tlsdesc:var
6985 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
6986 ///    add   x0, x0, #:tlsdesc_lo12:var
6987 ///    .tlsdesccall var
6988 ///    blr   x1
6989 ///    (TPIDR_EL0 offset now in x0)
6990 ///
6991 ///  The above sequence must be produced unscheduled, to enable the linker to
6992 ///  optimize/relax this sequence.
6993 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
6994 ///  above sequence, and expanded really late in the compilation flow, to ensure
6995 ///  the sequence is produced as per above.
6996 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
6997                                                       const SDLoc &DL,
6998                                                       SelectionDAG &DAG) const {
6999   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7000 
7001   SDValue Chain = DAG.getEntryNode();
7002   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7003 
7004   Chain =
7005       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
7006   SDValue Glue = Chain.getValue(1);
7007 
7008   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
7009 }
7010 
7011 SDValue
7012 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
7013                                                 SelectionDAG &DAG) const {
7014   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
7015 
7016   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7017 
7018   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
7019 
7020   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
7021     if (Model == TLSModel::LocalDynamic)
7022       Model = TLSModel::GeneralDynamic;
7023   }
7024 
7025   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
7026       Model != TLSModel::LocalExec)
7027     report_fatal_error("ELF TLS only supported in small memory model or "
7028                        "in local exec TLS model");
7029   // Different choices can be made for the maximum size of the TLS area for a
7030   // module. For the small address model, the default TLS size is 16MiB and the
7031   // maximum TLS size is 4GiB.
7032   // FIXME: add tiny and large code model support for TLS access models other
7033   // than local exec. We currently generate the same code as small for tiny,
7034   // which may be larger than needed.
7035 
7036   SDValue TPOff;
7037   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7038   SDLoc DL(Op);
7039   const GlobalValue *GV = GA->getGlobal();
7040 
7041   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
7042 
7043   if (Model == TLSModel::LocalExec) {
7044     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
7045   } else if (Model == TLSModel::InitialExec) {
7046     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
7047     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
7048   } else if (Model == TLSModel::LocalDynamic) {
7049     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
7050     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
7051     // the beginning of the module's TLS region, followed by a DTPREL offset
7052     // calculation.
7053 
7054     // These accesses will need deduplicating if there's more than one.
7055     AArch64FunctionInfo *MFI =
7056         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7057     MFI->incNumLocalDynamicTLSAccesses();
7058 
7059     // The call needs a relocation too for linker relaxation. It doesn't make
7060     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
7061     // the address.
7062     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
7063                                                   AArch64II::MO_TLS);
7064 
7065     // Now we can calculate the offset from TPIDR_EL0 to this module's
7066     // thread-local area.
7067     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
7068 
7069     // Now use :dtprel_whatever: operations to calculate this variable's offset
7070     // in its thread-storage area.
7071     SDValue HiVar = DAG.getTargetGlobalAddress(
7072         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
7073     SDValue LoVar = DAG.getTargetGlobalAddress(
7074         GV, DL, MVT::i64, 0,
7075         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
7076 
7077     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
7078                                        DAG.getTargetConstant(0, DL, MVT::i32)),
7079                     0);
7080     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
7081                                        DAG.getTargetConstant(0, DL, MVT::i32)),
7082                     0);
7083   } else if (Model == TLSModel::GeneralDynamic) {
7084     // The call needs a relocation too for linker relaxation. It doesn't make
7085     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
7086     // the address.
7087     SDValue SymAddr =
7088         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
7089 
7090     // Finally we can make a call to calculate the offset from tpidr_el0.
7091     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
7092   } else
7093     llvm_unreachable("Unsupported ELF TLS access model");
7094 
7095   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
7096 }
7097 
7098 SDValue
7099 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
7100                                                     SelectionDAG &DAG) const {
7101   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
7102 
7103   SDValue Chain = DAG.getEntryNode();
7104   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7105   SDLoc DL(Op);
7106 
7107   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
7108 
7109   // Load the ThreadLocalStoragePointer from the TEB
7110   // A pointer to the TLS array is located at offset 0x58 from the TEB.
7111   SDValue TLSArray =
7112       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
7113   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
7114   Chain = TLSArray.getValue(1);
7115 
7116   // Load the TLS index from the C runtime;
7117   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
7118   // This also does the same as LOADgot, but using a generic i32 load,
7119   // while LOADgot only loads i64.
7120   SDValue TLSIndexHi =
7121       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
7122   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
7123       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
7124   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
7125   SDValue TLSIndex =
7126       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
7127   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
7128   Chain = TLSIndex.getValue(1);
7129 
7130   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
7131   // offset into the TLSArray.
7132   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
7133   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
7134                              DAG.getConstant(3, DL, PtrVT));
7135   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
7136                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
7137                             MachinePointerInfo());
7138   Chain = TLS.getValue(1);
7139 
7140   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7141   const GlobalValue *GV = GA->getGlobal();
7142   SDValue TGAHi = DAG.getTargetGlobalAddress(
7143       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
7144   SDValue TGALo = DAG.getTargetGlobalAddress(
7145       GV, DL, PtrVT, 0,
7146       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
7147 
7148   // Add the offset from the start of the .tls section (section base).
7149   SDValue Addr =
7150       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
7151                                  DAG.getTargetConstant(0, DL, MVT::i32)),
7152               0);
7153   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
7154   return Addr;
7155 }
7156 
7157 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
7158                                                      SelectionDAG &DAG) const {
7159   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7160   if (DAG.getTarget().useEmulatedTLS())
7161     return LowerToTLSEmulatedModel(GA, DAG);
7162 
7163   if (Subtarget->isTargetDarwin())
7164     return LowerDarwinGlobalTLSAddress(Op, DAG);
7165   if (Subtarget->isTargetELF())
7166     return LowerELFGlobalTLSAddress(Op, DAG);
7167   if (Subtarget->isTargetWindows())
7168     return LowerWindowsGlobalTLSAddress(Op, DAG);
7169 
7170   llvm_unreachable("Unexpected platform trying to use TLS");
7171 }
7172 
7173 // Looks through \param Val to determine the bit that can be used to
7174 // check the sign of the value. It returns the unextended value and
7175 // the sign bit position.
7176 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
7177   if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
7178     return {Val.getOperand(0),
7179             cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
7180                 1};
7181 
7182   if (Val.getOpcode() == ISD::SIGN_EXTEND)
7183     return {Val.getOperand(0),
7184             Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
7185 
7186   return {Val, Val.getValueSizeInBits() - 1};
7187 }
7188 
7189 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
7190   SDValue Chain = Op.getOperand(0);
7191   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
7192   SDValue LHS = Op.getOperand(2);
7193   SDValue RHS = Op.getOperand(3);
7194   SDValue Dest = Op.getOperand(4);
7195   SDLoc dl(Op);
7196 
7197   MachineFunction &MF = DAG.getMachineFunction();
7198   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
7199   // will not be produced, as they are conditional branch instructions that do
7200   // not set flags.
7201   bool ProduceNonFlagSettingCondBr =
7202       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
7203 
7204   // Handle f128 first, since lowering it will result in comparing the return
7205   // value of a libcall against zero, which is just what the rest of LowerBR_CC
7206   // is expecting to deal with.
7207   if (LHS.getValueType() == MVT::f128) {
7208     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
7209 
7210     // If softenSetCCOperands returned a scalar, we need to compare the result
7211     // against zero to select between true and false values.
7212     if (!RHS.getNode()) {
7213       RHS = DAG.getConstant(0, dl, LHS.getValueType());
7214       CC = ISD::SETNE;
7215     }
7216   }
7217 
7218   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
7219   // instruction.
7220   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
7221       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7222     // Only lower legal XALUO ops.
7223     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
7224       return SDValue();
7225 
7226     // The actual operation with overflow check.
7227     AArch64CC::CondCode OFCC;
7228     SDValue Value, Overflow;
7229     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
7230 
7231     if (CC == ISD::SETNE)
7232       OFCC = getInvertedCondCode(OFCC);
7233     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
7234 
7235     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
7236                        Overflow);
7237   }
7238 
7239   if (LHS.getValueType().isInteger()) {
7240     assert((LHS.getValueType() == RHS.getValueType()) &&
7241            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
7242 
7243     // If the RHS of the comparison is zero, we can potentially fold this
7244     // to a specialized branch.
7245     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
7246     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
7247       if (CC == ISD::SETEQ) {
7248         // See if we can use a TBZ to fold in an AND as well.
7249         // TBZ has a smaller branch displacement than CBZ.  If the offset is
7250         // out of bounds, a late MI-layer pass rewrites branches.
7251         // 403.gcc is an example that hits this case.
7252         if (LHS.getOpcode() == ISD::AND &&
7253             isa<ConstantSDNode>(LHS.getOperand(1)) &&
7254             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
7255           SDValue Test = LHS.getOperand(0);
7256           uint64_t Mask = LHS.getConstantOperandVal(1);
7257           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
7258                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
7259                              Dest);
7260         }
7261 
7262         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
7263       } else if (CC == ISD::SETNE) {
7264         // See if we can use a TBZ to fold in an AND as well.
7265         // TBZ has a smaller branch displacement than CBZ.  If the offset is
7266         // out of bounds, a late MI-layer pass rewrites branches.
7267         // 403.gcc is an example that hits this case.
7268         if (LHS.getOpcode() == ISD::AND &&
7269             isa<ConstantSDNode>(LHS.getOperand(1)) &&
7270             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
7271           SDValue Test = LHS.getOperand(0);
7272           uint64_t Mask = LHS.getConstantOperandVal(1);
7273           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
7274                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
7275                              Dest);
7276         }
7277 
7278         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
7279       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
7280         // Don't combine AND since emitComparison converts the AND to an ANDS
7281         // (a.k.a. TST) and the test in the test bit and branch instruction
7282         // becomes redundant.  This would also increase register pressure.
7283         uint64_t SignBitPos;
7284         std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
7285         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
7286                            DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
7287       }
7288     }
7289     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
7290         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
7291       // Don't combine AND since emitComparison converts the AND to an ANDS
7292       // (a.k.a. TST) and the test in the test bit and branch instruction
7293       // becomes redundant.  This would also increase register pressure.
7294       uint64_t SignBitPos;
7295       std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
7296       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
7297                          DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
7298     }
7299 
7300     SDValue CCVal;
7301     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
7302     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
7303                        Cmp);
7304   }
7305 
7306   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
7307          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
7308 
7309   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7310   // clean.  Some of them require two branches to implement.
7311   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7312   AArch64CC::CondCode CC1, CC2;
7313   changeFPCCToAArch64CC(CC, CC1, CC2);
7314   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7315   SDValue BR1 =
7316       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
7317   if (CC2 != AArch64CC::AL) {
7318     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7319     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
7320                        Cmp);
7321   }
7322 
7323   return BR1;
7324 }
7325 
7326 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
7327                                               SelectionDAG &DAG) const {
7328   EVT VT = Op.getValueType();
7329   SDLoc DL(Op);
7330 
7331   SDValue In1 = Op.getOperand(0);
7332   SDValue In2 = Op.getOperand(1);
7333   EVT SrcVT = In2.getValueType();
7334 
7335   if (VT.isScalableVector()) {
7336     if (VT != SrcVT)
7337       return SDValue();
7338 
7339     // copysign(x,y) -> (y & SIGN_MASK) | (x & ~SIGN_MASK)
7340     //
7341     // A possible alternative sequence involves using FNEG_MERGE_PASSTHRU;
7342     // maybe useful for copysign operations with mismatched VTs.
7343     //
7344     // IntVT here is chosen so it's a legal type with the same element width
7345     // as the input.
7346     EVT IntVT =
7347         getPackedSVEVectorVT(VT.getVectorElementType().changeTypeToInteger());
7348     unsigned NumBits = VT.getScalarSizeInBits();
7349     SDValue SignMask = DAG.getConstant(APInt::getSignMask(NumBits), DL, IntVT);
7350     SDValue InvSignMask = DAG.getNOT(DL, SignMask, IntVT);
7351     SDValue Sign = DAG.getNode(ISD::AND, DL, IntVT, SignMask,
7352                                getSVESafeBitCast(IntVT, In2, DAG));
7353     SDValue Magnitude = DAG.getNode(ISD::AND, DL, IntVT, InvSignMask,
7354                                     getSVESafeBitCast(IntVT, In1, DAG));
7355     SDValue IntResult = DAG.getNode(ISD::OR, DL, IntVT, Sign, Magnitude);
7356     return getSVESafeBitCast(VT, IntResult, DAG);
7357   }
7358 
7359   if (!Subtarget->hasNEON())
7360     return SDValue();
7361 
7362   if (SrcVT.bitsLT(VT))
7363     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
7364   else if (SrcVT.bitsGT(VT))
7365     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
7366 
7367   EVT VecVT;
7368   uint64_t EltMask;
7369   SDValue VecVal1, VecVal2;
7370 
7371   auto setVecVal = [&] (int Idx) {
7372     if (!VT.isVector()) {
7373       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
7374                                           DAG.getUNDEF(VecVT), In1);
7375       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
7376                                           DAG.getUNDEF(VecVT), In2);
7377     } else {
7378       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
7379       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
7380     }
7381   };
7382 
7383   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
7384     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
7385     EltMask = 0x80000000ULL;
7386     setVecVal(AArch64::ssub);
7387   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
7388     VecVT = MVT::v2i64;
7389 
7390     // We want to materialize a mask with the high bit set, but the AdvSIMD
7391     // immediate moves cannot materialize that in a single instruction for
7392     // 64-bit elements. Instead, materialize zero and then negate it.
7393     EltMask = 0;
7394 
7395     setVecVal(AArch64::dsub);
7396   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
7397     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
7398     EltMask = 0x8000ULL;
7399     setVecVal(AArch64::hsub);
7400   } else {
7401     llvm_unreachable("Invalid type for copysign!");
7402   }
7403 
7404   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
7405 
7406   // If we couldn't materialize the mask above, then the mask vector will be
7407   // the zero vector, and we need to negate it here.
7408   if (VT == MVT::f64 || VT == MVT::v2f64) {
7409     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
7410     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
7411     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
7412   }
7413 
7414   SDValue Sel =
7415       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
7416 
7417   if (VT == MVT::f16)
7418     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
7419   if (VT == MVT::f32)
7420     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
7421   else if (VT == MVT::f64)
7422     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
7423   else
7424     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
7425 }
7426 
7427 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
7428   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7429           Attribute::NoImplicitFloat))
7430     return SDValue();
7431 
7432   if (!Subtarget->hasNEON())
7433     return SDValue();
7434 
7435   // While there is no integer popcount instruction, it can
7436   // be more efficiently lowered to the following sequence that uses
7437   // AdvSIMD registers/instructions as long as the copies to/from
7438   // the AdvSIMD registers are cheap.
7439   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
7440   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
7441   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
7442   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
7443   SDValue Val = Op.getOperand(0);
7444   SDLoc DL(Op);
7445   EVT VT = Op.getValueType();
7446 
7447   if (VT == MVT::i32 || VT == MVT::i64) {
7448     if (VT == MVT::i32)
7449       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
7450     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
7451 
7452     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
7453     SDValue UaddLV = DAG.getNode(
7454         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
7455         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
7456 
7457     if (VT == MVT::i64)
7458       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
7459     return UaddLV;
7460   } else if (VT == MVT::i128) {
7461     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
7462 
7463     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
7464     SDValue UaddLV = DAG.getNode(
7465         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
7466         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
7467 
7468     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
7469   }
7470 
7471   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
7472     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
7473 
7474   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
7475           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
7476          "Unexpected type for custom ctpop lowering");
7477 
7478   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
7479   Val = DAG.getBitcast(VT8Bit, Val);
7480   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
7481 
7482   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
7483   unsigned EltSize = 8;
7484   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
7485   while (EltSize != VT.getScalarSizeInBits()) {
7486     EltSize *= 2;
7487     NumElts /= 2;
7488     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
7489     Val = DAG.getNode(
7490         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
7491         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
7492   }
7493 
7494   return Val;
7495 }
7496 
7497 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7498   EVT VT = Op.getValueType();
7499   assert(VT.isScalableVector() ||
7500          useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true));
7501 
7502   SDLoc DL(Op);
7503   SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
7504   return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
7505 }
7506 
7507 SDValue AArch64TargetLowering::LowerMinMax(SDValue Op,
7508                                            SelectionDAG &DAG) const {
7509 
7510   EVT VT = Op.getValueType();
7511   SDLoc DL(Op);
7512   unsigned Opcode = Op.getOpcode();
7513   ISD::CondCode CC;
7514   switch (Opcode) {
7515   default:
7516     llvm_unreachable("Wrong instruction");
7517   case ISD::SMAX:
7518     CC = ISD::SETGT;
7519     break;
7520   case ISD::SMIN:
7521     CC = ISD::SETLT;
7522     break;
7523   case ISD::UMAX:
7524     CC = ISD::SETUGT;
7525     break;
7526   case ISD::UMIN:
7527     CC = ISD::SETULT;
7528     break;
7529   }
7530 
7531   if (VT.isScalableVector() ||
7532       useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) {
7533     switch (Opcode) {
7534     default:
7535       llvm_unreachable("Wrong instruction");
7536     case ISD::SMAX:
7537       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
7538                                  /*OverrideNEON=*/true);
7539     case ISD::SMIN:
7540       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
7541                                  /*OverrideNEON=*/true);
7542     case ISD::UMAX:
7543       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
7544                                  /*OverrideNEON=*/true);
7545     case ISD::UMIN:
7546       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
7547                                  /*OverrideNEON=*/true);
7548     }
7549   }
7550 
7551   SDValue Op0 = Op.getOperand(0);
7552   SDValue Op1 = Op.getOperand(1);
7553   SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC);
7554   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
7555 }
7556 
7557 SDValue AArch64TargetLowering::LowerBitreverse(SDValue Op,
7558                                                SelectionDAG &DAG) const {
7559   EVT VT = Op.getValueType();
7560 
7561   if (VT.isScalableVector() ||
7562       useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
7563     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU,
7564                                true);
7565 
7566   SDLoc DL(Op);
7567   SDValue REVB;
7568   MVT VST;
7569 
7570   switch (VT.getSimpleVT().SimpleTy) {
7571   default:
7572     llvm_unreachable("Invalid type for bitreverse!");
7573 
7574   case MVT::v2i32: {
7575     VST = MVT::v8i8;
7576     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
7577 
7578     break;
7579   }
7580 
7581   case MVT::v4i32: {
7582     VST = MVT::v16i8;
7583     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
7584 
7585     break;
7586   }
7587 
7588   case MVT::v1i64: {
7589     VST = MVT::v8i8;
7590     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
7591 
7592     break;
7593   }
7594 
7595   case MVT::v2i64: {
7596     VST = MVT::v16i8;
7597     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
7598 
7599     break;
7600   }
7601   }
7602 
7603   return DAG.getNode(AArch64ISD::NVCAST, DL, VT,
7604                      DAG.getNode(ISD::BITREVERSE, DL, VST, REVB));
7605 }
7606 
7607 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7608 
7609   if (Op.getValueType().isVector())
7610     return LowerVSETCC(Op, DAG);
7611 
7612   bool IsStrict = Op->isStrictFPOpcode();
7613   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
7614   unsigned OpNo = IsStrict ? 1 : 0;
7615   SDValue Chain;
7616   if (IsStrict)
7617     Chain = Op.getOperand(0);
7618   SDValue LHS = Op.getOperand(OpNo + 0);
7619   SDValue RHS = Op.getOperand(OpNo + 1);
7620   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
7621   SDLoc dl(Op);
7622 
7623   // We chose ZeroOrOneBooleanContents, so use zero and one.
7624   EVT VT = Op.getValueType();
7625   SDValue TVal = DAG.getConstant(1, dl, VT);
7626   SDValue FVal = DAG.getConstant(0, dl, VT);
7627 
7628   // Handle f128 first, since one possible outcome is a normal integer
7629   // comparison which gets picked up by the next if statement.
7630   if (LHS.getValueType() == MVT::f128) {
7631     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
7632                         IsSignaling);
7633 
7634     // If softenSetCCOperands returned a scalar, use it.
7635     if (!RHS.getNode()) {
7636       assert(LHS.getValueType() == Op.getValueType() &&
7637              "Unexpected setcc expansion!");
7638       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
7639     }
7640   }
7641 
7642   if (LHS.getValueType().isInteger()) {
7643     SDValue CCVal;
7644     SDValue Cmp = getAArch64Cmp(
7645         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
7646 
7647     // Note that we inverted the condition above, so we reverse the order of
7648     // the true and false operands here.  This will allow the setcc to be
7649     // matched to a single CSINC instruction.
7650     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
7651     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
7652   }
7653 
7654   // Now we know we're dealing with FP values.
7655   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
7656          LHS.getValueType() == MVT::f64);
7657 
7658   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
7659   // and do the comparison.
7660   SDValue Cmp;
7661   if (IsStrict)
7662     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
7663   else
7664     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7665 
7666   AArch64CC::CondCode CC1, CC2;
7667   changeFPCCToAArch64CC(CC, CC1, CC2);
7668   SDValue Res;
7669   if (CC2 == AArch64CC::AL) {
7670     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
7671                           CC2);
7672     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7673 
7674     // Note that we inverted the condition above, so we reverse the order of
7675     // the true and false operands here.  This will allow the setcc to be
7676     // matched to a single CSINC instruction.
7677     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
7678   } else {
7679     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
7680     // totally clean.  Some of them require two CSELs to implement.  As is in
7681     // this case, we emit the first CSEL and then emit a second using the output
7682     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
7683 
7684     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
7685     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7686     SDValue CS1 =
7687         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
7688 
7689     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7690     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
7691   }
7692   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
7693 }
7694 
7695 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
7696                                               SDValue RHS, SDValue TVal,
7697                                               SDValue FVal, const SDLoc &dl,
7698                                               SelectionDAG &DAG) const {
7699   // Handle f128 first, because it will result in a comparison of some RTLIB
7700   // call result against zero.
7701   if (LHS.getValueType() == MVT::f128) {
7702     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
7703 
7704     // If softenSetCCOperands returned a scalar, we need to compare the result
7705     // against zero to select between true and false values.
7706     if (!RHS.getNode()) {
7707       RHS = DAG.getConstant(0, dl, LHS.getValueType());
7708       CC = ISD::SETNE;
7709     }
7710   }
7711 
7712   // Also handle f16, for which we need to do a f32 comparison.
7713   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
7714     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
7715     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
7716   }
7717 
7718   // Next, handle integers.
7719   if (LHS.getValueType().isInteger()) {
7720     assert((LHS.getValueType() == RHS.getValueType()) &&
7721            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
7722 
7723     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
7724     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
7725     ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
7726     // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
7727     // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
7728     // supported types.
7729     if (CC == ISD::SETGT && RHSC && RHSC->isAllOnes() && CTVal && CFVal &&
7730         CTVal->isOne() && CFVal->isAllOnes() &&
7731         LHS.getValueType() == TVal.getValueType()) {
7732       EVT VT = LHS.getValueType();
7733       SDValue Shift =
7734           DAG.getNode(ISD::SRA, dl, VT, LHS,
7735                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
7736       return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
7737     }
7738 
7739     unsigned Opcode = AArch64ISD::CSEL;
7740 
7741     // If both the TVal and the FVal are constants, see if we can swap them in
7742     // order to for a CSINV or CSINC out of them.
7743     if (CTVal && CFVal && CTVal->isAllOnes() && CFVal->isZero()) {
7744       std::swap(TVal, FVal);
7745       std::swap(CTVal, CFVal);
7746       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7747     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isZero()) {
7748       std::swap(TVal, FVal);
7749       std::swap(CTVal, CFVal);
7750       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7751     } else if (TVal.getOpcode() == ISD::XOR) {
7752       // If TVal is a NOT we want to swap TVal and FVal so that we can match
7753       // with a CSINV rather than a CSEL.
7754       if (isAllOnesConstant(TVal.getOperand(1))) {
7755         std::swap(TVal, FVal);
7756         std::swap(CTVal, CFVal);
7757         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7758       }
7759     } else if (TVal.getOpcode() == ISD::SUB) {
7760       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
7761       // that we can match with a CSNEG rather than a CSEL.
7762       if (isNullConstant(TVal.getOperand(0))) {
7763         std::swap(TVal, FVal);
7764         std::swap(CTVal, CFVal);
7765         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7766       }
7767     } else if (CTVal && CFVal) {
7768       const int64_t TrueVal = CTVal->getSExtValue();
7769       const int64_t FalseVal = CFVal->getSExtValue();
7770       bool Swap = false;
7771 
7772       // If both TVal and FVal are constants, see if FVal is the
7773       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
7774       // instead of a CSEL in that case.
7775       if (TrueVal == ~FalseVal) {
7776         Opcode = AArch64ISD::CSINV;
7777       } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
7778                  TrueVal == -FalseVal) {
7779         Opcode = AArch64ISD::CSNEG;
7780       } else if (TVal.getValueType() == MVT::i32) {
7781         // If our operands are only 32-bit wide, make sure we use 32-bit
7782         // arithmetic for the check whether we can use CSINC. This ensures that
7783         // the addition in the check will wrap around properly in case there is
7784         // an overflow (which would not be the case if we do the check with
7785         // 64-bit arithmetic).
7786         const uint32_t TrueVal32 = CTVal->getZExtValue();
7787         const uint32_t FalseVal32 = CFVal->getZExtValue();
7788 
7789         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
7790           Opcode = AArch64ISD::CSINC;
7791 
7792           if (TrueVal32 > FalseVal32) {
7793             Swap = true;
7794           }
7795         }
7796         // 64-bit check whether we can use CSINC.
7797       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
7798         Opcode = AArch64ISD::CSINC;
7799 
7800         if (TrueVal > FalseVal) {
7801           Swap = true;
7802         }
7803       }
7804 
7805       // Swap TVal and FVal if necessary.
7806       if (Swap) {
7807         std::swap(TVal, FVal);
7808         std::swap(CTVal, CFVal);
7809         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7810       }
7811 
7812       if (Opcode != AArch64ISD::CSEL) {
7813         // Drop FVal since we can get its value by simply inverting/negating
7814         // TVal.
7815         FVal = TVal;
7816       }
7817     }
7818 
7819     // Avoid materializing a constant when possible by reusing a known value in
7820     // a register.  However, don't perform this optimization if the known value
7821     // is one, zero or negative one in the case of a CSEL.  We can always
7822     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
7823     // FVal, respectively.
7824     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
7825     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
7826         !RHSVal->isZero() && !RHSVal->isAllOnes()) {
7827       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7828       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
7829       // "a != C ? x : a" to avoid materializing C.
7830       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
7831         TVal = LHS;
7832       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
7833         FVal = LHS;
7834     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
7835       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
7836       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
7837       // avoid materializing C.
7838       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7839       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
7840         Opcode = AArch64ISD::CSINV;
7841         TVal = LHS;
7842         FVal = DAG.getConstant(0, dl, FVal.getValueType());
7843       }
7844     }
7845 
7846     SDValue CCVal;
7847     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
7848     EVT VT = TVal.getValueType();
7849     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
7850   }
7851 
7852   // Now we know we're dealing with FP values.
7853   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
7854          LHS.getValueType() == MVT::f64);
7855   assert(LHS.getValueType() == RHS.getValueType());
7856   EVT VT = TVal.getValueType();
7857   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7858 
7859   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7860   // clean.  Some of them require two CSELs to implement.
7861   AArch64CC::CondCode CC1, CC2;
7862   changeFPCCToAArch64CC(CC, CC1, CC2);
7863 
7864   if (DAG.getTarget().Options.UnsafeFPMath) {
7865     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
7866     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
7867     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
7868     if (RHSVal && RHSVal->isZero()) {
7869       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
7870       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
7871 
7872       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
7873           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
7874         TVal = LHS;
7875       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
7876                CFVal && CFVal->isZero() &&
7877                FVal.getValueType() == LHS.getValueType())
7878         FVal = LHS;
7879     }
7880   }
7881 
7882   // Emit first, and possibly only, CSEL.
7883   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7884   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
7885 
7886   // If we need a second CSEL, emit it, using the output of the first as the
7887   // RHS.  We're effectively OR'ing the two CC's together.
7888   if (CC2 != AArch64CC::AL) {
7889     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7890     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
7891   }
7892 
7893   // Otherwise, return the output of the first CSEL.
7894   return CS1;
7895 }
7896 
7897 SDValue AArch64TargetLowering::LowerVECTOR_SPLICE(SDValue Op,
7898                                                   SelectionDAG &DAG) const {
7899   EVT Ty = Op.getValueType();
7900   auto Idx = Op.getConstantOperandAPInt(2);
7901   int64_t IdxVal = Idx.getSExtValue();
7902   assert(Ty.isScalableVector() &&
7903          "Only expect scalable vectors for custom lowering of VECTOR_SPLICE");
7904 
7905   // We can use the splice instruction for certain index values where we are
7906   // able to efficiently generate the correct predicate. The index will be
7907   // inverted and used directly as the input to the ptrue instruction, i.e.
7908   // -1 -> vl1, -2 -> vl2, etc. The predicate will then be reversed to get the
7909   // splice predicate. However, we can only do this if we can guarantee that
7910   // there are enough elements in the vector, hence we check the index <= min
7911   // number of elements.
7912   Optional<unsigned> PredPattern;
7913   if (Ty.isScalableVector() && IdxVal < 0 &&
7914       (PredPattern = getSVEPredPatternFromNumElements(std::abs(IdxVal))) !=
7915           None) {
7916     SDLoc DL(Op);
7917 
7918     // Create a predicate where all but the last -IdxVal elements are false.
7919     EVT PredVT = Ty.changeVectorElementType(MVT::i1);
7920     SDValue Pred = getPTrue(DAG, DL, PredVT, *PredPattern);
7921     Pred = DAG.getNode(ISD::VECTOR_REVERSE, DL, PredVT, Pred);
7922 
7923     // Now splice the two inputs together using the predicate.
7924     return DAG.getNode(AArch64ISD::SPLICE, DL, Ty, Pred, Op.getOperand(0),
7925                        Op.getOperand(1));
7926   }
7927 
7928   // This will select to an EXT instruction, which has a maximum immediate
7929   // value of 255, hence 2048-bits is the maximum value we can lower.
7930   if (IdxVal >= 0 &&
7931       IdxVal < int64_t(2048 / Ty.getVectorElementType().getSizeInBits()))
7932     return Op;
7933 
7934   return SDValue();
7935 }
7936 
7937 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
7938                                               SelectionDAG &DAG) const {
7939   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7940   SDValue LHS = Op.getOperand(0);
7941   SDValue RHS = Op.getOperand(1);
7942   SDValue TVal = Op.getOperand(2);
7943   SDValue FVal = Op.getOperand(3);
7944   SDLoc DL(Op);
7945   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
7946 }
7947 
7948 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
7949                                            SelectionDAG &DAG) const {
7950   SDValue CCVal = Op->getOperand(0);
7951   SDValue TVal = Op->getOperand(1);
7952   SDValue FVal = Op->getOperand(2);
7953   SDLoc DL(Op);
7954 
7955   EVT Ty = Op.getValueType();
7956   if (Ty.isScalableVector()) {
7957     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
7958     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
7959     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
7960     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
7961   }
7962 
7963   if (useSVEForFixedLengthVectorVT(Ty)) {
7964     // FIXME: Ideally this would be the same as above using i1 types, however
7965     // for the moment we can't deal with fixed i1 vector types properly, so
7966     // instead extend the predicate to a result type sized integer vector.
7967     MVT SplatValVT = MVT::getIntegerVT(Ty.getScalarSizeInBits());
7968     MVT PredVT = MVT::getVectorVT(SplatValVT, Ty.getVectorElementCount());
7969     SDValue SplatVal = DAG.getSExtOrTrunc(CCVal, DL, SplatValVT);
7970     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, SplatVal);
7971     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
7972   }
7973 
7974   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
7975   // instruction.
7976   if (ISD::isOverflowIntrOpRes(CCVal)) {
7977     // Only lower legal XALUO ops.
7978     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
7979       return SDValue();
7980 
7981     AArch64CC::CondCode OFCC;
7982     SDValue Value, Overflow;
7983     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
7984     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
7985 
7986     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
7987                        CCVal, Overflow);
7988   }
7989 
7990   // Lower it the same way as we would lower a SELECT_CC node.
7991   ISD::CondCode CC;
7992   SDValue LHS, RHS;
7993   if (CCVal.getOpcode() == ISD::SETCC) {
7994     LHS = CCVal.getOperand(0);
7995     RHS = CCVal.getOperand(1);
7996     CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get();
7997   } else {
7998     LHS = CCVal;
7999     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
8000     CC = ISD::SETNE;
8001   }
8002   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
8003 }
8004 
8005 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
8006                                               SelectionDAG &DAG) const {
8007   // Jump table entries as PC relative offsets. No additional tweaking
8008   // is necessary here. Just get the address of the jump table.
8009   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8010 
8011   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
8012       !Subtarget->isTargetMachO()) {
8013     return getAddrLarge(JT, DAG);
8014   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
8015     return getAddrTiny(JT, DAG);
8016   }
8017   return getAddr(JT, DAG);
8018 }
8019 
8020 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
8021                                           SelectionDAG &DAG) const {
8022   // Jump table entries as PC relative offsets. No additional tweaking
8023   // is necessary here. Just get the address of the jump table.
8024   SDLoc DL(Op);
8025   SDValue JT = Op.getOperand(1);
8026   SDValue Entry = Op.getOperand(2);
8027   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
8028 
8029   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
8030   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
8031 
8032   SDNode *Dest =
8033       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
8034                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
8035   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
8036                      SDValue(Dest, 0));
8037 }
8038 
8039 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
8040                                                  SelectionDAG &DAG) const {
8041   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8042 
8043   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
8044     // Use the GOT for the large code model on iOS.
8045     if (Subtarget->isTargetMachO()) {
8046       return getGOT(CP, DAG);
8047     }
8048     return getAddrLarge(CP, DAG);
8049   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
8050     return getAddrTiny(CP, DAG);
8051   } else {
8052     return getAddr(CP, DAG);
8053   }
8054 }
8055 
8056 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
8057                                                SelectionDAG &DAG) const {
8058   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
8059   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
8060       !Subtarget->isTargetMachO()) {
8061     return getAddrLarge(BA, DAG);
8062   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
8063     return getAddrTiny(BA, DAG);
8064   }
8065   return getAddr(BA, DAG);
8066 }
8067 
8068 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
8069                                                  SelectionDAG &DAG) const {
8070   AArch64FunctionInfo *FuncInfo =
8071       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
8072 
8073   SDLoc DL(Op);
8074   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
8075                                  getPointerTy(DAG.getDataLayout()));
8076   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
8077   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8078   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8079                       MachinePointerInfo(SV));
8080 }
8081 
8082 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
8083                                                   SelectionDAG &DAG) const {
8084   AArch64FunctionInfo *FuncInfo =
8085       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
8086 
8087   SDLoc DL(Op);
8088   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
8089                                      ? FuncInfo->getVarArgsGPRIndex()
8090                                      : FuncInfo->getVarArgsStackIndex(),
8091                                  getPointerTy(DAG.getDataLayout()));
8092   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8093   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8094                       MachinePointerInfo(SV));
8095 }
8096 
8097 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
8098                                                   SelectionDAG &DAG) const {
8099   // The layout of the va_list struct is specified in the AArch64 Procedure Call
8100   // Standard, section B.3.
8101   MachineFunction &MF = DAG.getMachineFunction();
8102   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
8103   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
8104   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
8105   auto PtrVT = getPointerTy(DAG.getDataLayout());
8106   SDLoc DL(Op);
8107 
8108   SDValue Chain = Op.getOperand(0);
8109   SDValue VAList = Op.getOperand(1);
8110   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8111   SmallVector<SDValue, 4> MemOps;
8112 
8113   // void *__stack at offset 0
8114   unsigned Offset = 0;
8115   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
8116   Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
8117   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
8118                                 MachinePointerInfo(SV), Align(PtrSize)));
8119 
8120   // void *__gr_top at offset 8 (4 on ILP32)
8121   Offset += PtrSize;
8122   int GPRSize = FuncInfo->getVarArgsGPRSize();
8123   if (GPRSize > 0) {
8124     SDValue GRTop, GRTopAddr;
8125 
8126     GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8127                             DAG.getConstant(Offset, DL, PtrVT));
8128 
8129     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
8130     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
8131                         DAG.getConstant(GPRSize, DL, PtrVT));
8132     GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
8133 
8134     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
8135                                   MachinePointerInfo(SV, Offset),
8136                                   Align(PtrSize)));
8137   }
8138 
8139   // void *__vr_top at offset 16 (8 on ILP32)
8140   Offset += PtrSize;
8141   int FPRSize = FuncInfo->getVarArgsFPRSize();
8142   if (FPRSize > 0) {
8143     SDValue VRTop, VRTopAddr;
8144     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8145                             DAG.getConstant(Offset, DL, PtrVT));
8146 
8147     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
8148     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
8149                         DAG.getConstant(FPRSize, DL, PtrVT));
8150     VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
8151 
8152     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
8153                                   MachinePointerInfo(SV, Offset),
8154                                   Align(PtrSize)));
8155   }
8156 
8157   // int __gr_offs at offset 24 (12 on ILP32)
8158   Offset += PtrSize;
8159   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8160                                    DAG.getConstant(Offset, DL, PtrVT));
8161   MemOps.push_back(
8162       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
8163                    GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
8164 
8165   // int __vr_offs at offset 28 (16 on ILP32)
8166   Offset += 4;
8167   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8168                                    DAG.getConstant(Offset, DL, PtrVT));
8169   MemOps.push_back(
8170       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
8171                    VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
8172 
8173   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
8174 }
8175 
8176 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
8177                                             SelectionDAG &DAG) const {
8178   MachineFunction &MF = DAG.getMachineFunction();
8179 
8180   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
8181     return LowerWin64_VASTART(Op, DAG);
8182   else if (Subtarget->isTargetDarwin())
8183     return LowerDarwin_VASTART(Op, DAG);
8184   else
8185     return LowerAAPCS_VASTART(Op, DAG);
8186 }
8187 
8188 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
8189                                            SelectionDAG &DAG) const {
8190   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
8191   // pointer.
8192   SDLoc DL(Op);
8193   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
8194   unsigned VaListSize =
8195       (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
8196           ? PtrSize
8197           : Subtarget->isTargetILP32() ? 20 : 32;
8198   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8199   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8200 
8201   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
8202                        DAG.getConstant(VaListSize, DL, MVT::i32),
8203                        Align(PtrSize), false, false, false,
8204                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
8205 }
8206 
8207 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8208   assert(Subtarget->isTargetDarwin() &&
8209          "automatic va_arg instruction only works on Darwin");
8210 
8211   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8212   EVT VT = Op.getValueType();
8213   SDLoc DL(Op);
8214   SDValue Chain = Op.getOperand(0);
8215   SDValue Addr = Op.getOperand(1);
8216   MaybeAlign Align(Op.getConstantOperandVal(3));
8217   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
8218   auto PtrVT = getPointerTy(DAG.getDataLayout());
8219   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
8220   SDValue VAList =
8221       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
8222   Chain = VAList.getValue(1);
8223   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
8224 
8225   if (VT.isScalableVector())
8226     report_fatal_error("Passing SVE types to variadic functions is "
8227                        "currently not supported");
8228 
8229   if (Align && *Align > MinSlotSize) {
8230     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8231                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
8232     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
8233                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
8234   }
8235 
8236   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8237   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
8238 
8239   // Scalar integer and FP values smaller than 64 bits are implicitly extended
8240   // up to 64 bits.  At the very least, we have to increase the striding of the
8241   // vaargs list to match this, and for FP values we need to introduce
8242   // FP_ROUND nodes as well.
8243   if (VT.isInteger() && !VT.isVector())
8244     ArgSize = std::max(ArgSize, MinSlotSize);
8245   bool NeedFPTrunc = false;
8246   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
8247     ArgSize = 8;
8248     NeedFPTrunc = true;
8249   }
8250 
8251   // Increment the pointer, VAList, to the next vaarg
8252   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8253                                DAG.getConstant(ArgSize, DL, PtrVT));
8254   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
8255 
8256   // Store the incremented VAList to the legalized pointer
8257   SDValue APStore =
8258       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
8259 
8260   // Load the actual argument out of the pointer VAList
8261   if (NeedFPTrunc) {
8262     // Load the value as an f64.
8263     SDValue WideFP =
8264         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
8265     // Round the value down to an f32.
8266     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
8267                                    DAG.getIntPtrConstant(1, DL));
8268     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
8269     // Merge the rounded value with the chain output of the load.
8270     return DAG.getMergeValues(Ops, DL);
8271   }
8272 
8273   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
8274 }
8275 
8276 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
8277                                               SelectionDAG &DAG) const {
8278   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8279   MFI.setFrameAddressIsTaken(true);
8280 
8281   EVT VT = Op.getValueType();
8282   SDLoc DL(Op);
8283   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8284   SDValue FrameAddr =
8285       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
8286   while (Depth--)
8287     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
8288                             MachinePointerInfo());
8289 
8290   if (Subtarget->isTargetILP32())
8291     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
8292                             DAG.getValueType(VT));
8293 
8294   return FrameAddr;
8295 }
8296 
8297 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
8298                                               SelectionDAG &DAG) const {
8299   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8300 
8301   EVT VT = getPointerTy(DAG.getDataLayout());
8302   SDLoc DL(Op);
8303   int FI = MFI.CreateFixedObject(4, 0, false);
8304   return DAG.getFrameIndex(FI, VT);
8305 }
8306 
8307 #define GET_REGISTER_MATCHER
8308 #include "AArch64GenAsmMatcher.inc"
8309 
8310 // FIXME? Maybe this could be a TableGen attribute on some registers and
8311 // this table could be generated automatically from RegInfo.
8312 Register AArch64TargetLowering::
8313 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
8314   Register Reg = MatchRegisterName(RegName);
8315   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
8316     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
8317     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
8318     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
8319       Reg = 0;
8320   }
8321   if (Reg)
8322     return Reg;
8323   report_fatal_error(Twine("Invalid register name \""
8324                               + StringRef(RegName)  + "\"."));
8325 }
8326 
8327 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
8328                                                      SelectionDAG &DAG) const {
8329   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
8330 
8331   EVT VT = Op.getValueType();
8332   SDLoc DL(Op);
8333 
8334   SDValue FrameAddr =
8335       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
8336   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
8337 
8338   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
8339 }
8340 
8341 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
8342                                                SelectionDAG &DAG) const {
8343   MachineFunction &MF = DAG.getMachineFunction();
8344   MachineFrameInfo &MFI = MF.getFrameInfo();
8345   MFI.setReturnAddressIsTaken(true);
8346 
8347   EVT VT = Op.getValueType();
8348   SDLoc DL(Op);
8349   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8350   SDValue ReturnAddress;
8351   if (Depth) {
8352     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8353     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
8354     ReturnAddress = DAG.getLoad(
8355         VT, DL, DAG.getEntryNode(),
8356         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
8357   } else {
8358     // Return LR, which contains the return address. Mark it an implicit
8359     // live-in.
8360     Register Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
8361     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
8362   }
8363 
8364   // The XPACLRI instruction assembles to a hint-space instruction before
8365   // Armv8.3-A therefore this instruction can be safely used for any pre
8366   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
8367   // that instead.
8368   SDNode *St;
8369   if (Subtarget->hasPAuth()) {
8370     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
8371   } else {
8372     // XPACLRI operates on LR therefore we must move the operand accordingly.
8373     SDValue Chain =
8374         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
8375     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
8376   }
8377   return SDValue(St, 0);
8378 }
8379 
8380 /// LowerShiftParts - Lower SHL_PARTS/SRA_PARTS/SRL_PARTS, which returns two
8381 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
8382 SDValue AArch64TargetLowering::LowerShiftParts(SDValue Op,
8383                                                SelectionDAG &DAG) const {
8384   SDValue Lo, Hi;
8385   expandShiftParts(Op.getNode(), Lo, Hi, DAG);
8386   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
8387 }
8388 
8389 bool AArch64TargetLowering::isOffsetFoldingLegal(
8390     const GlobalAddressSDNode *GA) const {
8391   // Offsets are folded in the DAG combine rather than here so that we can
8392   // intelligently choose an offset based on the uses.
8393   return false;
8394 }
8395 
8396 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
8397                                          bool OptForSize) const {
8398   bool IsLegal = false;
8399   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
8400   // 16-bit case when target has full fp16 support.
8401   // FIXME: We should be able to handle f128 as well with a clever lowering.
8402   const APInt ImmInt = Imm.bitcastToAPInt();
8403   if (VT == MVT::f64)
8404     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
8405   else if (VT == MVT::f32)
8406     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
8407   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
8408     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
8409   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
8410   //       generate that fmov.
8411 
8412   // If we can not materialize in immediate field for fmov, check if the
8413   // value can be encoded as the immediate operand of a logical instruction.
8414   // The immediate value will be created with either MOVZ, MOVN, or ORR.
8415   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
8416     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
8417     // however the mov+fmov sequence is always better because of the reduced
8418     // cache pressure. The timings are still the same if you consider
8419     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
8420     // movw+movk is fused). So we limit up to 2 instrdduction at most.
8421     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
8422     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
8423 			      Insn);
8424     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
8425     IsLegal = Insn.size() <= Limit;
8426   }
8427 
8428   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
8429                     << " imm value: "; Imm.dump(););
8430   return IsLegal;
8431 }
8432 
8433 //===----------------------------------------------------------------------===//
8434 //                          AArch64 Optimization Hooks
8435 //===----------------------------------------------------------------------===//
8436 
8437 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
8438                            SDValue Operand, SelectionDAG &DAG,
8439                            int &ExtraSteps) {
8440   EVT VT = Operand.getValueType();
8441   if ((ST->hasNEON() &&
8442        (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
8443         VT == MVT::f32 || VT == MVT::v1f32 || VT == MVT::v2f32 ||
8444         VT == MVT::v4f32)) ||
8445       (ST->hasSVE() &&
8446        (VT == MVT::nxv8f16 || VT == MVT::nxv4f32 || VT == MVT::nxv2f64))) {
8447     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
8448       // For the reciprocal estimates, convergence is quadratic, so the number
8449       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
8450       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
8451       // the result for float (23 mantissa bits) is 2 and for double (52
8452       // mantissa bits) is 3.
8453       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
8454 
8455     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
8456   }
8457 
8458   return SDValue();
8459 }
8460 
8461 SDValue
8462 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
8463                                         const DenormalMode &Mode) const {
8464   SDLoc DL(Op);
8465   EVT VT = Op.getValueType();
8466   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8467   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
8468   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
8469 }
8470 
8471 SDValue
8472 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
8473                                                    SelectionDAG &DAG) const {
8474   return Op;
8475 }
8476 
8477 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
8478                                                SelectionDAG &DAG, int Enabled,
8479                                                int &ExtraSteps,
8480                                                bool &UseOneConst,
8481                                                bool Reciprocal) const {
8482   if (Enabled == ReciprocalEstimate::Enabled ||
8483       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
8484     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
8485                                        DAG, ExtraSteps)) {
8486       SDLoc DL(Operand);
8487       EVT VT = Operand.getValueType();
8488 
8489       SDNodeFlags Flags;
8490       Flags.setAllowReassociation(true);
8491 
8492       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
8493       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
8494       for (int i = ExtraSteps; i > 0; --i) {
8495         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
8496                                    Flags);
8497         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
8498         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
8499       }
8500       if (!Reciprocal)
8501         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
8502 
8503       ExtraSteps = 0;
8504       return Estimate;
8505     }
8506 
8507   return SDValue();
8508 }
8509 
8510 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
8511                                                 SelectionDAG &DAG, int Enabled,
8512                                                 int &ExtraSteps) const {
8513   if (Enabled == ReciprocalEstimate::Enabled)
8514     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
8515                                        DAG, ExtraSteps)) {
8516       SDLoc DL(Operand);
8517       EVT VT = Operand.getValueType();
8518 
8519       SDNodeFlags Flags;
8520       Flags.setAllowReassociation(true);
8521 
8522       // Newton reciprocal iteration: E * (2 - X * E)
8523       // AArch64 reciprocal iteration instruction: (2 - M * N)
8524       for (int i = ExtraSteps; i > 0; --i) {
8525         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
8526                                    Estimate, Flags);
8527         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
8528       }
8529 
8530       ExtraSteps = 0;
8531       return Estimate;
8532     }
8533 
8534   return SDValue();
8535 }
8536 
8537 //===----------------------------------------------------------------------===//
8538 //                          AArch64 Inline Assembly Support
8539 //===----------------------------------------------------------------------===//
8540 
8541 // Table of Constraints
8542 // TODO: This is the current set of constraints supported by ARM for the
8543 // compiler, not all of them may make sense.
8544 //
8545 // r - A general register
8546 // w - An FP/SIMD register of some size in the range v0-v31
8547 // x - An FP/SIMD register of some size in the range v0-v15
8548 // I - Constant that can be used with an ADD instruction
8549 // J - Constant that can be used with a SUB instruction
8550 // K - Constant that can be used with a 32-bit logical instruction
8551 // L - Constant that can be used with a 64-bit logical instruction
8552 // M - Constant that can be used as a 32-bit MOV immediate
8553 // N - Constant that can be used as a 64-bit MOV immediate
8554 // Q - A memory reference with base register and no offset
8555 // S - A symbolic address
8556 // Y - Floating point constant zero
8557 // Z - Integer constant zero
8558 //
8559 //   Note that general register operands will be output using their 64-bit x
8560 // register name, whatever the size of the variable, unless the asm operand
8561 // is prefixed by the %w modifier. Floating-point and SIMD register operands
8562 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
8563 // %q modifier.
8564 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
8565   // At this point, we have to lower this constraint to something else, so we
8566   // lower it to an "r" or "w". However, by doing this we will force the result
8567   // to be in register, while the X constraint is much more permissive.
8568   //
8569   // Although we are correct (we are free to emit anything, without
8570   // constraints), we might break use cases that would expect us to be more
8571   // efficient and emit something else.
8572   if (!Subtarget->hasFPARMv8())
8573     return "r";
8574 
8575   if (ConstraintVT.isFloatingPoint())
8576     return "w";
8577 
8578   if (ConstraintVT.isVector() &&
8579      (ConstraintVT.getSizeInBits() == 64 ||
8580       ConstraintVT.getSizeInBits() == 128))
8581     return "w";
8582 
8583   return "r";
8584 }
8585 
8586 enum PredicateConstraint {
8587   Upl,
8588   Upa,
8589   Invalid
8590 };
8591 
8592 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
8593   PredicateConstraint P = PredicateConstraint::Invalid;
8594   if (Constraint == "Upa")
8595     P = PredicateConstraint::Upa;
8596   if (Constraint == "Upl")
8597     P = PredicateConstraint::Upl;
8598   return P;
8599 }
8600 
8601 /// getConstraintType - Given a constraint letter, return the type of
8602 /// constraint it is for this target.
8603 AArch64TargetLowering::ConstraintType
8604 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
8605   if (Constraint.size() == 1) {
8606     switch (Constraint[0]) {
8607     default:
8608       break;
8609     case 'x':
8610     case 'w':
8611     case 'y':
8612       return C_RegisterClass;
8613     // An address with a single base register. Due to the way we
8614     // currently handle addresses it is the same as 'r'.
8615     case 'Q':
8616       return C_Memory;
8617     case 'I':
8618     case 'J':
8619     case 'K':
8620     case 'L':
8621     case 'M':
8622     case 'N':
8623     case 'Y':
8624     case 'Z':
8625       return C_Immediate;
8626     case 'z':
8627     case 'S': // A symbolic address
8628       return C_Other;
8629     }
8630   } else if (parsePredicateConstraint(Constraint) !=
8631              PredicateConstraint::Invalid)
8632       return C_RegisterClass;
8633   return TargetLowering::getConstraintType(Constraint);
8634 }
8635 
8636 /// Examine constraint type and operand type and determine a weight value.
8637 /// This object must already have been set up with the operand type
8638 /// and the current alternative constraint selected.
8639 TargetLowering::ConstraintWeight
8640 AArch64TargetLowering::getSingleConstraintMatchWeight(
8641     AsmOperandInfo &info, const char *constraint) const {
8642   ConstraintWeight weight = CW_Invalid;
8643   Value *CallOperandVal = info.CallOperandVal;
8644   // If we don't have a value, we can't do a match,
8645   // but allow it at the lowest weight.
8646   if (!CallOperandVal)
8647     return CW_Default;
8648   Type *type = CallOperandVal->getType();
8649   // Look at the constraint type.
8650   switch (*constraint) {
8651   default:
8652     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8653     break;
8654   case 'x':
8655   case 'w':
8656   case 'y':
8657     if (type->isFloatingPointTy() || type->isVectorTy())
8658       weight = CW_Register;
8659     break;
8660   case 'z':
8661     weight = CW_Constant;
8662     break;
8663   case 'U':
8664     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
8665       weight = CW_Register;
8666     break;
8667   }
8668   return weight;
8669 }
8670 
8671 std::pair<unsigned, const TargetRegisterClass *>
8672 AArch64TargetLowering::getRegForInlineAsmConstraint(
8673     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
8674   if (Constraint.size() == 1) {
8675     switch (Constraint[0]) {
8676     case 'r':
8677       if (VT.isScalableVector())
8678         return std::make_pair(0U, nullptr);
8679       if (Subtarget->hasLS64() && VT.getSizeInBits() == 512)
8680         return std::make_pair(0U, &AArch64::GPR64x8ClassRegClass);
8681       if (VT.getFixedSizeInBits() == 64)
8682         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
8683       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
8684     case 'w': {
8685       if (!Subtarget->hasFPARMv8())
8686         break;
8687       if (VT.isScalableVector()) {
8688         if (VT.getVectorElementType() != MVT::i1)
8689           return std::make_pair(0U, &AArch64::ZPRRegClass);
8690         return std::make_pair(0U, nullptr);
8691       }
8692       uint64_t VTSize = VT.getFixedSizeInBits();
8693       if (VTSize == 16)
8694         return std::make_pair(0U, &AArch64::FPR16RegClass);
8695       if (VTSize == 32)
8696         return std::make_pair(0U, &AArch64::FPR32RegClass);
8697       if (VTSize == 64)
8698         return std::make_pair(0U, &AArch64::FPR64RegClass);
8699       if (VTSize == 128)
8700         return std::make_pair(0U, &AArch64::FPR128RegClass);
8701       break;
8702     }
8703     // The instructions that this constraint is designed for can
8704     // only take 128-bit registers so just use that regclass.
8705     case 'x':
8706       if (!Subtarget->hasFPARMv8())
8707         break;
8708       if (VT.isScalableVector())
8709         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
8710       if (VT.getSizeInBits() == 128)
8711         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
8712       break;
8713     case 'y':
8714       if (!Subtarget->hasFPARMv8())
8715         break;
8716       if (VT.isScalableVector())
8717         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
8718       break;
8719     }
8720   } else {
8721     PredicateConstraint PC = parsePredicateConstraint(Constraint);
8722     if (PC != PredicateConstraint::Invalid) {
8723       if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
8724         return std::make_pair(0U, nullptr);
8725       bool restricted = (PC == PredicateConstraint::Upl);
8726       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
8727                         : std::make_pair(0U, &AArch64::PPRRegClass);
8728     }
8729   }
8730   if (StringRef("{cc}").equals_insensitive(Constraint))
8731     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
8732 
8733   // Use the default implementation in TargetLowering to convert the register
8734   // constraint into a member of a register class.
8735   std::pair<unsigned, const TargetRegisterClass *> Res;
8736   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8737 
8738   // Not found as a standard register?
8739   if (!Res.second) {
8740     unsigned Size = Constraint.size();
8741     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
8742         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
8743       int RegNo;
8744       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
8745       if (!Failed && RegNo >= 0 && RegNo <= 31) {
8746         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
8747         // By default we'll emit v0-v31 for this unless there's a modifier where
8748         // we'll emit the correct register as well.
8749         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
8750           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
8751           Res.second = &AArch64::FPR64RegClass;
8752         } else {
8753           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
8754           Res.second = &AArch64::FPR128RegClass;
8755         }
8756       }
8757     }
8758   }
8759 
8760   if (Res.second && !Subtarget->hasFPARMv8() &&
8761       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
8762       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
8763     return std::make_pair(0U, nullptr);
8764 
8765   return Res;
8766 }
8767 
8768 EVT AArch64TargetLowering::getAsmOperandValueType(const DataLayout &DL,
8769                                                   llvm::Type *Ty,
8770                                                   bool AllowUnknown) const {
8771   if (Subtarget->hasLS64() && Ty->isIntegerTy(512))
8772     return EVT(MVT::i64x8);
8773 
8774   return TargetLowering::getAsmOperandValueType(DL, Ty, AllowUnknown);
8775 }
8776 
8777 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8778 /// vector.  If it is invalid, don't add anything to Ops.
8779 void AArch64TargetLowering::LowerAsmOperandForConstraint(
8780     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
8781     SelectionDAG &DAG) const {
8782   SDValue Result;
8783 
8784   // Currently only support length 1 constraints.
8785   if (Constraint.length() != 1)
8786     return;
8787 
8788   char ConstraintLetter = Constraint[0];
8789   switch (ConstraintLetter) {
8790   default:
8791     break;
8792 
8793   // This set of constraints deal with valid constants for various instructions.
8794   // Validate and return a target constant for them if we can.
8795   case 'z': {
8796     // 'z' maps to xzr or wzr so it needs an input of 0.
8797     if (!isNullConstant(Op))
8798       return;
8799 
8800     if (Op.getValueType() == MVT::i64)
8801       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
8802     else
8803       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
8804     break;
8805   }
8806   case 'S': {
8807     // An absolute symbolic address or label reference.
8808     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8809       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
8810                                           GA->getValueType(0));
8811     } else if (const BlockAddressSDNode *BA =
8812                    dyn_cast<BlockAddressSDNode>(Op)) {
8813       Result =
8814           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
8815     } else
8816       return;
8817     break;
8818   }
8819 
8820   case 'I':
8821   case 'J':
8822   case 'K':
8823   case 'L':
8824   case 'M':
8825   case 'N':
8826     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8827     if (!C)
8828       return;
8829 
8830     // Grab the value and do some validation.
8831     uint64_t CVal = C->getZExtValue();
8832     switch (ConstraintLetter) {
8833     // The I constraint applies only to simple ADD or SUB immediate operands:
8834     // i.e. 0 to 4095 with optional shift by 12
8835     // The J constraint applies only to ADD or SUB immediates that would be
8836     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
8837     // instruction [or vice versa], in other words -1 to -4095 with optional
8838     // left shift by 12.
8839     case 'I':
8840       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
8841         break;
8842       return;
8843     case 'J': {
8844       uint64_t NVal = -C->getSExtValue();
8845       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
8846         CVal = C->getSExtValue();
8847         break;
8848       }
8849       return;
8850     }
8851     // The K and L constraints apply *only* to logical immediates, including
8852     // what used to be the MOVI alias for ORR (though the MOVI alias has now
8853     // been removed and MOV should be used). So these constraints have to
8854     // distinguish between bit patterns that are valid 32-bit or 64-bit
8855     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
8856     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
8857     // versa.
8858     case 'K':
8859       if (AArch64_AM::isLogicalImmediate(CVal, 32))
8860         break;
8861       return;
8862     case 'L':
8863       if (AArch64_AM::isLogicalImmediate(CVal, 64))
8864         break;
8865       return;
8866     // The M and N constraints are a superset of K and L respectively, for use
8867     // with the MOV (immediate) alias. As well as the logical immediates they
8868     // also match 32 or 64-bit immediates that can be loaded either using a
8869     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
8870     // (M) or 64-bit 0x1234000000000000 (N) etc.
8871     // As a note some of this code is liberally stolen from the asm parser.
8872     case 'M': {
8873       if (!isUInt<32>(CVal))
8874         return;
8875       if (AArch64_AM::isLogicalImmediate(CVal, 32))
8876         break;
8877       if ((CVal & 0xFFFF) == CVal)
8878         break;
8879       if ((CVal & 0xFFFF0000ULL) == CVal)
8880         break;
8881       uint64_t NCVal = ~(uint32_t)CVal;
8882       if ((NCVal & 0xFFFFULL) == NCVal)
8883         break;
8884       if ((NCVal & 0xFFFF0000ULL) == NCVal)
8885         break;
8886       return;
8887     }
8888     case 'N': {
8889       if (AArch64_AM::isLogicalImmediate(CVal, 64))
8890         break;
8891       if ((CVal & 0xFFFFULL) == CVal)
8892         break;
8893       if ((CVal & 0xFFFF0000ULL) == CVal)
8894         break;
8895       if ((CVal & 0xFFFF00000000ULL) == CVal)
8896         break;
8897       if ((CVal & 0xFFFF000000000000ULL) == CVal)
8898         break;
8899       uint64_t NCVal = ~CVal;
8900       if ((NCVal & 0xFFFFULL) == NCVal)
8901         break;
8902       if ((NCVal & 0xFFFF0000ULL) == NCVal)
8903         break;
8904       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
8905         break;
8906       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
8907         break;
8908       return;
8909     }
8910     default:
8911       return;
8912     }
8913 
8914     // All assembler immediates are 64-bit integers.
8915     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
8916     break;
8917   }
8918 
8919   if (Result.getNode()) {
8920     Ops.push_back(Result);
8921     return;
8922   }
8923 
8924   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8925 }
8926 
8927 //===----------------------------------------------------------------------===//
8928 //                     AArch64 Advanced SIMD Support
8929 //===----------------------------------------------------------------------===//
8930 
8931 /// WidenVector - Given a value in the V64 register class, produce the
8932 /// equivalent value in the V128 register class.
8933 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
8934   EVT VT = V64Reg.getValueType();
8935   unsigned NarrowSize = VT.getVectorNumElements();
8936   MVT EltTy = VT.getVectorElementType().getSimpleVT();
8937   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
8938   SDLoc DL(V64Reg);
8939 
8940   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
8941                      V64Reg, DAG.getConstant(0, DL, MVT::i64));
8942 }
8943 
8944 /// getExtFactor - Determine the adjustment factor for the position when
8945 /// generating an "extract from vector registers" instruction.
8946 static unsigned getExtFactor(SDValue &V) {
8947   EVT EltType = V.getValueType().getVectorElementType();
8948   return EltType.getSizeInBits() / 8;
8949 }
8950 
8951 /// NarrowVector - Given a value in the V128 register class, produce the
8952 /// equivalent value in the V64 register class.
8953 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
8954   EVT VT = V128Reg.getValueType();
8955   unsigned WideSize = VT.getVectorNumElements();
8956   MVT EltTy = VT.getVectorElementType().getSimpleVT();
8957   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
8958   SDLoc DL(V128Reg);
8959 
8960   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
8961 }
8962 
8963 // Gather data to see if the operation can be modelled as a
8964 // shuffle in combination with VEXTs.
8965 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
8966                                                   SelectionDAG &DAG) const {
8967   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8968   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
8969   SDLoc dl(Op);
8970   EVT VT = Op.getValueType();
8971   assert(!VT.isScalableVector() &&
8972          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
8973   unsigned NumElts = VT.getVectorNumElements();
8974 
8975   struct ShuffleSourceInfo {
8976     SDValue Vec;
8977     unsigned MinElt;
8978     unsigned MaxElt;
8979 
8980     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8981     // be compatible with the shuffle we intend to construct. As a result
8982     // ShuffleVec will be some sliding window into the original Vec.
8983     SDValue ShuffleVec;
8984 
8985     // Code should guarantee that element i in Vec starts at element "WindowBase
8986     // + i * WindowScale in ShuffleVec".
8987     int WindowBase;
8988     int WindowScale;
8989 
8990     ShuffleSourceInfo(SDValue Vec)
8991       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
8992           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
8993 
8994     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8995   };
8996 
8997   // First gather all vectors used as an immediate source for this BUILD_VECTOR
8998   // node.
8999   SmallVector<ShuffleSourceInfo, 2> Sources;
9000   for (unsigned i = 0; i < NumElts; ++i) {
9001     SDValue V = Op.getOperand(i);
9002     if (V.isUndef())
9003       continue;
9004     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9005              !isa<ConstantSDNode>(V.getOperand(1)) ||
9006              V.getOperand(0).getValueType().isScalableVector()) {
9007       LLVM_DEBUG(
9008           dbgs() << "Reshuffle failed: "
9009                     "a shuffle can only come from building a vector from "
9010                     "various elements of other fixed-width vectors, provided "
9011                     "their indices are constant\n");
9012       return SDValue();
9013     }
9014 
9015     // Add this element source to the list if it's not already there.
9016     SDValue SourceVec = V.getOperand(0);
9017     auto Source = find(Sources, SourceVec);
9018     if (Source == Sources.end())
9019       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
9020 
9021     // Update the minimum and maximum lane number seen.
9022     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
9023     Source->MinElt = std::min(Source->MinElt, EltNo);
9024     Source->MaxElt = std::max(Source->MaxElt, EltNo);
9025   }
9026 
9027   if (Sources.size() > 2) {
9028     LLVM_DEBUG(
9029         dbgs() << "Reshuffle failed: currently only do something sane when at "
9030                   "most two source vectors are involved\n");
9031     return SDValue();
9032   }
9033 
9034   // Find out the smallest element size among result and two sources, and use
9035   // it as element size to build the shuffle_vector.
9036   EVT SmallestEltTy = VT.getVectorElementType();
9037   for (auto &Source : Sources) {
9038     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
9039     if (SrcEltTy.bitsLT(SmallestEltTy)) {
9040       SmallestEltTy = SrcEltTy;
9041     }
9042   }
9043   unsigned ResMultiplier =
9044       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
9045   uint64_t VTSize = VT.getFixedSizeInBits();
9046   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
9047   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
9048 
9049   // If the source vector is too wide or too narrow, we may nevertheless be able
9050   // to construct a compatible shuffle either by concatenating it with UNDEF or
9051   // extracting a suitable range of elements.
9052   for (auto &Src : Sources) {
9053     EVT SrcVT = Src.ShuffleVec.getValueType();
9054 
9055     TypeSize SrcVTSize = SrcVT.getSizeInBits();
9056     if (SrcVTSize == TypeSize::Fixed(VTSize))
9057       continue;
9058 
9059     // This stage of the search produces a source with the same element type as
9060     // the original, but with a total width matching the BUILD_VECTOR output.
9061     EVT EltVT = SrcVT.getVectorElementType();
9062     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
9063     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
9064 
9065     if (SrcVTSize.getFixedValue() < VTSize) {
9066       assert(2 * SrcVTSize == VTSize);
9067       // We can pad out the smaller vector for free, so if it's part of a
9068       // shuffle...
9069       Src.ShuffleVec =
9070           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
9071                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
9072       continue;
9073     }
9074 
9075     if (SrcVTSize.getFixedValue() != 2 * VTSize) {
9076       LLVM_DEBUG(
9077           dbgs() << "Reshuffle failed: result vector too small to extract\n");
9078       return SDValue();
9079     }
9080 
9081     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
9082       LLVM_DEBUG(
9083           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
9084       return SDValue();
9085     }
9086 
9087     if (Src.MinElt >= NumSrcElts) {
9088       // The extraction can just take the second half
9089       Src.ShuffleVec =
9090           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
9091                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
9092       Src.WindowBase = -NumSrcElts;
9093     } else if (Src.MaxElt < NumSrcElts) {
9094       // The extraction can just take the first half
9095       Src.ShuffleVec =
9096           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
9097                       DAG.getConstant(0, dl, MVT::i64));
9098     } else {
9099       // An actual VEXT is needed
9100       SDValue VEXTSrc1 =
9101           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
9102                       DAG.getConstant(0, dl, MVT::i64));
9103       SDValue VEXTSrc2 =
9104           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
9105                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
9106       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
9107 
9108       if (!SrcVT.is64BitVector()) {
9109         LLVM_DEBUG(
9110           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
9111                     "for SVE vectors.");
9112         return SDValue();
9113       }
9114 
9115       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
9116                                    VEXTSrc2,
9117                                    DAG.getConstant(Imm, dl, MVT::i32));
9118       Src.WindowBase = -Src.MinElt;
9119     }
9120   }
9121 
9122   // Another possible incompatibility occurs from the vector element types. We
9123   // can fix this by bitcasting the source vectors to the same type we intend
9124   // for the shuffle.
9125   for (auto &Src : Sources) {
9126     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
9127     if (SrcEltTy == SmallestEltTy)
9128       continue;
9129     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
9130     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
9131     Src.WindowScale =
9132         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
9133     Src.WindowBase *= Src.WindowScale;
9134   }
9135 
9136   // Final check before we try to actually produce a shuffle.
9137   LLVM_DEBUG(for (auto Src
9138                   : Sources)
9139                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
9140 
9141   // The stars all align, our next step is to produce the mask for the shuffle.
9142   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
9143   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
9144   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
9145     SDValue Entry = Op.getOperand(i);
9146     if (Entry.isUndef())
9147       continue;
9148 
9149     auto Src = find(Sources, Entry.getOperand(0));
9150     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
9151 
9152     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
9153     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
9154     // segment.
9155     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
9156     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
9157                                VT.getScalarSizeInBits());
9158     int LanesDefined = BitsDefined / BitsPerShuffleLane;
9159 
9160     // This source is expected to fill ResMultiplier lanes of the final shuffle,
9161     // starting at the appropriate offset.
9162     int *LaneMask = &Mask[i * ResMultiplier];
9163 
9164     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
9165     ExtractBase += NumElts * (Src - Sources.begin());
9166     for (int j = 0; j < LanesDefined; ++j)
9167       LaneMask[j] = ExtractBase + j;
9168   }
9169 
9170   // Final check before we try to produce nonsense...
9171   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
9172     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
9173     return SDValue();
9174   }
9175 
9176   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
9177   for (unsigned i = 0; i < Sources.size(); ++i)
9178     ShuffleOps[i] = Sources[i].ShuffleVec;
9179 
9180   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
9181                                          ShuffleOps[1], Mask);
9182   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
9183 
9184   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
9185              dbgs() << "Reshuffle, creating node: "; V.dump(););
9186 
9187   return V;
9188 }
9189 
9190 // check if an EXT instruction can handle the shuffle mask when the
9191 // vector sources of the shuffle are the same.
9192 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
9193   unsigned NumElts = VT.getVectorNumElements();
9194 
9195   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
9196   if (M[0] < 0)
9197     return false;
9198 
9199   Imm = M[0];
9200 
9201   // If this is a VEXT shuffle, the immediate value is the index of the first
9202   // element.  The other shuffle indices must be the successive elements after
9203   // the first one.
9204   unsigned ExpectedElt = Imm;
9205   for (unsigned i = 1; i < NumElts; ++i) {
9206     // Increment the expected index.  If it wraps around, just follow it
9207     // back to index zero and keep going.
9208     ++ExpectedElt;
9209     if (ExpectedElt == NumElts)
9210       ExpectedElt = 0;
9211 
9212     if (M[i] < 0)
9213       continue; // ignore UNDEF indices
9214     if (ExpectedElt != static_cast<unsigned>(M[i]))
9215       return false;
9216   }
9217 
9218   return true;
9219 }
9220 
9221 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
9222 /// element width than the vector lane type. If that is the case the function
9223 /// returns true and writes the value of the DUP instruction lane operand into
9224 /// DupLaneOp
9225 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
9226                           unsigned &DupLaneOp) {
9227   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
9228          "Only possible block sizes for wide DUP are: 16, 32, 64");
9229 
9230   if (BlockSize <= VT.getScalarSizeInBits())
9231     return false;
9232   if (BlockSize % VT.getScalarSizeInBits() != 0)
9233     return false;
9234   if (VT.getSizeInBits() % BlockSize != 0)
9235     return false;
9236 
9237   size_t SingleVecNumElements = VT.getVectorNumElements();
9238   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
9239   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
9240 
9241   // We are looking for masks like
9242   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
9243   // might be replaced by 'undefined'. BlockIndices will eventually contain
9244   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
9245   // for the above examples)
9246   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
9247   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
9248     for (size_t I = 0; I < NumEltsPerBlock; I++) {
9249       int Elt = M[BlockIndex * NumEltsPerBlock + I];
9250       if (Elt < 0)
9251         continue;
9252       // For now we don't support shuffles that use the second operand
9253       if ((unsigned)Elt >= SingleVecNumElements)
9254         return false;
9255       if (BlockElts[I] < 0)
9256         BlockElts[I] = Elt;
9257       else if (BlockElts[I] != Elt)
9258         return false;
9259     }
9260 
9261   // We found a candidate block (possibly with some undefs). It must be a
9262   // sequence of consecutive integers starting with a value divisible by
9263   // NumEltsPerBlock with some values possibly replaced by undef-s.
9264 
9265   // Find first non-undef element
9266   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
9267   assert(FirstRealEltIter != BlockElts.end() &&
9268          "Shuffle with all-undefs must have been caught by previous cases, "
9269          "e.g. isSplat()");
9270   if (FirstRealEltIter == BlockElts.end()) {
9271     DupLaneOp = 0;
9272     return true;
9273   }
9274 
9275   // Index of FirstRealElt in BlockElts
9276   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
9277 
9278   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
9279     return false;
9280   // BlockElts[0] must have the following value if it isn't undef:
9281   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
9282 
9283   // Check the first element
9284   if (Elt0 % NumEltsPerBlock != 0)
9285     return false;
9286   // Check that the sequence indeed consists of consecutive integers (modulo
9287   // undefs)
9288   for (size_t I = 0; I < NumEltsPerBlock; I++)
9289     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
9290       return false;
9291 
9292   DupLaneOp = Elt0 / NumEltsPerBlock;
9293   return true;
9294 }
9295 
9296 // check if an EXT instruction can handle the shuffle mask when the
9297 // vector sources of the shuffle are different.
9298 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
9299                       unsigned &Imm) {
9300   // Look for the first non-undef element.
9301   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
9302 
9303   // Benefit form APInt to handle overflow when calculating expected element.
9304   unsigned NumElts = VT.getVectorNumElements();
9305   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
9306   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
9307   // The following shuffle indices must be the successive elements after the
9308   // first real element.
9309   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
9310       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
9311   if (FirstWrongElt != M.end())
9312     return false;
9313 
9314   // The index of an EXT is the first element if it is not UNDEF.
9315   // Watch out for the beginning UNDEFs. The EXT index should be the expected
9316   // value of the first element.  E.g.
9317   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
9318   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
9319   // ExpectedElt is the last mask index plus 1.
9320   Imm = ExpectedElt.getZExtValue();
9321 
9322   // There are two difference cases requiring to reverse input vectors.
9323   // For example, for vector <4 x i32> we have the following cases,
9324   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
9325   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
9326   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
9327   // to reverse two input vectors.
9328   if (Imm < NumElts)
9329     ReverseEXT = true;
9330   else
9331     Imm -= NumElts;
9332 
9333   return true;
9334 }
9335 
9336 /// isREVMask - Check if a vector shuffle corresponds to a REV
9337 /// instruction with the specified blocksize.  (The order of the elements
9338 /// within each block of the vector is reversed.)
9339 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
9340   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
9341          "Only possible block sizes for REV are: 16, 32, 64");
9342 
9343   unsigned EltSz = VT.getScalarSizeInBits();
9344   if (EltSz == 64)
9345     return false;
9346 
9347   unsigned NumElts = VT.getVectorNumElements();
9348   unsigned BlockElts = M[0] + 1;
9349   // If the first shuffle index is UNDEF, be optimistic.
9350   if (M[0] < 0)
9351     BlockElts = BlockSize / EltSz;
9352 
9353   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
9354     return false;
9355 
9356   for (unsigned i = 0; i < NumElts; ++i) {
9357     if (M[i] < 0)
9358       continue; // ignore UNDEF indices
9359     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
9360       return false;
9361   }
9362 
9363   return true;
9364 }
9365 
9366 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9367   unsigned NumElts = VT.getVectorNumElements();
9368   if (NumElts % 2 != 0)
9369     return false;
9370   WhichResult = (M[0] == 0 ? 0 : 1);
9371   unsigned Idx = WhichResult * NumElts / 2;
9372   for (unsigned i = 0; i != NumElts; i += 2) {
9373     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
9374         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
9375       return false;
9376     Idx += 1;
9377   }
9378 
9379   return true;
9380 }
9381 
9382 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9383   unsigned NumElts = VT.getVectorNumElements();
9384   WhichResult = (M[0] == 0 ? 0 : 1);
9385   for (unsigned i = 0; i != NumElts; ++i) {
9386     if (M[i] < 0)
9387       continue; // ignore UNDEF indices
9388     if ((unsigned)M[i] != 2 * i + WhichResult)
9389       return false;
9390   }
9391 
9392   return true;
9393 }
9394 
9395 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9396   unsigned NumElts = VT.getVectorNumElements();
9397   if (NumElts % 2 != 0)
9398     return false;
9399   WhichResult = (M[0] == 0 ? 0 : 1);
9400   for (unsigned i = 0; i < NumElts; i += 2) {
9401     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
9402         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
9403       return false;
9404   }
9405   return true;
9406 }
9407 
9408 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
9409 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9410 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
9411 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9412   unsigned NumElts = VT.getVectorNumElements();
9413   if (NumElts % 2 != 0)
9414     return false;
9415   WhichResult = (M[0] == 0 ? 0 : 1);
9416   unsigned Idx = WhichResult * NumElts / 2;
9417   for (unsigned i = 0; i != NumElts; i += 2) {
9418     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
9419         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
9420       return false;
9421     Idx += 1;
9422   }
9423 
9424   return true;
9425 }
9426 
9427 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
9428 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9429 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
9430 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9431   unsigned Half = VT.getVectorNumElements() / 2;
9432   WhichResult = (M[0] == 0 ? 0 : 1);
9433   for (unsigned j = 0; j != 2; ++j) {
9434     unsigned Idx = WhichResult;
9435     for (unsigned i = 0; i != Half; ++i) {
9436       int MIdx = M[i + j * Half];
9437       if (MIdx >= 0 && (unsigned)MIdx != Idx)
9438         return false;
9439       Idx += 2;
9440     }
9441   }
9442 
9443   return true;
9444 }
9445 
9446 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
9447 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9448 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
9449 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9450   unsigned NumElts = VT.getVectorNumElements();
9451   if (NumElts % 2 != 0)
9452     return false;
9453   WhichResult = (M[0] == 0 ? 0 : 1);
9454   for (unsigned i = 0; i < NumElts; i += 2) {
9455     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
9456         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
9457       return false;
9458   }
9459   return true;
9460 }
9461 
9462 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
9463                       bool &DstIsLeft, int &Anomaly) {
9464   if (M.size() != static_cast<size_t>(NumInputElements))
9465     return false;
9466 
9467   int NumLHSMatch = 0, NumRHSMatch = 0;
9468   int LastLHSMismatch = -1, LastRHSMismatch = -1;
9469 
9470   for (int i = 0; i < NumInputElements; ++i) {
9471     if (M[i] == -1) {
9472       ++NumLHSMatch;
9473       ++NumRHSMatch;
9474       continue;
9475     }
9476 
9477     if (M[i] == i)
9478       ++NumLHSMatch;
9479     else
9480       LastLHSMismatch = i;
9481 
9482     if (M[i] == i + NumInputElements)
9483       ++NumRHSMatch;
9484     else
9485       LastRHSMismatch = i;
9486   }
9487 
9488   if (NumLHSMatch == NumInputElements - 1) {
9489     DstIsLeft = true;
9490     Anomaly = LastLHSMismatch;
9491     return true;
9492   } else if (NumRHSMatch == NumInputElements - 1) {
9493     DstIsLeft = false;
9494     Anomaly = LastRHSMismatch;
9495     return true;
9496   }
9497 
9498   return false;
9499 }
9500 
9501 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
9502   if (VT.getSizeInBits() != 128)
9503     return false;
9504 
9505   unsigned NumElts = VT.getVectorNumElements();
9506 
9507   for (int I = 0, E = NumElts / 2; I != E; I++) {
9508     if (Mask[I] != I)
9509       return false;
9510   }
9511 
9512   int Offset = NumElts / 2;
9513   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
9514     if (Mask[I] != I + SplitLHS * Offset)
9515       return false;
9516   }
9517 
9518   return true;
9519 }
9520 
9521 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
9522   SDLoc DL(Op);
9523   EVT VT = Op.getValueType();
9524   SDValue V0 = Op.getOperand(0);
9525   SDValue V1 = Op.getOperand(1);
9526   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
9527 
9528   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
9529       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
9530     return SDValue();
9531 
9532   bool SplitV0 = V0.getValueSizeInBits() == 128;
9533 
9534   if (!isConcatMask(Mask, VT, SplitV0))
9535     return SDValue();
9536 
9537   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
9538   if (SplitV0) {
9539     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
9540                      DAG.getConstant(0, DL, MVT::i64));
9541   }
9542   if (V1.getValueSizeInBits() == 128) {
9543     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
9544                      DAG.getConstant(0, DL, MVT::i64));
9545   }
9546   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
9547 }
9548 
9549 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9550 /// the specified operations to build the shuffle.
9551 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9552                                       SDValue RHS, SelectionDAG &DAG,
9553                                       const SDLoc &dl) {
9554   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9555   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
9556   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
9557 
9558   enum {
9559     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9560     OP_VREV,
9561     OP_VDUP0,
9562     OP_VDUP1,
9563     OP_VDUP2,
9564     OP_VDUP3,
9565     OP_VEXT1,
9566     OP_VEXT2,
9567     OP_VEXT3,
9568     OP_VUZPL, // VUZP, left result
9569     OP_VUZPR, // VUZP, right result
9570     OP_VZIPL, // VZIP, left result
9571     OP_VZIPR, // VZIP, right result
9572     OP_VTRNL, // VTRN, left result
9573     OP_VTRNR  // VTRN, right result
9574   };
9575 
9576   if (OpNum == OP_COPY) {
9577     if (LHSID == (1 * 9 + 2) * 9 + 3)
9578       return LHS;
9579     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
9580     return RHS;
9581   }
9582 
9583   SDValue OpLHS, OpRHS;
9584   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9585   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9586   EVT VT = OpLHS.getValueType();
9587 
9588   switch (OpNum) {
9589   default:
9590     llvm_unreachable("Unknown shuffle opcode!");
9591   case OP_VREV:
9592     // VREV divides the vector in half and swaps within the half.
9593     if (VT.getVectorElementType() == MVT::i32 ||
9594         VT.getVectorElementType() == MVT::f32)
9595       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
9596     // vrev <4 x i16> -> REV32
9597     if (VT.getVectorElementType() == MVT::i16 ||
9598         VT.getVectorElementType() == MVT::f16 ||
9599         VT.getVectorElementType() == MVT::bf16)
9600       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
9601     // vrev <4 x i8> -> REV16
9602     assert(VT.getVectorElementType() == MVT::i8);
9603     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
9604   case OP_VDUP0:
9605   case OP_VDUP1:
9606   case OP_VDUP2:
9607   case OP_VDUP3: {
9608     EVT EltTy = VT.getVectorElementType();
9609     unsigned Opcode;
9610     if (EltTy == MVT::i8)
9611       Opcode = AArch64ISD::DUPLANE8;
9612     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
9613       Opcode = AArch64ISD::DUPLANE16;
9614     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
9615       Opcode = AArch64ISD::DUPLANE32;
9616     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
9617       Opcode = AArch64ISD::DUPLANE64;
9618     else
9619       llvm_unreachable("Invalid vector element type?");
9620 
9621     if (VT.getSizeInBits() == 64)
9622       OpLHS = WidenVector(OpLHS, DAG);
9623     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
9624     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
9625   }
9626   case OP_VEXT1:
9627   case OP_VEXT2:
9628   case OP_VEXT3: {
9629     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
9630     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
9631                        DAG.getConstant(Imm, dl, MVT::i32));
9632   }
9633   case OP_VUZPL:
9634     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
9635                        OpRHS);
9636   case OP_VUZPR:
9637     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
9638                        OpRHS);
9639   case OP_VZIPL:
9640     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
9641                        OpRHS);
9642   case OP_VZIPR:
9643     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
9644                        OpRHS);
9645   case OP_VTRNL:
9646     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
9647                        OpRHS);
9648   case OP_VTRNR:
9649     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
9650                        OpRHS);
9651   }
9652 }
9653 
9654 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
9655                            SelectionDAG &DAG) {
9656   // Check to see if we can use the TBL instruction.
9657   SDValue V1 = Op.getOperand(0);
9658   SDValue V2 = Op.getOperand(1);
9659   SDLoc DL(Op);
9660 
9661   EVT EltVT = Op.getValueType().getVectorElementType();
9662   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
9663 
9664   SmallVector<SDValue, 8> TBLMask;
9665   for (int Val : ShuffleMask) {
9666     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
9667       unsigned Offset = Byte + Val * BytesPerElt;
9668       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
9669     }
9670   }
9671 
9672   MVT IndexVT = MVT::v8i8;
9673   unsigned IndexLen = 8;
9674   if (Op.getValueSizeInBits() == 128) {
9675     IndexVT = MVT::v16i8;
9676     IndexLen = 16;
9677   }
9678 
9679   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
9680   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
9681 
9682   SDValue Shuffle;
9683   if (V2.getNode()->isUndef()) {
9684     if (IndexLen == 8)
9685       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
9686     Shuffle = DAG.getNode(
9687         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9688         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
9689         DAG.getBuildVector(IndexVT, DL,
9690                            makeArrayRef(TBLMask.data(), IndexLen)));
9691   } else {
9692     if (IndexLen == 8) {
9693       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
9694       Shuffle = DAG.getNode(
9695           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9696           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
9697           DAG.getBuildVector(IndexVT, DL,
9698                              makeArrayRef(TBLMask.data(), IndexLen)));
9699     } else {
9700       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
9701       // cannot currently represent the register constraints on the input
9702       // table registers.
9703       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
9704       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
9705       //                   IndexLen));
9706       Shuffle = DAG.getNode(
9707           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9708           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
9709           V2Cst, DAG.getBuildVector(IndexVT, DL,
9710                                     makeArrayRef(TBLMask.data(), IndexLen)));
9711     }
9712   }
9713   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
9714 }
9715 
9716 static unsigned getDUPLANEOp(EVT EltType) {
9717   if (EltType == MVT::i8)
9718     return AArch64ISD::DUPLANE8;
9719   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
9720     return AArch64ISD::DUPLANE16;
9721   if (EltType == MVT::i32 || EltType == MVT::f32)
9722     return AArch64ISD::DUPLANE32;
9723   if (EltType == MVT::i64 || EltType == MVT::f64)
9724     return AArch64ISD::DUPLANE64;
9725 
9726   llvm_unreachable("Invalid vector element type?");
9727 }
9728 
9729 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
9730                             unsigned Opcode, SelectionDAG &DAG) {
9731   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
9732   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
9733     // Match: dup (bitcast (extract_subv X, C)), LaneC
9734     if (BitCast.getOpcode() != ISD::BITCAST ||
9735         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
9736       return false;
9737 
9738     // The extract index must align in the destination type. That may not
9739     // happen if the bitcast is from narrow to wide type.
9740     SDValue Extract = BitCast.getOperand(0);
9741     unsigned ExtIdx = Extract.getConstantOperandVal(1);
9742     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
9743     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
9744     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
9745     if (ExtIdxInBits % CastedEltBitWidth != 0)
9746       return false;
9747 
9748     // Can't handle cases where vector size is not 128-bit
9749     if (!Extract.getOperand(0).getValueType().is128BitVector())
9750       return false;
9751 
9752     // Update the lane value by offsetting with the scaled extract index.
9753     LaneC += ExtIdxInBits / CastedEltBitWidth;
9754 
9755     // Determine the casted vector type of the wide vector input.
9756     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
9757     // Examples:
9758     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
9759     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
9760     unsigned SrcVecNumElts =
9761         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
9762     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
9763                               SrcVecNumElts);
9764     return true;
9765   };
9766   MVT CastVT;
9767   if (getScaledOffsetDup(V, Lane, CastVT)) {
9768     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
9769   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9770              V.getOperand(0).getValueType().is128BitVector()) {
9771     // The lane is incremented by the index of the extract.
9772     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
9773     Lane += V.getConstantOperandVal(1);
9774     V = V.getOperand(0);
9775   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
9776     // The lane is decremented if we are splatting from the 2nd operand.
9777     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
9778     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
9779     Lane -= Idx * VT.getVectorNumElements() / 2;
9780     V = WidenVector(V.getOperand(Idx), DAG);
9781   } else if (VT.getSizeInBits() == 64) {
9782     // Widen the operand to 128-bit register with undef.
9783     V = WidenVector(V, DAG);
9784   }
9785   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
9786 }
9787 
9788 // Return true if we can get a new shuffle mask by checking the parameter mask
9789 // array to test whether every two adjacent mask values are continuous and
9790 // starting from an even number.
9791 static bool isWideTypeMask(ArrayRef<int> M, EVT VT,
9792                            SmallVectorImpl<int> &NewMask) {
9793   unsigned NumElts = VT.getVectorNumElements();
9794   if (NumElts % 2 != 0)
9795     return false;
9796 
9797   NewMask.clear();
9798   for (unsigned i = 0; i < NumElts; i += 2) {
9799     int M0 = M[i];
9800     int M1 = M[i + 1];
9801 
9802     // If both elements are undef, new mask is undef too.
9803     if (M0 == -1 && M1 == -1) {
9804       NewMask.push_back(-1);
9805       continue;
9806     }
9807 
9808     if (M0 == -1 && M1 != -1 && (M1 % 2) == 1) {
9809       NewMask.push_back(M1 / 2);
9810       continue;
9811     }
9812 
9813     if (M0 != -1 && (M0 % 2) == 0 && ((M0 + 1) == M1 || M1 == -1)) {
9814       NewMask.push_back(M0 / 2);
9815       continue;
9816     }
9817 
9818     NewMask.clear();
9819     return false;
9820   }
9821 
9822   assert(NewMask.size() == NumElts / 2 && "Incorrect size for mask!");
9823   return true;
9824 }
9825 
9826 // Try to widen element type to get a new mask value for a better permutation
9827 // sequence, so that we can use NEON shuffle instructions, such as zip1/2,
9828 // UZP1/2, TRN1/2, REV, INS, etc.
9829 // For example:
9830 //  shufflevector <4 x i32> %a, <4 x i32> %b,
9831 //                <4 x i32> <i32 6, i32 7, i32 2, i32 3>
9832 // is equivalent to:
9833 //  shufflevector <2 x i64> %a, <2 x i64> %b, <2 x i32> <i32 3, i32 1>
9834 // Finally, we can get:
9835 //  mov     v0.d[0], v1.d[1]
9836 static SDValue tryWidenMaskForShuffle(SDValue Op, SelectionDAG &DAG) {
9837   SDLoc DL(Op);
9838   EVT VT = Op.getValueType();
9839   EVT ScalarVT = VT.getVectorElementType();
9840   unsigned ElementSize = ScalarVT.getFixedSizeInBits();
9841   SDValue V0 = Op.getOperand(0);
9842   SDValue V1 = Op.getOperand(1);
9843   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
9844 
9845   // If combining adjacent elements, like two i16's -> i32, two i32's -> i64 ...
9846   // We need to make sure the wider element type is legal. Thus, ElementSize
9847   // should be not larger than 32 bits, and i1 type should also be excluded.
9848   if (ElementSize > 32 || ElementSize == 1)
9849     return SDValue();
9850 
9851   SmallVector<int, 8> NewMask;
9852   if (isWideTypeMask(Mask, VT, NewMask)) {
9853     MVT NewEltVT = VT.isFloatingPoint()
9854                        ? MVT::getFloatingPointVT(ElementSize * 2)
9855                        : MVT::getIntegerVT(ElementSize * 2);
9856     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9857     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9858       V0 = DAG.getBitcast(NewVT, V0);
9859       V1 = DAG.getBitcast(NewVT, V1);
9860       return DAG.getBitcast(VT,
9861                             DAG.getVectorShuffle(NewVT, DL, V0, V1, NewMask));
9862     }
9863   }
9864 
9865   return SDValue();
9866 }
9867 
9868 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9869                                                    SelectionDAG &DAG) const {
9870   SDLoc dl(Op);
9871   EVT VT = Op.getValueType();
9872 
9873   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
9874 
9875   if (useSVEForFixedLengthVectorVT(VT))
9876     return LowerFixedLengthVECTOR_SHUFFLEToSVE(Op, DAG);
9877 
9878   // Convert shuffles that are directly supported on NEON to target-specific
9879   // DAG nodes, instead of keeping them as shuffles and matching them again
9880   // during code selection.  This is more efficient and avoids the possibility
9881   // of inconsistencies between legalization and selection.
9882   ArrayRef<int> ShuffleMask = SVN->getMask();
9883 
9884   SDValue V1 = Op.getOperand(0);
9885   SDValue V2 = Op.getOperand(1);
9886 
9887   assert(V1.getValueType() == VT && "Unexpected VECTOR_SHUFFLE type!");
9888   assert(ShuffleMask.size() == VT.getVectorNumElements() &&
9889          "Unexpected VECTOR_SHUFFLE mask size!");
9890 
9891   if (SVN->isSplat()) {
9892     int Lane = SVN->getSplatIndex();
9893     // If this is undef splat, generate it via "just" vdup, if possible.
9894     if (Lane == -1)
9895       Lane = 0;
9896 
9897     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
9898       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
9899                          V1.getOperand(0));
9900     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
9901     // constant. If so, we can just reference the lane's definition directly.
9902     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
9903         !isa<ConstantSDNode>(V1.getOperand(Lane)))
9904       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
9905 
9906     // Otherwise, duplicate from the lane of the input vector.
9907     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
9908     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
9909   }
9910 
9911   // Check if the mask matches a DUP for a wider element
9912   for (unsigned LaneSize : {64U, 32U, 16U}) {
9913     unsigned Lane = 0;
9914     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
9915       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
9916                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
9917                                                         : AArch64ISD::DUPLANE16;
9918       // Cast V1 to an integer vector with required lane size
9919       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
9920       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
9921       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
9922       V1 = DAG.getBitcast(NewVecTy, V1);
9923       // Constuct the DUP instruction
9924       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
9925       // Cast back to the original type
9926       return DAG.getBitcast(VT, V1);
9927     }
9928   }
9929 
9930   if (isREVMask(ShuffleMask, VT, 64))
9931     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
9932   if (isREVMask(ShuffleMask, VT, 32))
9933     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
9934   if (isREVMask(ShuffleMask, VT, 16))
9935     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
9936 
9937   if (((VT.getVectorNumElements() == 8 && VT.getScalarSizeInBits() == 16) ||
9938        (VT.getVectorNumElements() == 16 && VT.getScalarSizeInBits() == 8)) &&
9939       ShuffleVectorInst::isReverseMask(ShuffleMask)) {
9940     SDValue Rev = DAG.getNode(AArch64ISD::REV64, dl, VT, V1);
9941     return DAG.getNode(AArch64ISD::EXT, dl, VT, Rev, Rev,
9942                        DAG.getConstant(8, dl, MVT::i32));
9943   }
9944 
9945   bool ReverseEXT = false;
9946   unsigned Imm;
9947   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
9948     if (ReverseEXT)
9949       std::swap(V1, V2);
9950     Imm *= getExtFactor(V1);
9951     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
9952                        DAG.getConstant(Imm, dl, MVT::i32));
9953   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
9954     Imm *= getExtFactor(V1);
9955     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
9956                        DAG.getConstant(Imm, dl, MVT::i32));
9957   }
9958 
9959   unsigned WhichResult;
9960   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
9961     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
9962     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9963   }
9964   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
9965     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
9966     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9967   }
9968   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
9969     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
9970     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9971   }
9972 
9973   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9974     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
9975     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9976   }
9977   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9978     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
9979     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9980   }
9981   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9982     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
9983     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9984   }
9985 
9986   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
9987     return Concat;
9988 
9989   bool DstIsLeft;
9990   int Anomaly;
9991   int NumInputElements = V1.getValueType().getVectorNumElements();
9992   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
9993     SDValue DstVec = DstIsLeft ? V1 : V2;
9994     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
9995 
9996     SDValue SrcVec = V1;
9997     int SrcLane = ShuffleMask[Anomaly];
9998     if (SrcLane >= NumInputElements) {
9999       SrcVec = V2;
10000       SrcLane -= VT.getVectorNumElements();
10001     }
10002     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
10003 
10004     EVT ScalarVT = VT.getVectorElementType();
10005 
10006     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
10007       ScalarVT = MVT::i32;
10008 
10009     return DAG.getNode(
10010         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
10011         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
10012         DstLaneV);
10013   }
10014 
10015   if (SDValue NewSD = tryWidenMaskForShuffle(Op, DAG))
10016     return NewSD;
10017 
10018   // If the shuffle is not directly supported and it has 4 elements, use
10019   // the PerfectShuffle-generated table to synthesize it from other shuffles.
10020   unsigned NumElts = VT.getVectorNumElements();
10021   if (NumElts == 4) {
10022     unsigned PFIndexes[4];
10023     for (unsigned i = 0; i != 4; ++i) {
10024       if (ShuffleMask[i] < 0)
10025         PFIndexes[i] = 8;
10026       else
10027         PFIndexes[i] = ShuffleMask[i];
10028     }
10029 
10030     // Compute the index in the perfect shuffle table.
10031     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10032                             PFIndexes[2] * 9 + PFIndexes[3];
10033     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10034     unsigned Cost = (PFEntry >> 30);
10035 
10036     if (Cost <= 4)
10037       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10038   }
10039 
10040   return GenerateTBL(Op, ShuffleMask, DAG);
10041 }
10042 
10043 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
10044                                                  SelectionDAG &DAG) const {
10045   SDLoc dl(Op);
10046   EVT VT = Op.getValueType();
10047   EVT ElemVT = VT.getScalarType();
10048   SDValue SplatVal = Op.getOperand(0);
10049 
10050   if (useSVEForFixedLengthVectorVT(VT))
10051     return LowerToScalableOp(Op, DAG);
10052 
10053   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
10054   // FPRs don't have this restriction.
10055   switch (ElemVT.getSimpleVT().SimpleTy) {
10056   case MVT::i1: {
10057     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
10058     // lowering code.
10059     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
10060       // We can hande the zero case during isel.
10061       if (ConstVal->isZero())
10062         return Op;
10063       if (ConstVal->isOne())
10064         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
10065     }
10066     // The general case of i1.  There isn't any natural way to do this,
10067     // so we use some trickery with whilelo.
10068     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
10069     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
10070                            DAG.getValueType(MVT::i1));
10071     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
10072                                        MVT::i64);
10073     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
10074                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
10075   }
10076   case MVT::i8:
10077   case MVT::i16:
10078   case MVT::i32:
10079     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
10080     break;
10081   case MVT::i64:
10082     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
10083     break;
10084   case MVT::f16:
10085   case MVT::bf16:
10086   case MVT::f32:
10087   case MVT::f64:
10088     // Fine as is
10089     break;
10090   default:
10091     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
10092   }
10093 
10094   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
10095 }
10096 
10097 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
10098                                              SelectionDAG &DAG) const {
10099   SDLoc DL(Op);
10100 
10101   EVT VT = Op.getValueType();
10102   if (!isTypeLegal(VT) || !VT.isScalableVector())
10103     return SDValue();
10104 
10105   // Current lowering only supports the SVE-ACLE types.
10106   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
10107     return SDValue();
10108 
10109   // The DUPQ operation is indepedent of element type so normalise to i64s.
10110   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
10111   SDValue Idx128 = Op.getOperand(2);
10112 
10113   // DUPQ can be used when idx is in range.
10114   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
10115   if (CIdx && (CIdx->getZExtValue() <= 3)) {
10116     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
10117     SDNode *DUPQ =
10118         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
10119     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
10120   }
10121 
10122   // The ACLE says this must produce the same result as:
10123   //   svtbl(data, svadd_x(svptrue_b64(),
10124   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
10125   //                       index * 2))
10126   SDValue One = DAG.getConstant(1, DL, MVT::i64);
10127   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
10128 
10129   // create the vector 0,1,0,1,...
10130   SDValue SV = DAG.getStepVector(DL, MVT::nxv2i64);
10131   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
10132 
10133   // create the vector idx64,idx64+1,idx64,idx64+1,...
10134   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
10135   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
10136   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
10137 
10138   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
10139   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
10140   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
10141 }
10142 
10143 
10144 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
10145                                APInt &UndefBits) {
10146   EVT VT = BVN->getValueType(0);
10147   APInt SplatBits, SplatUndef;
10148   unsigned SplatBitSize;
10149   bool HasAnyUndefs;
10150   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10151     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
10152 
10153     for (unsigned i = 0; i < NumSplats; ++i) {
10154       CnstBits <<= SplatBitSize;
10155       UndefBits <<= SplatBitSize;
10156       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
10157       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
10158     }
10159 
10160     return true;
10161   }
10162 
10163   return false;
10164 }
10165 
10166 // Try 64-bit splatted SIMD immediate.
10167 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10168                                  const APInt &Bits) {
10169   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10170     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10171     EVT VT = Op.getValueType();
10172     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
10173 
10174     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
10175       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
10176 
10177       SDLoc dl(Op);
10178       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10179                                 DAG.getConstant(Value, dl, MVT::i32));
10180       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10181     }
10182   }
10183 
10184   return SDValue();
10185 }
10186 
10187 // Try 32-bit splatted SIMD immediate.
10188 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10189                                   const APInt &Bits,
10190                                   const SDValue *LHS = nullptr) {
10191   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10192     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10193     EVT VT = Op.getValueType();
10194     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
10195     bool isAdvSIMDModImm = false;
10196     uint64_t Shift;
10197 
10198     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
10199       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
10200       Shift = 0;
10201     }
10202     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
10203       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
10204       Shift = 8;
10205     }
10206     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
10207       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
10208       Shift = 16;
10209     }
10210     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
10211       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
10212       Shift = 24;
10213     }
10214 
10215     if (isAdvSIMDModImm) {
10216       SDLoc dl(Op);
10217       SDValue Mov;
10218 
10219       if (LHS)
10220         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
10221                           DAG.getConstant(Value, dl, MVT::i32),
10222                           DAG.getConstant(Shift, dl, MVT::i32));
10223       else
10224         Mov = DAG.getNode(NewOp, dl, MovTy,
10225                           DAG.getConstant(Value, dl, MVT::i32),
10226                           DAG.getConstant(Shift, dl, MVT::i32));
10227 
10228       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10229     }
10230   }
10231 
10232   return SDValue();
10233 }
10234 
10235 // Try 16-bit splatted SIMD immediate.
10236 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10237                                   const APInt &Bits,
10238                                   const SDValue *LHS = nullptr) {
10239   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10240     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10241     EVT VT = Op.getValueType();
10242     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
10243     bool isAdvSIMDModImm = false;
10244     uint64_t Shift;
10245 
10246     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
10247       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
10248       Shift = 0;
10249     }
10250     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
10251       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
10252       Shift = 8;
10253     }
10254 
10255     if (isAdvSIMDModImm) {
10256       SDLoc dl(Op);
10257       SDValue Mov;
10258 
10259       if (LHS)
10260         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
10261                           DAG.getConstant(Value, dl, MVT::i32),
10262                           DAG.getConstant(Shift, dl, MVT::i32));
10263       else
10264         Mov = DAG.getNode(NewOp, dl, MovTy,
10265                           DAG.getConstant(Value, dl, MVT::i32),
10266                           DAG.getConstant(Shift, dl, MVT::i32));
10267 
10268       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10269     }
10270   }
10271 
10272   return SDValue();
10273 }
10274 
10275 // Try 32-bit splatted SIMD immediate with shifted ones.
10276 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
10277                                     SelectionDAG &DAG, const APInt &Bits) {
10278   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10279     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10280     EVT VT = Op.getValueType();
10281     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
10282     bool isAdvSIMDModImm = false;
10283     uint64_t Shift;
10284 
10285     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
10286       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
10287       Shift = 264;
10288     }
10289     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
10290       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
10291       Shift = 272;
10292     }
10293 
10294     if (isAdvSIMDModImm) {
10295       SDLoc dl(Op);
10296       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10297                                 DAG.getConstant(Value, dl, MVT::i32),
10298                                 DAG.getConstant(Shift, dl, MVT::i32));
10299       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10300     }
10301   }
10302 
10303   return SDValue();
10304 }
10305 
10306 // Try 8-bit splatted SIMD immediate.
10307 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10308                                  const APInt &Bits) {
10309   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10310     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10311     EVT VT = Op.getValueType();
10312     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
10313 
10314     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
10315       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
10316 
10317       SDLoc dl(Op);
10318       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10319                                 DAG.getConstant(Value, dl, MVT::i32));
10320       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10321     }
10322   }
10323 
10324   return SDValue();
10325 }
10326 
10327 // Try FP splatted SIMD immediate.
10328 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10329                                   const APInt &Bits) {
10330   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10331     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10332     EVT VT = Op.getValueType();
10333     bool isWide = (VT.getSizeInBits() == 128);
10334     MVT MovTy;
10335     bool isAdvSIMDModImm = false;
10336 
10337     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
10338       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
10339       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
10340     }
10341     else if (isWide &&
10342              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
10343       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
10344       MovTy = MVT::v2f64;
10345     }
10346 
10347     if (isAdvSIMDModImm) {
10348       SDLoc dl(Op);
10349       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10350                                 DAG.getConstant(Value, dl, MVT::i32));
10351       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10352     }
10353   }
10354 
10355   return SDValue();
10356 }
10357 
10358 // Specialized code to quickly find if PotentialBVec is a BuildVector that
10359 // consists of only the same constant int value, returned in reference arg
10360 // ConstVal
10361 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
10362                                      uint64_t &ConstVal) {
10363   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
10364   if (!Bvec)
10365     return false;
10366   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
10367   if (!FirstElt)
10368     return false;
10369   EVT VT = Bvec->getValueType(0);
10370   unsigned NumElts = VT.getVectorNumElements();
10371   for (unsigned i = 1; i < NumElts; ++i)
10372     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
10373       return false;
10374   ConstVal = FirstElt->getZExtValue();
10375   return true;
10376 }
10377 
10378 static unsigned getIntrinsicID(const SDNode *N) {
10379   unsigned Opcode = N->getOpcode();
10380   switch (Opcode) {
10381   default:
10382     return Intrinsic::not_intrinsic;
10383   case ISD::INTRINSIC_WO_CHAIN: {
10384     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10385     if (IID < Intrinsic::num_intrinsics)
10386       return IID;
10387     return Intrinsic::not_intrinsic;
10388   }
10389   }
10390 }
10391 
10392 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
10393 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
10394 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
10395 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
10396 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
10397 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
10398 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
10399   EVT VT = N->getValueType(0);
10400 
10401   if (!VT.isVector())
10402     return SDValue();
10403 
10404   SDLoc DL(N);
10405 
10406   SDValue And;
10407   SDValue Shift;
10408 
10409   SDValue FirstOp = N->getOperand(0);
10410   unsigned FirstOpc = FirstOp.getOpcode();
10411   SDValue SecondOp = N->getOperand(1);
10412   unsigned SecondOpc = SecondOp.getOpcode();
10413 
10414   // Is one of the operands an AND or a BICi? The AND may have been optimised to
10415   // a BICi in order to use an immediate instead of a register.
10416   // Is the other operand an shl or lshr? This will have been turned into:
10417   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
10418   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
10419       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
10420     And = FirstOp;
10421     Shift = SecondOp;
10422 
10423   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
10424              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
10425     And = SecondOp;
10426     Shift = FirstOp;
10427   } else
10428     return SDValue();
10429 
10430   bool IsAnd = And.getOpcode() == ISD::AND;
10431   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
10432 
10433   // Is the shift amount constant?
10434   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10435   if (!C2node)
10436     return SDValue();
10437 
10438   uint64_t C1;
10439   if (IsAnd) {
10440     // Is the and mask vector all constant?
10441     if (!isAllConstantBuildVector(And.getOperand(1), C1))
10442       return SDValue();
10443   } else {
10444     // Reconstruct the corresponding AND immediate from the two BICi immediates.
10445     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
10446     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
10447     assert(C1nodeImm && C1nodeShift);
10448     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
10449   }
10450 
10451   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
10452   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
10453   // how much one can shift elements of a particular size?
10454   uint64_t C2 = C2node->getZExtValue();
10455   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
10456   if (C2 > ElemSizeInBits)
10457     return SDValue();
10458 
10459   APInt C1AsAPInt(ElemSizeInBits, C1);
10460   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
10461                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
10462   if (C1AsAPInt != RequiredC1)
10463     return SDValue();
10464 
10465   SDValue X = And.getOperand(0);
10466   SDValue Y = Shift.getOperand(0);
10467 
10468   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
10469   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
10470 
10471   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
10472   LLVM_DEBUG(N->dump(&DAG));
10473   LLVM_DEBUG(dbgs() << "into: \n");
10474   LLVM_DEBUG(ResultSLI->dump(&DAG));
10475 
10476   ++NumShiftInserts;
10477   return ResultSLI;
10478 }
10479 
10480 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
10481                                              SelectionDAG &DAG) const {
10482   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10483     return LowerToScalableOp(Op, DAG);
10484 
10485   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
10486   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
10487     return Res;
10488 
10489   EVT VT = Op.getValueType();
10490 
10491   SDValue LHS = Op.getOperand(0);
10492   BuildVectorSDNode *BVN =
10493       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
10494   if (!BVN) {
10495     // OR commutes, so try swapping the operands.
10496     LHS = Op.getOperand(1);
10497     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
10498   }
10499   if (!BVN)
10500     return Op;
10501 
10502   APInt DefBits(VT.getSizeInBits(), 0);
10503   APInt UndefBits(VT.getSizeInBits(), 0);
10504   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10505     SDValue NewOp;
10506 
10507     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
10508                                     DefBits, &LHS)) ||
10509         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
10510                                     DefBits, &LHS)))
10511       return NewOp;
10512 
10513     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
10514                                     UndefBits, &LHS)) ||
10515         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
10516                                     UndefBits, &LHS)))
10517       return NewOp;
10518   }
10519 
10520   // We can always fall back to a non-immediate OR.
10521   return Op;
10522 }
10523 
10524 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
10525 // be truncated to fit element width.
10526 static SDValue NormalizeBuildVector(SDValue Op,
10527                                     SelectionDAG &DAG) {
10528   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
10529   SDLoc dl(Op);
10530   EVT VT = Op.getValueType();
10531   EVT EltTy= VT.getVectorElementType();
10532 
10533   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
10534     return Op;
10535 
10536   SmallVector<SDValue, 16> Ops;
10537   for (SDValue Lane : Op->ops()) {
10538     // For integer vectors, type legalization would have promoted the
10539     // operands already. Otherwise, if Op is a floating-point splat
10540     // (with operands cast to integers), then the only possibilities
10541     // are constants and UNDEFs.
10542     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
10543       APInt LowBits(EltTy.getSizeInBits(),
10544                     CstLane->getZExtValue());
10545       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
10546     } else if (Lane.getNode()->isUndef()) {
10547       Lane = DAG.getUNDEF(MVT::i32);
10548     } else {
10549       assert(Lane.getValueType() == MVT::i32 &&
10550              "Unexpected BUILD_VECTOR operand type");
10551     }
10552     Ops.push_back(Lane);
10553   }
10554   return DAG.getBuildVector(VT, dl, Ops);
10555 }
10556 
10557 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
10558   EVT VT = Op.getValueType();
10559 
10560   APInt DefBits(VT.getSizeInBits(), 0);
10561   APInt UndefBits(VT.getSizeInBits(), 0);
10562   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
10563   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10564     SDValue NewOp;
10565     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
10566         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10567         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
10568         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10569         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
10570         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
10571       return NewOp;
10572 
10573     DefBits = ~DefBits;
10574     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
10575         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
10576         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
10577       return NewOp;
10578 
10579     DefBits = UndefBits;
10580     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
10581         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10582         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
10583         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10584         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
10585         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
10586       return NewOp;
10587 
10588     DefBits = ~UndefBits;
10589     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
10590         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
10591         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
10592       return NewOp;
10593   }
10594 
10595   return SDValue();
10596 }
10597 
10598 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
10599                                                  SelectionDAG &DAG) const {
10600   EVT VT = Op.getValueType();
10601 
10602   // Try to build a simple constant vector.
10603   Op = NormalizeBuildVector(Op, DAG);
10604   if (VT.isInteger()) {
10605     // Certain vector constants, used to express things like logical NOT and
10606     // arithmetic NEG, are passed through unmodified.  This allows special
10607     // patterns for these operations to match, which will lower these constants
10608     // to whatever is proven necessary.
10609     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
10610     if (BVN->isConstant())
10611       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
10612         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
10613         APInt Val(BitSize,
10614                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
10615         if (Val.isZero() || Val.isAllOnes())
10616           return Op;
10617       }
10618   }
10619 
10620   if (SDValue V = ConstantBuildVector(Op, DAG))
10621     return V;
10622 
10623   // Scan through the operands to find some interesting properties we can
10624   // exploit:
10625   //   1) If only one value is used, we can use a DUP, or
10626   //   2) if only the low element is not undef, we can just insert that, or
10627   //   3) if only one constant value is used (w/ some non-constant lanes),
10628   //      we can splat the constant value into the whole vector then fill
10629   //      in the non-constant lanes.
10630   //   4) FIXME: If different constant values are used, but we can intelligently
10631   //             select the values we'll be overwriting for the non-constant
10632   //             lanes such that we can directly materialize the vector
10633   //             some other way (MOVI, e.g.), we can be sneaky.
10634   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
10635   SDLoc dl(Op);
10636   unsigned NumElts = VT.getVectorNumElements();
10637   bool isOnlyLowElement = true;
10638   bool usesOnlyOneValue = true;
10639   bool usesOnlyOneConstantValue = true;
10640   bool isConstant = true;
10641   bool AllLanesExtractElt = true;
10642   unsigned NumConstantLanes = 0;
10643   unsigned NumDifferentLanes = 0;
10644   unsigned NumUndefLanes = 0;
10645   SDValue Value;
10646   SDValue ConstantValue;
10647   for (unsigned i = 0; i < NumElts; ++i) {
10648     SDValue V = Op.getOperand(i);
10649     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10650       AllLanesExtractElt = false;
10651     if (V.isUndef()) {
10652       ++NumUndefLanes;
10653       continue;
10654     }
10655     if (i > 0)
10656       isOnlyLowElement = false;
10657     if (!isIntOrFPConstant(V))
10658       isConstant = false;
10659 
10660     if (isIntOrFPConstant(V)) {
10661       ++NumConstantLanes;
10662       if (!ConstantValue.getNode())
10663         ConstantValue = V;
10664       else if (ConstantValue != V)
10665         usesOnlyOneConstantValue = false;
10666     }
10667 
10668     if (!Value.getNode())
10669       Value = V;
10670     else if (V != Value) {
10671       usesOnlyOneValue = false;
10672       ++NumDifferentLanes;
10673     }
10674   }
10675 
10676   if (!Value.getNode()) {
10677     LLVM_DEBUG(
10678         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
10679     return DAG.getUNDEF(VT);
10680   }
10681 
10682   // Convert BUILD_VECTOR where all elements but the lowest are undef into
10683   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
10684   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
10685   if (isOnlyLowElement && !(NumElts == 1 && isIntOrFPConstant(Value))) {
10686     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
10687                          "SCALAR_TO_VECTOR node\n");
10688     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
10689   }
10690 
10691   if (AllLanesExtractElt) {
10692     SDNode *Vector = nullptr;
10693     bool Even = false;
10694     bool Odd = false;
10695     // Check whether the extract elements match the Even pattern <0,2,4,...> or
10696     // the Odd pattern <1,3,5,...>.
10697     for (unsigned i = 0; i < NumElts; ++i) {
10698       SDValue V = Op.getOperand(i);
10699       const SDNode *N = V.getNode();
10700       if (!isa<ConstantSDNode>(N->getOperand(1)))
10701         break;
10702       SDValue N0 = N->getOperand(0);
10703 
10704       // All elements are extracted from the same vector.
10705       if (!Vector) {
10706         Vector = N0.getNode();
10707         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
10708         // BUILD_VECTOR.
10709         if (VT.getVectorElementType() !=
10710             N0.getValueType().getVectorElementType())
10711           break;
10712       } else if (Vector != N0.getNode()) {
10713         Odd = false;
10714         Even = false;
10715         break;
10716       }
10717 
10718       // Extracted values are either at Even indices <0,2,4,...> or at Odd
10719       // indices <1,3,5,...>.
10720       uint64_t Val = N->getConstantOperandVal(1);
10721       if (Val == 2 * i) {
10722         Even = true;
10723         continue;
10724       }
10725       if (Val - 1 == 2 * i) {
10726         Odd = true;
10727         continue;
10728       }
10729 
10730       // Something does not match: abort.
10731       Odd = false;
10732       Even = false;
10733       break;
10734     }
10735     if (Even || Odd) {
10736       SDValue LHS =
10737           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
10738                       DAG.getConstant(0, dl, MVT::i64));
10739       SDValue RHS =
10740           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
10741                       DAG.getConstant(NumElts, dl, MVT::i64));
10742 
10743       if (Even && !Odd)
10744         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
10745                            RHS);
10746       if (Odd && !Even)
10747         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
10748                            RHS);
10749     }
10750   }
10751 
10752   // Use DUP for non-constant splats. For f32 constant splats, reduce to
10753   // i32 and try again.
10754   if (usesOnlyOneValue) {
10755     if (!isConstant) {
10756       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10757           Value.getValueType() != VT) {
10758         LLVM_DEBUG(
10759             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
10760         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
10761       }
10762 
10763       // This is actually a DUPLANExx operation, which keeps everything vectory.
10764 
10765       SDValue Lane = Value.getOperand(1);
10766       Value = Value.getOperand(0);
10767       if (Value.getValueSizeInBits() == 64) {
10768         LLVM_DEBUG(
10769             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
10770                       "widening it\n");
10771         Value = WidenVector(Value, DAG);
10772       }
10773 
10774       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
10775       return DAG.getNode(Opcode, dl, VT, Value, Lane);
10776     }
10777 
10778     if (VT.getVectorElementType().isFloatingPoint()) {
10779       SmallVector<SDValue, 8> Ops;
10780       EVT EltTy = VT.getVectorElementType();
10781       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
10782                EltTy == MVT::f64) && "Unsupported floating-point vector type");
10783       LLVM_DEBUG(
10784           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
10785                     "BITCASTS, and try again\n");
10786       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
10787       for (unsigned i = 0; i < NumElts; ++i)
10788         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
10789       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
10790       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
10791       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
10792                  Val.dump(););
10793       Val = LowerBUILD_VECTOR(Val, DAG);
10794       if (Val.getNode())
10795         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
10796     }
10797   }
10798 
10799   // If we need to insert a small number of different non-constant elements and
10800   // the vector width is sufficiently large, prefer using DUP with the common
10801   // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
10802   // skip the constant lane handling below.
10803   bool PreferDUPAndInsert =
10804       !isConstant && NumDifferentLanes >= 1 &&
10805       NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
10806       NumDifferentLanes >= NumConstantLanes;
10807 
10808   // If there was only one constant value used and for more than one lane,
10809   // start by splatting that value, then replace the non-constant lanes. This
10810   // is better than the default, which will perform a separate initialization
10811   // for each lane.
10812   if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
10813     // Firstly, try to materialize the splat constant.
10814     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
10815             Val = ConstantBuildVector(Vec, DAG);
10816     if (!Val) {
10817       // Otherwise, materialize the constant and splat it.
10818       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
10819       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
10820     }
10821 
10822     // Now insert the non-constant lanes.
10823     for (unsigned i = 0; i < NumElts; ++i) {
10824       SDValue V = Op.getOperand(i);
10825       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
10826       if (!isIntOrFPConstant(V))
10827         // Note that type legalization likely mucked about with the VT of the
10828         // source operand, so we may have to convert it here before inserting.
10829         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
10830     }
10831     return Val;
10832   }
10833 
10834   // This will generate a load from the constant pool.
10835   if (isConstant) {
10836     LLVM_DEBUG(
10837         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
10838                   "expansion\n");
10839     return SDValue();
10840   }
10841 
10842   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
10843   if (NumElts >= 4) {
10844     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
10845       return shuffle;
10846   }
10847 
10848   if (PreferDUPAndInsert) {
10849     // First, build a constant vector with the common element.
10850     SmallVector<SDValue, 8> Ops(NumElts, Value);
10851     SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
10852     // Next, insert the elements that do not match the common value.
10853     for (unsigned I = 0; I < NumElts; ++I)
10854       if (Op.getOperand(I) != Value)
10855         NewVector =
10856             DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
10857                         Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
10858 
10859     return NewVector;
10860   }
10861 
10862   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
10863   // know the default expansion would otherwise fall back on something even
10864   // worse. For a vector with one or two non-undef values, that's
10865   // scalar_to_vector for the elements followed by a shuffle (provided the
10866   // shuffle is valid for the target) and materialization element by element
10867   // on the stack followed by a load for everything else.
10868   if (!isConstant && !usesOnlyOneValue) {
10869     LLVM_DEBUG(
10870         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
10871                   "of INSERT_VECTOR_ELT\n");
10872 
10873     SDValue Vec = DAG.getUNDEF(VT);
10874     SDValue Op0 = Op.getOperand(0);
10875     unsigned i = 0;
10876 
10877     // Use SCALAR_TO_VECTOR for lane zero to
10878     // a) Avoid a RMW dependency on the full vector register, and
10879     // b) Allow the register coalescer to fold away the copy if the
10880     //    value is already in an S or D register, and we're forced to emit an
10881     //    INSERT_SUBREG that we can't fold anywhere.
10882     //
10883     // We also allow types like i8 and i16 which are illegal scalar but legal
10884     // vector element types. After type-legalization the inserted value is
10885     // extended (i32) and it is safe to cast them to the vector type by ignoring
10886     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
10887     if (!Op0.isUndef()) {
10888       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
10889       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
10890       ++i;
10891     }
10892     LLVM_DEBUG(if (i < NumElts) dbgs()
10893                    << "Creating nodes for the other vector elements:\n";);
10894     for (; i < NumElts; ++i) {
10895       SDValue V = Op.getOperand(i);
10896       if (V.isUndef())
10897         continue;
10898       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
10899       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
10900     }
10901     return Vec;
10902   }
10903 
10904   LLVM_DEBUG(
10905       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
10906                 "better alternative\n");
10907   return SDValue();
10908 }
10909 
10910 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
10911                                                    SelectionDAG &DAG) const {
10912   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10913     return LowerFixedLengthConcatVectorsToSVE(Op, DAG);
10914 
10915   assert(Op.getValueType().isScalableVector() &&
10916          isTypeLegal(Op.getValueType()) &&
10917          "Expected legal scalable vector type!");
10918 
10919   if (isTypeLegal(Op.getOperand(0).getValueType())) {
10920     unsigned NumOperands = Op->getNumOperands();
10921     assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
10922            "Unexpected number of operands in CONCAT_VECTORS");
10923 
10924     if (NumOperands == 2)
10925       return Op;
10926 
10927     // Concat each pair of subvectors and pack into the lower half of the array.
10928     SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
10929     while (ConcatOps.size() > 1) {
10930       for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
10931         SDValue V1 = ConcatOps[I];
10932         SDValue V2 = ConcatOps[I + 1];
10933         EVT SubVT = V1.getValueType();
10934         EVT PairVT = SubVT.getDoubleNumVectorElementsVT(*DAG.getContext());
10935         ConcatOps[I / 2] =
10936             DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), PairVT, V1, V2);
10937       }
10938       ConcatOps.resize(ConcatOps.size() / 2);
10939     }
10940     return ConcatOps[0];
10941   }
10942 
10943   return SDValue();
10944 }
10945 
10946 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10947                                                       SelectionDAG &DAG) const {
10948   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
10949 
10950   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10951     return LowerFixedLengthInsertVectorElt(Op, DAG);
10952 
10953   // Check for non-constant or out of range lane.
10954   EVT VT = Op.getOperand(0).getValueType();
10955 
10956   if (VT.getScalarType() == MVT::i1) {
10957     EVT VectorVT = getPromotedVTForPredicate(VT);
10958     SDLoc DL(Op);
10959     SDValue ExtendedVector =
10960         DAG.getAnyExtOrTrunc(Op.getOperand(0), DL, VectorVT);
10961     SDValue ExtendedValue =
10962         DAG.getAnyExtOrTrunc(Op.getOperand(1), DL,
10963                              VectorVT.getScalarType().getSizeInBits() < 32
10964                                  ? MVT::i32
10965                                  : VectorVT.getScalarType());
10966     ExtendedVector =
10967         DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VectorVT, ExtendedVector,
10968                     ExtendedValue, Op.getOperand(2));
10969     return DAG.getAnyExtOrTrunc(ExtendedVector, DL, VT);
10970   }
10971 
10972   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10973   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
10974     return SDValue();
10975 
10976   // Insertion/extraction are legal for V128 types.
10977   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10978       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
10979       VT == MVT::v8f16 || VT == MVT::v8bf16)
10980     return Op;
10981 
10982   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
10983       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
10984       VT != MVT::v4bf16)
10985     return SDValue();
10986 
10987   // For V64 types, we perform insertion by expanding the value
10988   // to a V128 type and perform the insertion on that.
10989   SDLoc DL(Op);
10990   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
10991   EVT WideTy = WideVec.getValueType();
10992 
10993   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
10994                              Op.getOperand(1), Op.getOperand(2));
10995   // Re-narrow the resultant vector.
10996   return NarrowVector(Node, DAG);
10997 }
10998 
10999 SDValue
11000 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11001                                                SelectionDAG &DAG) const {
11002   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
11003   EVT VT = Op.getOperand(0).getValueType();
11004 
11005   if (VT.getScalarType() == MVT::i1) {
11006     // We can't directly extract from an SVE predicate; extend it first.
11007     // (This isn't the only possible lowering, but it's straightforward.)
11008     EVT VectorVT = getPromotedVTForPredicate(VT);
11009     SDLoc DL(Op);
11010     SDValue Extend =
11011         DAG.getNode(ISD::ANY_EXTEND, DL, VectorVT, Op.getOperand(0));
11012     MVT ExtractTy = VectorVT == MVT::nxv2i64 ? MVT::i64 : MVT::i32;
11013     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractTy,
11014                                   Extend, Op.getOperand(1));
11015     return DAG.getAnyExtOrTrunc(Extract, DL, Op.getValueType());
11016   }
11017 
11018   if (useSVEForFixedLengthVectorVT(VT))
11019     return LowerFixedLengthExtractVectorElt(Op, DAG);
11020 
11021   // Check for non-constant or out of range lane.
11022   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11023   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
11024     return SDValue();
11025 
11026   // Insertion/extraction are legal for V128 types.
11027   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
11028       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
11029       VT == MVT::v8f16 || VT == MVT::v8bf16)
11030     return Op;
11031 
11032   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
11033       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
11034       VT != MVT::v4bf16)
11035     return SDValue();
11036 
11037   // For V64 types, we perform extraction by expanding the value
11038   // to a V128 type and perform the extraction on that.
11039   SDLoc DL(Op);
11040   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
11041   EVT WideTy = WideVec.getValueType();
11042 
11043   EVT ExtrTy = WideTy.getVectorElementType();
11044   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
11045     ExtrTy = MVT::i32;
11046 
11047   // For extractions, we just return the result directly.
11048   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
11049                      Op.getOperand(1));
11050 }
11051 
11052 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
11053                                                       SelectionDAG &DAG) const {
11054   assert(Op.getValueType().isFixedLengthVector() &&
11055          "Only cases that extract a fixed length vector are supported!");
11056 
11057   EVT InVT = Op.getOperand(0).getValueType();
11058   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11059   unsigned Size = Op.getValueSizeInBits();
11060 
11061   // If we don't have legal types yet, do nothing
11062   if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
11063     return SDValue();
11064 
11065   if (InVT.isScalableVector()) {
11066     // This will be matched by custom code during ISelDAGToDAG.
11067     if (Idx == 0 && isPackedVectorType(InVT, DAG))
11068       return Op;
11069 
11070     return SDValue();
11071   }
11072 
11073   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
11074   if (Idx == 0 && InVT.getSizeInBits() <= 128)
11075     return Op;
11076 
11077   // If this is extracting the upper 64-bits of a 128-bit vector, we match
11078   // that directly.
11079   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
11080       InVT.getSizeInBits() == 128)
11081     return Op;
11082 
11083   if (useSVEForFixedLengthVectorVT(InVT)) {
11084     SDLoc DL(Op);
11085 
11086     EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
11087     SDValue NewInVec =
11088         convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
11089 
11090     SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ContainerVT, NewInVec,
11091                                  NewInVec, DAG.getConstant(Idx, DL, MVT::i64));
11092     return convertFromScalableVector(DAG, Op.getValueType(), Splice);
11093   }
11094 
11095   return SDValue();
11096 }
11097 
11098 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
11099                                                      SelectionDAG &DAG) const {
11100   assert(Op.getValueType().isScalableVector() &&
11101          "Only expect to lower inserts into scalable vectors!");
11102 
11103   EVT InVT = Op.getOperand(1).getValueType();
11104   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11105 
11106   SDValue Vec0 = Op.getOperand(0);
11107   SDValue Vec1 = Op.getOperand(1);
11108   SDLoc DL(Op);
11109   EVT VT = Op.getValueType();
11110 
11111   if (InVT.isScalableVector()) {
11112     if (!isTypeLegal(VT))
11113       return SDValue();
11114 
11115     // Break down insert_subvector into simpler parts.
11116     if (VT.getVectorElementType() == MVT::i1) {
11117       unsigned NumElts = VT.getVectorMinNumElements();
11118       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11119 
11120       SDValue Lo, Hi;
11121       Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Vec0,
11122                        DAG.getVectorIdxConstant(0, DL));
11123       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Vec0,
11124                        DAG.getVectorIdxConstant(NumElts / 2, DL));
11125       if (Idx < (NumElts / 2)) {
11126         SDValue NewLo = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, HalfVT, Lo, Vec1,
11127                                     DAG.getVectorIdxConstant(Idx, DL));
11128         return DAG.getNode(AArch64ISD::UZP1, DL, VT, NewLo, Hi);
11129       } else {
11130         SDValue NewHi =
11131             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, HalfVT, Hi, Vec1,
11132                         DAG.getVectorIdxConstant(Idx - (NumElts / 2), DL));
11133         return DAG.getNode(AArch64ISD::UZP1, DL, VT, Lo, NewHi);
11134       }
11135     }
11136 
11137     // Ensure the subvector is half the size of the main vector.
11138     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
11139       return SDValue();
11140 
11141     EVT WideVT;
11142     SDValue ExtVec;
11143 
11144     if (VT.isFloatingPoint()) {
11145       // The InVT type should be legal. We can safely cast the unpacked
11146       // subvector from InVT -> VT.
11147       WideVT = VT;
11148       ExtVec = getSVESafeBitCast(VT, Vec1, DAG);
11149     } else {
11150       // Extend elements of smaller vector...
11151       WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
11152       ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
11153     }
11154 
11155     if (Idx == 0) {
11156       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
11157       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
11158     } else if (Idx == InVT.getVectorMinNumElements()) {
11159       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
11160       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
11161     }
11162 
11163     return SDValue();
11164   }
11165 
11166   if (Idx == 0 && isPackedVectorType(VT, DAG)) {
11167     // This will be matched by custom code during ISelDAGToDAG.
11168     if (Vec0.isUndef())
11169       return Op;
11170 
11171     Optional<unsigned> PredPattern =
11172         getSVEPredPatternFromNumElements(InVT.getVectorNumElements());
11173     auto PredTy = VT.changeVectorElementType(MVT::i1);
11174     SDValue PTrue = getPTrue(DAG, DL, PredTy, *PredPattern);
11175     SDValue ScalableVec1 = convertToScalableVector(DAG, VT, Vec1);
11176     return DAG.getNode(ISD::VSELECT, DL, VT, PTrue, ScalableVec1, Vec0);
11177   }
11178 
11179   return SDValue();
11180 }
11181 
11182 static bool isPow2Splat(SDValue Op, uint64_t &SplatVal, bool &Negated) {
11183   if (Op.getOpcode() != AArch64ISD::DUP &&
11184       Op.getOpcode() != ISD::SPLAT_VECTOR &&
11185       Op.getOpcode() != ISD::BUILD_VECTOR)
11186     return false;
11187 
11188   if (Op.getOpcode() == ISD::BUILD_VECTOR &&
11189       !isAllConstantBuildVector(Op, SplatVal))
11190     return false;
11191 
11192   if (Op.getOpcode() != ISD::BUILD_VECTOR &&
11193       !isa<ConstantSDNode>(Op->getOperand(0)))
11194     return false;
11195 
11196   SplatVal = Op->getConstantOperandVal(0);
11197   if (Op.getValueType().getVectorElementType() != MVT::i64)
11198     SplatVal = (int32_t)SplatVal;
11199 
11200   Negated = false;
11201   if (isPowerOf2_64(SplatVal))
11202     return true;
11203 
11204   Negated = true;
11205   if (isPowerOf2_64(-SplatVal)) {
11206     SplatVal = -SplatVal;
11207     return true;
11208   }
11209 
11210   return false;
11211 }
11212 
11213 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
11214   EVT VT = Op.getValueType();
11215   SDLoc dl(Op);
11216 
11217   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
11218     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
11219 
11220   assert(VT.isScalableVector() && "Expected a scalable vector.");
11221 
11222   bool Signed = Op.getOpcode() == ISD::SDIV;
11223   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
11224 
11225   bool Negated;
11226   uint64_t SplatVal;
11227   if (Signed && isPow2Splat(Op.getOperand(1), SplatVal, Negated)) {
11228     SDValue Pg = getPredicateForScalableVector(DAG, dl, VT);
11229     SDValue Res =
11230         DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, dl, VT, Pg, Op->getOperand(0),
11231                     DAG.getTargetConstant(Log2_64(SplatVal), dl, MVT::i32));
11232     if (Negated)
11233       Res = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), Res);
11234 
11235     return Res;
11236   }
11237 
11238   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
11239     return LowerToPredicatedOp(Op, DAG, PredOpcode);
11240 
11241   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
11242   // operations, and truncate the result.
11243   EVT WidenedVT;
11244   if (VT == MVT::nxv16i8)
11245     WidenedVT = MVT::nxv8i16;
11246   else if (VT == MVT::nxv8i16)
11247     WidenedVT = MVT::nxv4i32;
11248   else
11249     llvm_unreachable("Unexpected Custom DIV operation");
11250 
11251   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
11252   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
11253   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
11254   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
11255   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
11256   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
11257   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
11258   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
11259   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
11260 }
11261 
11262 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
11263   // Currently no fixed length shuffles that require SVE are legal.
11264   if (useSVEForFixedLengthVectorVT(VT))
11265     return false;
11266 
11267   if (VT.getVectorNumElements() == 4 &&
11268       (VT.is128BitVector() || VT.is64BitVector())) {
11269     unsigned PFIndexes[4];
11270     for (unsigned i = 0; i != 4; ++i) {
11271       if (M[i] < 0)
11272         PFIndexes[i] = 8;
11273       else
11274         PFIndexes[i] = M[i];
11275     }
11276 
11277     // Compute the index in the perfect shuffle table.
11278     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
11279                             PFIndexes[2] * 9 + PFIndexes[3];
11280     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
11281     unsigned Cost = (PFEntry >> 30);
11282 
11283     if (Cost <= 4)
11284       return true;
11285   }
11286 
11287   bool DummyBool;
11288   int DummyInt;
11289   unsigned DummyUnsigned;
11290 
11291   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
11292           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
11293           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
11294           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
11295           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
11296           isZIPMask(M, VT, DummyUnsigned) ||
11297           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
11298           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
11299           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
11300           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
11301           isConcatMask(M, VT, VT.getSizeInBits() == 128));
11302 }
11303 
11304 /// getVShiftImm - Check if this is a valid build_vector for the immediate
11305 /// operand of a vector shift operation, where all the elements of the
11306 /// build_vector must have the same constant integer value.
11307 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11308   // Ignore bit_converts.
11309   while (Op.getOpcode() == ISD::BITCAST)
11310     Op = Op.getOperand(0);
11311   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11312   APInt SplatBits, SplatUndef;
11313   unsigned SplatBitSize;
11314   bool HasAnyUndefs;
11315   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11316                                     HasAnyUndefs, ElementBits) ||
11317       SplatBitSize > ElementBits)
11318     return false;
11319   Cnt = SplatBits.getSExtValue();
11320   return true;
11321 }
11322 
11323 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11324 /// operand of a vector shift left operation.  That value must be in the range:
11325 ///   0 <= Value < ElementBits for a left shift; or
11326 ///   0 <= Value <= ElementBits for a long left shift.
11327 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11328   assert(VT.isVector() && "vector shift count is not a vector type");
11329   int64_t ElementBits = VT.getScalarSizeInBits();
11330   if (!getVShiftImm(Op, ElementBits, Cnt))
11331     return false;
11332   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
11333 }
11334 
11335 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11336 /// operand of a vector shift right operation. The value must be in the range:
11337 ///   1 <= Value <= ElementBits for a right shift; or
11338 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
11339   assert(VT.isVector() && "vector shift count is not a vector type");
11340   int64_t ElementBits = VT.getScalarSizeInBits();
11341   if (!getVShiftImm(Op, ElementBits, Cnt))
11342     return false;
11343   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
11344 }
11345 
11346 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
11347                                              SelectionDAG &DAG) const {
11348   EVT VT = Op.getValueType();
11349 
11350   if (VT.getScalarType() == MVT::i1) {
11351     // Lower i1 truncate to `(x & 1) != 0`.
11352     SDLoc dl(Op);
11353     EVT OpVT = Op.getOperand(0).getValueType();
11354     SDValue Zero = DAG.getConstant(0, dl, OpVT);
11355     SDValue One = DAG.getConstant(1, dl, OpVT);
11356     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
11357     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
11358   }
11359 
11360   if (!VT.isVector() || VT.isScalableVector())
11361     return SDValue();
11362 
11363   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
11364     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
11365 
11366   return SDValue();
11367 }
11368 
11369 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
11370                                                       SelectionDAG &DAG) const {
11371   EVT VT = Op.getValueType();
11372   SDLoc DL(Op);
11373   int64_t Cnt;
11374 
11375   if (!Op.getOperand(1).getValueType().isVector())
11376     return Op;
11377   unsigned EltSize = VT.getScalarSizeInBits();
11378 
11379   switch (Op.getOpcode()) {
11380   default:
11381     llvm_unreachable("unexpected shift opcode");
11382 
11383   case ISD::SHL:
11384     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
11385       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
11386 
11387     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
11388       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
11389                          DAG.getConstant(Cnt, DL, MVT::i32));
11390     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11391                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
11392                                        MVT::i32),
11393                        Op.getOperand(0), Op.getOperand(1));
11394   case ISD::SRA:
11395   case ISD::SRL:
11396     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
11397       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
11398                                                 : AArch64ISD::SRL_PRED;
11399       return LowerToPredicatedOp(Op, DAG, Opc);
11400     }
11401 
11402     // Right shift immediate
11403     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
11404       unsigned Opc =
11405           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
11406       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
11407                          DAG.getConstant(Cnt, DL, MVT::i32));
11408     }
11409 
11410     // Right shift register.  Note, there is not a shift right register
11411     // instruction, but the shift left register instruction takes a signed
11412     // value, where negative numbers specify a right shift.
11413     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
11414                                                 : Intrinsic::aarch64_neon_ushl;
11415     // negate the shift amount
11416     SDValue NegShift = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
11417                                    Op.getOperand(1));
11418     SDValue NegShiftLeft =
11419         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11420                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
11421                     NegShift);
11422     return NegShiftLeft;
11423   }
11424 
11425   return SDValue();
11426 }
11427 
11428 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
11429                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
11430                                     const SDLoc &dl, SelectionDAG &DAG) {
11431   EVT SrcVT = LHS.getValueType();
11432   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
11433          "function only supposed to emit natural comparisons");
11434 
11435   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
11436   APInt CnstBits(VT.getSizeInBits(), 0);
11437   APInt UndefBits(VT.getSizeInBits(), 0);
11438   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
11439   bool IsZero = IsCnst && (CnstBits == 0);
11440 
11441   if (SrcVT.getVectorElementType().isFloatingPoint()) {
11442     switch (CC) {
11443     default:
11444       return SDValue();
11445     case AArch64CC::NE: {
11446       SDValue Fcmeq;
11447       if (IsZero)
11448         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
11449       else
11450         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
11451       return DAG.getNOT(dl, Fcmeq, VT);
11452     }
11453     case AArch64CC::EQ:
11454       if (IsZero)
11455         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
11456       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
11457     case AArch64CC::GE:
11458       if (IsZero)
11459         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
11460       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
11461     case AArch64CC::GT:
11462       if (IsZero)
11463         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
11464       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
11465     case AArch64CC::LS:
11466       if (IsZero)
11467         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
11468       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
11469     case AArch64CC::LT:
11470       if (!NoNans)
11471         return SDValue();
11472       // If we ignore NaNs then we can use to the MI implementation.
11473       LLVM_FALLTHROUGH;
11474     case AArch64CC::MI:
11475       if (IsZero)
11476         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
11477       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
11478     }
11479   }
11480 
11481   switch (CC) {
11482   default:
11483     return SDValue();
11484   case AArch64CC::NE: {
11485     SDValue Cmeq;
11486     if (IsZero)
11487       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
11488     else
11489       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
11490     return DAG.getNOT(dl, Cmeq, VT);
11491   }
11492   case AArch64CC::EQ:
11493     if (IsZero)
11494       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
11495     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
11496   case AArch64CC::GE:
11497     if (IsZero)
11498       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
11499     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
11500   case AArch64CC::GT:
11501     if (IsZero)
11502       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
11503     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
11504   case AArch64CC::LE:
11505     if (IsZero)
11506       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
11507     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
11508   case AArch64CC::LS:
11509     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
11510   case AArch64CC::LO:
11511     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
11512   case AArch64CC::LT:
11513     if (IsZero)
11514       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
11515     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
11516   case AArch64CC::HI:
11517     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
11518   case AArch64CC::HS:
11519     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
11520   }
11521 }
11522 
11523 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
11524                                            SelectionDAG &DAG) const {
11525   if (Op.getValueType().isScalableVector())
11526     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
11527 
11528   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
11529     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
11530 
11531   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11532   SDValue LHS = Op.getOperand(0);
11533   SDValue RHS = Op.getOperand(1);
11534   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
11535   SDLoc dl(Op);
11536 
11537   if (LHS.getValueType().getVectorElementType().isInteger()) {
11538     assert(LHS.getValueType() == RHS.getValueType());
11539     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
11540     SDValue Cmp =
11541         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
11542     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
11543   }
11544 
11545   const bool FullFP16 =
11546     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
11547 
11548   // Make v4f16 (only) fcmp operations utilise vector instructions
11549   // v8f16 support will be a litle more complicated
11550   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
11551     if (LHS.getValueType().getVectorNumElements() == 4) {
11552       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
11553       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
11554       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
11555       DAG.ReplaceAllUsesWith(Op, NewSetcc);
11556       CmpVT = MVT::v4i32;
11557     } else
11558       return SDValue();
11559   }
11560 
11561   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
11562           LHS.getValueType().getVectorElementType() != MVT::f128);
11563 
11564   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
11565   // clean.  Some of them require two branches to implement.
11566   AArch64CC::CondCode CC1, CC2;
11567   bool ShouldInvert;
11568   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
11569 
11570   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
11571   SDValue Cmp =
11572       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
11573   if (!Cmp.getNode())
11574     return SDValue();
11575 
11576   if (CC2 != AArch64CC::AL) {
11577     SDValue Cmp2 =
11578         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
11579     if (!Cmp2.getNode())
11580       return SDValue();
11581 
11582     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
11583   }
11584 
11585   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
11586 
11587   if (ShouldInvert)
11588     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
11589 
11590   return Cmp;
11591 }
11592 
11593 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
11594                                   SelectionDAG &DAG) {
11595   SDValue VecOp = ScalarOp.getOperand(0);
11596   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
11597   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
11598                      DAG.getConstant(0, DL, MVT::i64));
11599 }
11600 
11601 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
11602                                               SelectionDAG &DAG) const {
11603   SDValue Src = Op.getOperand(0);
11604 
11605   // Try to lower fixed length reductions to SVE.
11606   EVT SrcVT = Src.getValueType();
11607   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
11608                       Op.getOpcode() == ISD::VECREDUCE_OR ||
11609                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
11610                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
11611                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
11612                        SrcVT.getVectorElementType() == MVT::i64);
11613   if (SrcVT.isScalableVector() ||
11614       useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
11615 
11616     if (SrcVT.getVectorElementType() == MVT::i1)
11617       return LowerPredReductionToSVE(Op, DAG);
11618 
11619     switch (Op.getOpcode()) {
11620     case ISD::VECREDUCE_ADD:
11621       return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
11622     case ISD::VECREDUCE_AND:
11623       return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
11624     case ISD::VECREDUCE_OR:
11625       return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
11626     case ISD::VECREDUCE_SMAX:
11627       return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
11628     case ISD::VECREDUCE_SMIN:
11629       return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
11630     case ISD::VECREDUCE_UMAX:
11631       return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
11632     case ISD::VECREDUCE_UMIN:
11633       return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
11634     case ISD::VECREDUCE_XOR:
11635       return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
11636     case ISD::VECREDUCE_FADD:
11637       return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
11638     case ISD::VECREDUCE_FMAX:
11639       return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
11640     case ISD::VECREDUCE_FMIN:
11641       return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
11642     default:
11643       llvm_unreachable("Unhandled fixed length reduction");
11644     }
11645   }
11646 
11647   // Lower NEON reductions.
11648   SDLoc dl(Op);
11649   switch (Op.getOpcode()) {
11650   case ISD::VECREDUCE_ADD:
11651     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
11652   case ISD::VECREDUCE_SMAX:
11653     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
11654   case ISD::VECREDUCE_SMIN:
11655     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
11656   case ISD::VECREDUCE_UMAX:
11657     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
11658   case ISD::VECREDUCE_UMIN:
11659     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
11660   case ISD::VECREDUCE_FMAX: {
11661     return DAG.getNode(
11662         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
11663         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
11664         Src);
11665   }
11666   case ISD::VECREDUCE_FMIN: {
11667     return DAG.getNode(
11668         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
11669         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
11670         Src);
11671   }
11672   default:
11673     llvm_unreachable("Unhandled reduction");
11674   }
11675 }
11676 
11677 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
11678                                                     SelectionDAG &DAG) const {
11679   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
11680   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
11681     return SDValue();
11682 
11683   // LSE has an atomic load-add instruction, but not a load-sub.
11684   SDLoc dl(Op);
11685   MVT VT = Op.getSimpleValueType();
11686   SDValue RHS = Op.getOperand(2);
11687   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
11688   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
11689   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
11690                        Op.getOperand(0), Op.getOperand(1), RHS,
11691                        AN->getMemOperand());
11692 }
11693 
11694 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
11695                                                     SelectionDAG &DAG) const {
11696   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
11697   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
11698     return SDValue();
11699 
11700   // LSE has an atomic load-clear instruction, but not a load-and.
11701   SDLoc dl(Op);
11702   MVT VT = Op.getSimpleValueType();
11703   SDValue RHS = Op.getOperand(2);
11704   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
11705   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
11706   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
11707                        Op.getOperand(0), Op.getOperand(1), RHS,
11708                        AN->getMemOperand());
11709 }
11710 
11711 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
11712     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
11713   SDLoc dl(Op);
11714   EVT PtrVT = getPointerTy(DAG.getDataLayout());
11715   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
11716 
11717   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11718   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
11719   if (Subtarget->hasCustomCallingConv())
11720     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
11721 
11722   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
11723                      DAG.getConstant(4, dl, MVT::i64));
11724   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
11725   Chain =
11726       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
11727                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
11728                   DAG.getRegisterMask(Mask), Chain.getValue(1));
11729   // To match the actual intent better, we should read the output from X15 here
11730   // again (instead of potentially spilling it to the stack), but rereading Size
11731   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
11732   // here.
11733 
11734   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
11735                      DAG.getConstant(4, dl, MVT::i64));
11736   return Chain;
11737 }
11738 
11739 SDValue
11740 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11741                                                SelectionDAG &DAG) const {
11742   assert(Subtarget->isTargetWindows() &&
11743          "Only Windows alloca probing supported");
11744   SDLoc dl(Op);
11745   // Get the inputs.
11746   SDNode *Node = Op.getNode();
11747   SDValue Chain = Op.getOperand(0);
11748   SDValue Size = Op.getOperand(1);
11749   MaybeAlign Align =
11750       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
11751   EVT VT = Node->getValueType(0);
11752 
11753   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
11754           "no-stack-arg-probe")) {
11755     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
11756     Chain = SP.getValue(1);
11757     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
11758     if (Align)
11759       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11760                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
11761     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
11762     SDValue Ops[2] = {SP, Chain};
11763     return DAG.getMergeValues(Ops, dl);
11764   }
11765 
11766   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
11767 
11768   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
11769 
11770   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
11771   Chain = SP.getValue(1);
11772   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
11773   if (Align)
11774     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11775                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
11776   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
11777 
11778   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
11779                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
11780 
11781   SDValue Ops[2] = {SP, Chain};
11782   return DAG.getMergeValues(Ops, dl);
11783 }
11784 
11785 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
11786                                            SelectionDAG &DAG) const {
11787   EVT VT = Op.getValueType();
11788   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
11789 
11790   SDLoc DL(Op);
11791   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
11792   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
11793                             DL, VT);
11794 }
11795 
11796 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
11797 template <unsigned NumVecs>
11798 static bool
11799 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
11800               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
11801   Info.opc = ISD::INTRINSIC_VOID;
11802   // Retrieve EC from first vector argument.
11803   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
11804   ElementCount EC = VT.getVectorElementCount();
11805 #ifndef NDEBUG
11806   // Check the assumption that all input vectors are the same type.
11807   for (unsigned I = 0; I < NumVecs; ++I)
11808     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
11809            "Invalid type.");
11810 #endif
11811   // memVT is `NumVecs * VT`.
11812   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
11813                                 EC * NumVecs);
11814   Info.ptrVal = CI.getArgOperand(CI.arg_size() - 1);
11815   Info.offset = 0;
11816   Info.align.reset();
11817   Info.flags = MachineMemOperand::MOStore;
11818   return true;
11819 }
11820 
11821 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11822 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11823 /// specified in the intrinsic calls.
11824 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11825                                                const CallInst &I,
11826                                                MachineFunction &MF,
11827                                                unsigned Intrinsic) const {
11828   auto &DL = I.getModule()->getDataLayout();
11829   switch (Intrinsic) {
11830   case Intrinsic::aarch64_sve_st2:
11831     return setInfoSVEStN<2>(*this, DL, Info, I);
11832   case Intrinsic::aarch64_sve_st3:
11833     return setInfoSVEStN<3>(*this, DL, Info, I);
11834   case Intrinsic::aarch64_sve_st4:
11835     return setInfoSVEStN<4>(*this, DL, Info, I);
11836   case Intrinsic::aarch64_neon_ld2:
11837   case Intrinsic::aarch64_neon_ld3:
11838   case Intrinsic::aarch64_neon_ld4:
11839   case Intrinsic::aarch64_neon_ld1x2:
11840   case Intrinsic::aarch64_neon_ld1x3:
11841   case Intrinsic::aarch64_neon_ld1x4:
11842   case Intrinsic::aarch64_neon_ld2lane:
11843   case Intrinsic::aarch64_neon_ld3lane:
11844   case Intrinsic::aarch64_neon_ld4lane:
11845   case Intrinsic::aarch64_neon_ld2r:
11846   case Intrinsic::aarch64_neon_ld3r:
11847   case Intrinsic::aarch64_neon_ld4r: {
11848     Info.opc = ISD::INTRINSIC_W_CHAIN;
11849     // Conservatively set memVT to the entire set of vectors loaded.
11850     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11851     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11852     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
11853     Info.offset = 0;
11854     Info.align.reset();
11855     // volatile loads with NEON intrinsics not supported
11856     Info.flags = MachineMemOperand::MOLoad;
11857     return true;
11858   }
11859   case Intrinsic::aarch64_neon_st2:
11860   case Intrinsic::aarch64_neon_st3:
11861   case Intrinsic::aarch64_neon_st4:
11862   case Intrinsic::aarch64_neon_st1x2:
11863   case Intrinsic::aarch64_neon_st1x3:
11864   case Intrinsic::aarch64_neon_st1x4:
11865   case Intrinsic::aarch64_neon_st2lane:
11866   case Intrinsic::aarch64_neon_st3lane:
11867   case Intrinsic::aarch64_neon_st4lane: {
11868     Info.opc = ISD::INTRINSIC_VOID;
11869     // Conservatively set memVT to the entire set of vectors stored.
11870     unsigned NumElts = 0;
11871     for (const Value *Arg : I.args()) {
11872       Type *ArgTy = Arg->getType();
11873       if (!ArgTy->isVectorTy())
11874         break;
11875       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11876     }
11877     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11878     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
11879     Info.offset = 0;
11880     Info.align.reset();
11881     // volatile stores with NEON intrinsics not supported
11882     Info.flags = MachineMemOperand::MOStore;
11883     return true;
11884   }
11885   case Intrinsic::aarch64_ldaxr:
11886   case Intrinsic::aarch64_ldxr: {
11887     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11888     Info.opc = ISD::INTRINSIC_W_CHAIN;
11889     Info.memVT = MVT::getVT(PtrTy->getPointerElementType());
11890     Info.ptrVal = I.getArgOperand(0);
11891     Info.offset = 0;
11892     Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
11893     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
11894     return true;
11895   }
11896   case Intrinsic::aarch64_stlxr:
11897   case Intrinsic::aarch64_stxr: {
11898     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11899     Info.opc = ISD::INTRINSIC_W_CHAIN;
11900     Info.memVT = MVT::getVT(PtrTy->getPointerElementType());
11901     Info.ptrVal = I.getArgOperand(1);
11902     Info.offset = 0;
11903     Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
11904     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
11905     return true;
11906   }
11907   case Intrinsic::aarch64_ldaxp:
11908   case Intrinsic::aarch64_ldxp:
11909     Info.opc = ISD::INTRINSIC_W_CHAIN;
11910     Info.memVT = MVT::i128;
11911     Info.ptrVal = I.getArgOperand(0);
11912     Info.offset = 0;
11913     Info.align = Align(16);
11914     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
11915     return true;
11916   case Intrinsic::aarch64_stlxp:
11917   case Intrinsic::aarch64_stxp:
11918     Info.opc = ISD::INTRINSIC_W_CHAIN;
11919     Info.memVT = MVT::i128;
11920     Info.ptrVal = I.getArgOperand(2);
11921     Info.offset = 0;
11922     Info.align = Align(16);
11923     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
11924     return true;
11925   case Intrinsic::aarch64_sve_ldnt1: {
11926     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11927     Info.opc = ISD::INTRINSIC_W_CHAIN;
11928     Info.memVT = MVT::getVT(I.getType());
11929     Info.ptrVal = I.getArgOperand(1);
11930     Info.offset = 0;
11931     Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
11932     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
11933     return true;
11934   }
11935   case Intrinsic::aarch64_sve_stnt1: {
11936     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
11937     Info.opc = ISD::INTRINSIC_W_CHAIN;
11938     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
11939     Info.ptrVal = I.getArgOperand(2);
11940     Info.offset = 0;
11941     Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
11942     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
11943     return true;
11944   }
11945   case Intrinsic::aarch64_mops_memset_tag: {
11946     Value *Dst = I.getArgOperand(0);
11947     Value *Val = I.getArgOperand(1);
11948     Info.opc = ISD::INTRINSIC_W_CHAIN;
11949     Info.memVT = MVT::getVT(Val->getType());
11950     Info.ptrVal = Dst;
11951     Info.offset = 0;
11952     Info.align = I.getParamAlign(0).valueOrOne();
11953     Info.flags = MachineMemOperand::MOStore;
11954     // The size of the memory being operated on is unknown at this point
11955     Info.size = MemoryLocation::UnknownSize;
11956     return true;
11957   }
11958   default:
11959     break;
11960   }
11961 
11962   return false;
11963 }
11964 
11965 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
11966                                                   ISD::LoadExtType ExtTy,
11967                                                   EVT NewVT) const {
11968   // TODO: This may be worth removing. Check regression tests for diffs.
11969   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
11970     return false;
11971 
11972   // If we're reducing the load width in order to avoid having to use an extra
11973   // instruction to do extension then it's probably a good idea.
11974   if (ExtTy != ISD::NON_EXTLOAD)
11975     return true;
11976   // Don't reduce load width if it would prevent us from combining a shift into
11977   // the offset.
11978   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
11979   assert(Mem);
11980   const SDValue &Base = Mem->getBasePtr();
11981   if (Base.getOpcode() == ISD::ADD &&
11982       Base.getOperand(1).getOpcode() == ISD::SHL &&
11983       Base.getOperand(1).hasOneUse() &&
11984       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
11985     // It's unknown whether a scalable vector has a power-of-2 bitwidth.
11986     if (Mem->getMemoryVT().isScalableVector())
11987       return false;
11988     // The shift can be combined if it matches the size of the value being
11989     // loaded (and so reducing the width would make it not match).
11990     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
11991     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
11992     if (ShiftAmount == Log2_32(LoadBytes))
11993       return false;
11994   }
11995   // We have no reason to disallow reducing the load width, so allow it.
11996   return true;
11997 }
11998 
11999 // Truncations from 64-bit GPR to 32-bit GPR is free.
12000 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12001   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12002     return false;
12003   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
12004   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
12005   return NumBits1 > NumBits2;
12006 }
12007 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12008   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
12009     return false;
12010   uint64_t NumBits1 = VT1.getFixedSizeInBits();
12011   uint64_t NumBits2 = VT2.getFixedSizeInBits();
12012   return NumBits1 > NumBits2;
12013 }
12014 
12015 /// Check if it is profitable to hoist instruction in then/else to if.
12016 /// Not profitable if I and it's user can form a FMA instruction
12017 /// because we prefer FMSUB/FMADD.
12018 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
12019   if (I->getOpcode() != Instruction::FMul)
12020     return true;
12021 
12022   if (!I->hasOneUse())
12023     return true;
12024 
12025   Instruction *User = I->user_back();
12026 
12027   if (User &&
12028       !(User->getOpcode() == Instruction::FSub ||
12029         User->getOpcode() == Instruction::FAdd))
12030     return true;
12031 
12032   const TargetOptions &Options = getTargetMachine().Options;
12033   const Function *F = I->getFunction();
12034   const DataLayout &DL = F->getParent()->getDataLayout();
12035   Type *Ty = User->getOperand(0)->getType();
12036 
12037   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
12038            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
12039            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
12040             Options.UnsafeFPMath));
12041 }
12042 
12043 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
12044 // 64-bit GPR.
12045 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12046   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12047     return false;
12048   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12049   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12050   return NumBits1 == 32 && NumBits2 == 64;
12051 }
12052 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12053   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
12054     return false;
12055   unsigned NumBits1 = VT1.getSizeInBits();
12056   unsigned NumBits2 = VT2.getSizeInBits();
12057   return NumBits1 == 32 && NumBits2 == 64;
12058 }
12059 
12060 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12061   EVT VT1 = Val.getValueType();
12062   if (isZExtFree(VT1, VT2)) {
12063     return true;
12064   }
12065 
12066   if (Val.getOpcode() != ISD::LOAD)
12067     return false;
12068 
12069   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
12070   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
12071           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
12072           VT1.getSizeInBits() <= 32);
12073 }
12074 
12075 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
12076   if (isa<FPExtInst>(Ext))
12077     return false;
12078 
12079   // Vector types are not free.
12080   if (Ext->getType()->isVectorTy())
12081     return false;
12082 
12083   for (const Use &U : Ext->uses()) {
12084     // The extension is free if we can fold it with a left shift in an
12085     // addressing mode or an arithmetic operation: add, sub, and cmp.
12086 
12087     // Is there a shift?
12088     const Instruction *Instr = cast<Instruction>(U.getUser());
12089 
12090     // Is this a constant shift?
12091     switch (Instr->getOpcode()) {
12092     case Instruction::Shl:
12093       if (!isa<ConstantInt>(Instr->getOperand(1)))
12094         return false;
12095       break;
12096     case Instruction::GetElementPtr: {
12097       gep_type_iterator GTI = gep_type_begin(Instr);
12098       auto &DL = Ext->getModule()->getDataLayout();
12099       std::advance(GTI, U.getOperandNo()-1);
12100       Type *IdxTy = GTI.getIndexedType();
12101       // This extension will end up with a shift because of the scaling factor.
12102       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
12103       // Get the shift amount based on the scaling factor:
12104       // log2(sizeof(IdxTy)) - log2(8).
12105       uint64_t ShiftAmt =
12106         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
12107       // Is the constant foldable in the shift of the addressing mode?
12108       // I.e., shift amount is between 1 and 4 inclusive.
12109       if (ShiftAmt == 0 || ShiftAmt > 4)
12110         return false;
12111       break;
12112     }
12113     case Instruction::Trunc:
12114       // Check if this is a noop.
12115       // trunc(sext ty1 to ty2) to ty1.
12116       if (Instr->getType() == Ext->getOperand(0)->getType())
12117         continue;
12118       LLVM_FALLTHROUGH;
12119     default:
12120       return false;
12121     }
12122 
12123     // At this point we can use the bfm family, so this extension is free
12124     // for that use.
12125   }
12126   return true;
12127 }
12128 
12129 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
12130 /// or upper half of the vector elements.
12131 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
12132   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
12133     auto *FullTy = FullV->getType();
12134     auto *HalfTy = HalfV->getType();
12135     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
12136            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
12137   };
12138 
12139   auto extractHalf = [](Value *FullV, Value *HalfV) {
12140     auto *FullVT = cast<FixedVectorType>(FullV->getType());
12141     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
12142     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
12143   };
12144 
12145   ArrayRef<int> M1, M2;
12146   Value *S1Op1, *S2Op1;
12147   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
12148       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
12149     return false;
12150 
12151   // Check that the operands are half as wide as the result and we extract
12152   // half of the elements of the input vectors.
12153   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
12154       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
12155     return false;
12156 
12157   // Check the mask extracts either the lower or upper half of vector
12158   // elements.
12159   int M1Start = -1;
12160   int M2Start = -1;
12161   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
12162   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
12163       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
12164       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
12165     return false;
12166 
12167   return true;
12168 }
12169 
12170 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
12171 /// of the vector elements.
12172 static bool areExtractExts(Value *Ext1, Value *Ext2) {
12173   auto areExtDoubled = [](Instruction *Ext) {
12174     return Ext->getType()->getScalarSizeInBits() ==
12175            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
12176   };
12177 
12178   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
12179       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
12180       !areExtDoubled(cast<Instruction>(Ext1)) ||
12181       !areExtDoubled(cast<Instruction>(Ext2)))
12182     return false;
12183 
12184   return true;
12185 }
12186 
12187 /// Check if Op could be used with vmull_high_p64 intrinsic.
12188 static bool isOperandOfVmullHighP64(Value *Op) {
12189   Value *VectorOperand = nullptr;
12190   ConstantInt *ElementIndex = nullptr;
12191   return match(Op, m_ExtractElt(m_Value(VectorOperand),
12192                                 m_ConstantInt(ElementIndex))) &&
12193          ElementIndex->getValue() == 1 &&
12194          isa<FixedVectorType>(VectorOperand->getType()) &&
12195          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
12196 }
12197 
12198 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
12199 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
12200   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
12201 }
12202 
12203 static bool isSplatShuffle(Value *V) {
12204   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V))
12205     return is_splat(Shuf->getShuffleMask());
12206   return false;
12207 }
12208 
12209 /// Check if sinking \p I's operands to I's basic block is profitable, because
12210 /// the operands can be folded into a target instruction, e.g.
12211 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
12212 bool AArch64TargetLowering::shouldSinkOperands(
12213     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
12214   if (!I->getType()->isVectorTy())
12215     return false;
12216 
12217   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
12218     switch (II->getIntrinsicID()) {
12219     case Intrinsic::aarch64_neon_smull:
12220     case Intrinsic::aarch64_neon_umull:
12221       if (areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) {
12222         Ops.push_back(&II->getOperandUse(0));
12223         Ops.push_back(&II->getOperandUse(1));
12224         return true;
12225       }
12226       LLVM_FALLTHROUGH;
12227 
12228     case Intrinsic::aarch64_neon_sqdmull:
12229     case Intrinsic::aarch64_neon_sqdmulh:
12230     case Intrinsic::aarch64_neon_sqrdmulh:
12231       // Sink splats for index lane variants
12232       if (isSplatShuffle(II->getOperand(0)))
12233         Ops.push_back(&II->getOperandUse(0));
12234       if (isSplatShuffle(II->getOperand(1)))
12235         Ops.push_back(&II->getOperandUse(1));
12236       return !Ops.empty();
12237 
12238     case Intrinsic::aarch64_neon_pmull64:
12239       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
12240                                      II->getArgOperand(1)))
12241         return false;
12242       Ops.push_back(&II->getArgOperandUse(0));
12243       Ops.push_back(&II->getArgOperandUse(1));
12244       return true;
12245 
12246     default:
12247       return false;
12248     }
12249   }
12250 
12251   switch (I->getOpcode()) {
12252   case Instruction::Sub:
12253   case Instruction::Add: {
12254     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
12255       return false;
12256 
12257     // If the exts' operands extract either the lower or upper elements, we
12258     // can sink them too.
12259     auto Ext1 = cast<Instruction>(I->getOperand(0));
12260     auto Ext2 = cast<Instruction>(I->getOperand(1));
12261     if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
12262       Ops.push_back(&Ext1->getOperandUse(0));
12263       Ops.push_back(&Ext2->getOperandUse(0));
12264     }
12265 
12266     Ops.push_back(&I->getOperandUse(0));
12267     Ops.push_back(&I->getOperandUse(1));
12268 
12269     return true;
12270   }
12271   case Instruction::Mul: {
12272     bool IsProfitable = false;
12273     for (auto &Op : I->operands()) {
12274       // Make sure we are not already sinking this operand
12275       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
12276         continue;
12277 
12278       ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
12279       if (!Shuffle || !Shuffle->isZeroEltSplat())
12280         continue;
12281 
12282       Value *ShuffleOperand = Shuffle->getOperand(0);
12283       InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
12284       if (!Insert)
12285         continue;
12286 
12287       Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
12288       if (!OperandInstr)
12289         continue;
12290 
12291       ConstantInt *ElementConstant =
12292           dyn_cast<ConstantInt>(Insert->getOperand(2));
12293       // Check that the insertelement is inserting into element 0
12294       if (!ElementConstant || ElementConstant->getZExtValue() != 0)
12295         continue;
12296 
12297       unsigned Opcode = OperandInstr->getOpcode();
12298       if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
12299         continue;
12300 
12301       Ops.push_back(&Shuffle->getOperandUse(0));
12302       Ops.push_back(&Op);
12303       IsProfitable = true;
12304     }
12305 
12306     return IsProfitable;
12307   }
12308   default:
12309     return false;
12310   }
12311   return false;
12312 }
12313 
12314 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
12315                                           Align &RequiredAligment) const {
12316   if (!LoadedType.isSimple() ||
12317       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
12318     return false;
12319   // Cyclone supports unaligned accesses.
12320   RequiredAligment = Align(1);
12321   unsigned NumBits = LoadedType.getSizeInBits();
12322   return NumBits == 32 || NumBits == 64;
12323 }
12324 
12325 /// A helper function for determining the number of interleaved accesses we
12326 /// will generate when lowering accesses of the given type.
12327 unsigned AArch64TargetLowering::getNumInterleavedAccesses(
12328     VectorType *VecTy, const DataLayout &DL, bool UseScalable) const {
12329   unsigned VecSize = UseScalable ? Subtarget->getMinSVEVectorSizeInBits() : 128;
12330   return std::max<unsigned>(1, (DL.getTypeSizeInBits(VecTy) + 127) / VecSize);
12331 }
12332 
12333 MachineMemOperand::Flags
12334 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
12335   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
12336       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
12337     return MOStridedAccess;
12338   return MachineMemOperand::MONone;
12339 }
12340 
12341 bool AArch64TargetLowering::isLegalInterleavedAccessType(
12342     VectorType *VecTy, const DataLayout &DL, bool &UseScalable) const {
12343 
12344   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12345   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
12346   unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
12347 
12348   UseScalable = false;
12349 
12350   // Ensure the number of vector elements is greater than 1.
12351   if (NumElements < 2)
12352     return false;
12353 
12354   // Ensure the element type is legal.
12355   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
12356     return false;
12357 
12358   if (Subtarget->useSVEForFixedLengthVectors() &&
12359       (VecSize % Subtarget->getMinSVEVectorSizeInBits() == 0 ||
12360        (VecSize < Subtarget->getMinSVEVectorSizeInBits() &&
12361         isPowerOf2_32(NumElements) && VecSize > 128))) {
12362     UseScalable = true;
12363     return true;
12364   }
12365 
12366   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
12367   // 128 will be split into multiple interleaved accesses.
12368   return VecSize == 64 || VecSize % 128 == 0;
12369 }
12370 
12371 static ScalableVectorType *getSVEContainerIRType(FixedVectorType *VTy) {
12372   if (VTy->getElementType() == Type::getDoubleTy(VTy->getContext()))
12373     return ScalableVectorType::get(VTy->getElementType(), 2);
12374 
12375   if (VTy->getElementType() == Type::getFloatTy(VTy->getContext()))
12376     return ScalableVectorType::get(VTy->getElementType(), 4);
12377 
12378   if (VTy->getElementType() == Type::getBFloatTy(VTy->getContext()))
12379     return ScalableVectorType::get(VTy->getElementType(), 8);
12380 
12381   if (VTy->getElementType() == Type::getHalfTy(VTy->getContext()))
12382     return ScalableVectorType::get(VTy->getElementType(), 8);
12383 
12384   if (VTy->getElementType() == Type::getInt64Ty(VTy->getContext()))
12385     return ScalableVectorType::get(VTy->getElementType(), 2);
12386 
12387   if (VTy->getElementType() == Type::getInt32Ty(VTy->getContext()))
12388     return ScalableVectorType::get(VTy->getElementType(), 4);
12389 
12390   if (VTy->getElementType() == Type::getInt16Ty(VTy->getContext()))
12391     return ScalableVectorType::get(VTy->getElementType(), 8);
12392 
12393   if (VTy->getElementType() == Type::getInt8Ty(VTy->getContext()))
12394     return ScalableVectorType::get(VTy->getElementType(), 16);
12395 
12396   llvm_unreachable("Cannot handle input vector type");
12397 }
12398 
12399 /// Lower an interleaved load into a ldN intrinsic.
12400 ///
12401 /// E.g. Lower an interleaved load (Factor = 2):
12402 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
12403 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12404 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12405 ///
12406 ///      Into:
12407 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
12408 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
12409 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
12410 bool AArch64TargetLowering::lowerInterleavedLoad(
12411     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12412     ArrayRef<unsigned> Indices, unsigned Factor) const {
12413   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12414          "Invalid interleave factor");
12415   assert(!Shuffles.empty() && "Empty shufflevector input");
12416   assert(Shuffles.size() == Indices.size() &&
12417          "Unmatched number of shufflevectors and indices");
12418 
12419   const DataLayout &DL = LI->getModule()->getDataLayout();
12420 
12421   VectorType *VTy = Shuffles[0]->getType();
12422 
12423   // Skip if we do not have NEON and skip illegal vector types. We can
12424   // "legalize" wide vector types into multiple interleaved accesses as long as
12425   // the vector types are divisible by 128.
12426   bool UseScalable;
12427   if (!Subtarget->hasNEON() ||
12428       !isLegalInterleavedAccessType(VTy, DL, UseScalable))
12429     return false;
12430 
12431   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL, UseScalable);
12432 
12433   auto *FVTy = cast<FixedVectorType>(VTy);
12434 
12435   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12436   // load integer vectors first and then convert to pointer vectors.
12437   Type *EltTy = FVTy->getElementType();
12438   if (EltTy->isPointerTy())
12439     FVTy =
12440         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
12441 
12442   // If we're going to generate more than one load, reset the sub-vector type
12443   // to something legal.
12444   FVTy = FixedVectorType::get(FVTy->getElementType(),
12445                               FVTy->getNumElements() / NumLoads);
12446 
12447   auto *LDVTy =
12448       UseScalable ? cast<VectorType>(getSVEContainerIRType(FVTy)) : FVTy;
12449 
12450   IRBuilder<> Builder(LI);
12451 
12452   // The base address of the load.
12453   Value *BaseAddr = LI->getPointerOperand();
12454 
12455   if (NumLoads > 1) {
12456     // We will compute the pointer operand of each load from the original base
12457     // address using GEPs. Cast the base address to a pointer to the scalar
12458     // element type.
12459     BaseAddr = Builder.CreateBitCast(
12460         BaseAddr,
12461         LDVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
12462   }
12463 
12464   Type *PtrTy =
12465       UseScalable
12466           ? LDVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())
12467           : LDVTy->getPointerTo(LI->getPointerAddressSpace());
12468   Type *PredTy = VectorType::get(Type::getInt1Ty(LDVTy->getContext()),
12469                                  LDVTy->getElementCount());
12470 
12471   static const Intrinsic::ID SVELoadIntrs[3] = {
12472       Intrinsic::aarch64_sve_ld2_sret, Intrinsic::aarch64_sve_ld3_sret,
12473       Intrinsic::aarch64_sve_ld4_sret};
12474   static const Intrinsic::ID NEONLoadIntrs[3] = {Intrinsic::aarch64_neon_ld2,
12475                                                  Intrinsic::aarch64_neon_ld3,
12476                                                  Intrinsic::aarch64_neon_ld4};
12477   Function *LdNFunc;
12478   if (UseScalable)
12479     LdNFunc = Intrinsic::getDeclaration(LI->getModule(),
12480                                         SVELoadIntrs[Factor - 2], {LDVTy});
12481   else
12482     LdNFunc = Intrinsic::getDeclaration(
12483         LI->getModule(), NEONLoadIntrs[Factor - 2], {LDVTy, PtrTy});
12484 
12485   // Holds sub-vectors extracted from the load intrinsic return values. The
12486   // sub-vectors are associated with the shufflevector instructions they will
12487   // replace.
12488   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
12489 
12490   Value *PTrue = nullptr;
12491   if (UseScalable) {
12492     Optional<unsigned> PgPattern =
12493         getSVEPredPatternFromNumElements(FVTy->getNumElements());
12494     if (Subtarget->getMinSVEVectorSizeInBits() ==
12495             Subtarget->getMaxSVEVectorSizeInBits() &&
12496         Subtarget->getMinSVEVectorSizeInBits() == DL.getTypeSizeInBits(FVTy))
12497       PgPattern = AArch64SVEPredPattern::all;
12498 
12499     auto *PTruePat =
12500         ConstantInt::get(Type::getInt32Ty(LDVTy->getContext()), *PgPattern);
12501     PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue, {PredTy},
12502                                     {PTruePat});
12503   }
12504 
12505   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
12506 
12507     // If we're generating more than one load, compute the base address of
12508     // subsequent loads as an offset from the previous.
12509     if (LoadCount > 0)
12510       BaseAddr = Builder.CreateConstGEP1_32(LDVTy->getElementType(), BaseAddr,
12511                                             FVTy->getNumElements() * Factor);
12512 
12513     CallInst *LdN;
12514     if (UseScalable)
12515       LdN = Builder.CreateCall(
12516           LdNFunc, {PTrue, Builder.CreateBitCast(BaseAddr, PtrTy)}, "ldN");
12517     else
12518       LdN = Builder.CreateCall(LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy),
12519                                "ldN");
12520 
12521     // Extract and store the sub-vectors returned by the load intrinsic.
12522     for (unsigned i = 0; i < Shuffles.size(); i++) {
12523       ShuffleVectorInst *SVI = Shuffles[i];
12524       unsigned Index = Indices[i];
12525 
12526       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
12527 
12528       if (UseScalable)
12529         SubVec = Builder.CreateExtractVector(
12530             FVTy, SubVec,
12531             ConstantInt::get(Type::getInt64Ty(VTy->getContext()), 0));
12532 
12533       // Convert the integer vector to pointer vector if the element is pointer.
12534       if (EltTy->isPointerTy())
12535         SubVec = Builder.CreateIntToPtr(
12536             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
12537                                          FVTy->getNumElements()));
12538 
12539       SubVecs[SVI].push_back(SubVec);
12540     }
12541   }
12542 
12543   // Replace uses of the shufflevector instructions with the sub-vectors
12544   // returned by the load intrinsic. If a shufflevector instruction is
12545   // associated with more than one sub-vector, those sub-vectors will be
12546   // concatenated into a single wide vector.
12547   for (ShuffleVectorInst *SVI : Shuffles) {
12548     auto &SubVec = SubVecs[SVI];
12549     auto *WideVec =
12550         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
12551     SVI->replaceAllUsesWith(WideVec);
12552   }
12553 
12554   return true;
12555 }
12556 
12557 /// Lower an interleaved store into a stN intrinsic.
12558 ///
12559 /// E.g. Lower an interleaved store (Factor = 3):
12560 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12561 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12562 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
12563 ///
12564 ///      Into:
12565 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12566 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12567 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12568 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
12569 ///
12570 /// Note that the new shufflevectors will be removed and we'll only generate one
12571 /// st3 instruction in CodeGen.
12572 ///
12573 /// Example for a more general valid mask (Factor 3). Lower:
12574 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
12575 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
12576 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
12577 ///
12578 ///      Into:
12579 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
12580 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
12581 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
12582 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
12583 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
12584                                                   ShuffleVectorInst *SVI,
12585                                                   unsigned Factor) const {
12586   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12587          "Invalid interleave factor");
12588 
12589   auto *VecTy = cast<FixedVectorType>(SVI->getType());
12590   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
12591 
12592   unsigned LaneLen = VecTy->getNumElements() / Factor;
12593   Type *EltTy = VecTy->getElementType();
12594   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
12595 
12596   const DataLayout &DL = SI->getModule()->getDataLayout();
12597   bool UseScalable;
12598 
12599   // Skip if we do not have NEON and skip illegal vector types. We can
12600   // "legalize" wide vector types into multiple interleaved accesses as long as
12601   // the vector types are divisible by 128.
12602   if (!Subtarget->hasNEON() ||
12603       !isLegalInterleavedAccessType(SubVecTy, DL, UseScalable))
12604     return false;
12605 
12606   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
12607 
12608   Value *Op0 = SVI->getOperand(0);
12609   Value *Op1 = SVI->getOperand(1);
12610   IRBuilder<> Builder(SI);
12611 
12612   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12613   // vectors to integer vectors.
12614   if (EltTy->isPointerTy()) {
12615     Type *IntTy = DL.getIntPtrType(EltTy);
12616     unsigned NumOpElts =
12617         cast<FixedVectorType>(Op0->getType())->getNumElements();
12618 
12619     // Convert to the corresponding integer vector.
12620     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
12621     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12622     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12623 
12624     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
12625   }
12626 
12627   // If we're going to generate more than one store, reset the lane length
12628   // and sub-vector type to something legal.
12629   LaneLen /= NumStores;
12630   SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
12631 
12632   auto *STVTy = UseScalable ? cast<VectorType>(getSVEContainerIRType(SubVecTy))
12633                             : SubVecTy;
12634 
12635   // The base address of the store.
12636   Value *BaseAddr = SI->getPointerOperand();
12637 
12638   if (NumStores > 1) {
12639     // We will compute the pointer operand of each store from the original base
12640     // address using GEPs. Cast the base address to a pointer to the scalar
12641     // element type.
12642     BaseAddr = Builder.CreateBitCast(
12643         BaseAddr,
12644         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
12645   }
12646 
12647   auto Mask = SVI->getShuffleMask();
12648 
12649   Type *PtrTy =
12650       UseScalable
12651           ? STVTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())
12652           : STVTy->getPointerTo(SI->getPointerAddressSpace());
12653   Type *PredTy = VectorType::get(Type::getInt1Ty(STVTy->getContext()),
12654                                  STVTy->getElementCount());
12655 
12656   static const Intrinsic::ID SVEStoreIntrs[3] = {Intrinsic::aarch64_sve_st2,
12657                                                  Intrinsic::aarch64_sve_st3,
12658                                                  Intrinsic::aarch64_sve_st4};
12659   static const Intrinsic::ID NEONStoreIntrs[3] = {Intrinsic::aarch64_neon_st2,
12660                                                   Intrinsic::aarch64_neon_st3,
12661                                                   Intrinsic::aarch64_neon_st4};
12662   Function *StNFunc;
12663   if (UseScalable)
12664     StNFunc = Intrinsic::getDeclaration(SI->getModule(),
12665                                         SVEStoreIntrs[Factor - 2], {STVTy});
12666   else
12667     StNFunc = Intrinsic::getDeclaration(
12668         SI->getModule(), NEONStoreIntrs[Factor - 2], {STVTy, PtrTy});
12669 
12670   Value *PTrue = nullptr;
12671   if (UseScalable) {
12672     Optional<unsigned> PgPattern =
12673         getSVEPredPatternFromNumElements(SubVecTy->getNumElements());
12674     if (Subtarget->getMinSVEVectorSizeInBits() ==
12675             Subtarget->getMaxSVEVectorSizeInBits() &&
12676         Subtarget->getMinSVEVectorSizeInBits() ==
12677             DL.getTypeSizeInBits(SubVecTy))
12678       PgPattern = AArch64SVEPredPattern::all;
12679 
12680     auto *PTruePat =
12681         ConstantInt::get(Type::getInt32Ty(STVTy->getContext()), *PgPattern);
12682     PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue, {PredTy},
12683                                     {PTruePat});
12684   }
12685 
12686   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
12687 
12688     SmallVector<Value *, 5> Ops;
12689 
12690     // Split the shufflevector operands into sub vectors for the new stN call.
12691     for (unsigned i = 0; i < Factor; i++) {
12692       Value *Shuffle;
12693       unsigned IdxI = StoreCount * LaneLen * Factor + i;
12694       if (Mask[IdxI] >= 0) {
12695         Shuffle = Builder.CreateShuffleVector(
12696             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0));
12697       } else {
12698         unsigned StartMask = 0;
12699         for (unsigned j = 1; j < LaneLen; j++) {
12700           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
12701           if (Mask[IdxJ * Factor + IdxI] >= 0) {
12702             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
12703             break;
12704           }
12705         }
12706         // Note: Filling undef gaps with random elements is ok, since
12707         // those elements were being written anyway (with undefs).
12708         // In the case of all undefs we're defaulting to using elems from 0
12709         // Note: StartMask cannot be negative, it's checked in
12710         // isReInterleaveMask
12711         Shuffle = Builder.CreateShuffleVector(
12712             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0));
12713       }
12714 
12715       if (UseScalable)
12716         Shuffle = Builder.CreateInsertVector(
12717             STVTy, UndefValue::get(STVTy), Shuffle,
12718             ConstantInt::get(Type::getInt64Ty(STVTy->getContext()), 0));
12719 
12720       Ops.push_back(Shuffle);
12721     }
12722 
12723     if (UseScalable)
12724       Ops.push_back(PTrue);
12725 
12726     // If we generating more than one store, we compute the base address of
12727     // subsequent stores as an offset from the previous.
12728     if (StoreCount > 0)
12729       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
12730                                             BaseAddr, LaneLen * Factor);
12731 
12732     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
12733     Builder.CreateCall(StNFunc, Ops);
12734   }
12735   return true;
12736 }
12737 
12738 // Lower an SVE structured load intrinsic returning a tuple type to target
12739 // specific intrinsic taking the same input but returning a multi-result value
12740 // of the split tuple type.
12741 //
12742 // E.g. Lowering an LD3:
12743 //
12744 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
12745 //                                                    <vscale x 4 x i1> %pred,
12746 //                                                    <vscale x 4 x i32>* %addr)
12747 //
12748 //  Output DAG:
12749 //
12750 //    t0: ch = EntryToken
12751 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
12752 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
12753 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
12754 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
12755 //
12756 // This is called pre-legalization to avoid widening/splitting issues with
12757 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
12758 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
12759                                                   ArrayRef<SDValue> LoadOps,
12760                                                   EVT VT, SelectionDAG &DAG,
12761                                                   const SDLoc &DL) const {
12762   assert(VT.isScalableVector() && "Can only lower scalable vectors");
12763 
12764   unsigned N, Opcode;
12765   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
12766       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
12767       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
12768       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
12769 
12770   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
12771   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
12772          "invalid tuple vector type!");
12773 
12774   EVT SplitVT =
12775       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
12776                        VT.getVectorElementCount().divideCoefficientBy(N));
12777   assert(isTypeLegal(SplitVT));
12778 
12779   SmallVector<EVT, 5> VTs(N, SplitVT);
12780   VTs.push_back(MVT::Other); // Chain
12781   SDVTList NodeTys = DAG.getVTList(VTs);
12782 
12783   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
12784   SmallVector<SDValue, 4> PseudoLoadOps;
12785   for (unsigned I = 0; I < N; ++I)
12786     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
12787   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
12788 }
12789 
12790 EVT AArch64TargetLowering::getOptimalMemOpType(
12791     const MemOp &Op, const AttributeList &FuncAttributes) const {
12792   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
12793   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
12794   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
12795   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
12796   // taken one instruction to materialize the v2i64 zero and one store (with
12797   // restrictive addressing mode). Just do i64 stores.
12798   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
12799   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
12800     if (Op.isAligned(AlignCheck))
12801       return true;
12802     bool Fast;
12803     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
12804                                           MachineMemOperand::MONone, &Fast) &&
12805            Fast;
12806   };
12807 
12808   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
12809       AlignmentIsAcceptable(MVT::v16i8, Align(16)))
12810     return MVT::v16i8;
12811   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
12812     return MVT::f128;
12813   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
12814     return MVT::i64;
12815   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
12816     return MVT::i32;
12817   return MVT::Other;
12818 }
12819 
12820 LLT AArch64TargetLowering::getOptimalMemOpLLT(
12821     const MemOp &Op, const AttributeList &FuncAttributes) const {
12822   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
12823   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
12824   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
12825   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
12826   // taken one instruction to materialize the v2i64 zero and one store (with
12827   // restrictive addressing mode). Just do i64 stores.
12828   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
12829   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
12830     if (Op.isAligned(AlignCheck))
12831       return true;
12832     bool Fast;
12833     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
12834                                           MachineMemOperand::MONone, &Fast) &&
12835            Fast;
12836   };
12837 
12838   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
12839       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
12840     return LLT::fixed_vector(2, 64);
12841   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
12842     return LLT::scalar(128);
12843   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
12844     return LLT::scalar(64);
12845   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
12846     return LLT::scalar(32);
12847   return LLT();
12848 }
12849 
12850 // 12-bit optionally shifted immediates are legal for adds.
12851 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
12852   if (Immed == std::numeric_limits<int64_t>::min()) {
12853     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
12854                       << ": avoid UB for INT64_MIN\n");
12855     return false;
12856   }
12857   // Same encoding for add/sub, just flip the sign.
12858   Immed = std::abs(Immed);
12859   bool IsLegal = ((Immed >> 12) == 0 ||
12860                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
12861   LLVM_DEBUG(dbgs() << "Is " << Immed
12862                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
12863   return IsLegal;
12864 }
12865 
12866 // Return false to prevent folding
12867 // (mul (add x, c1), c2) -> (add (mul x, c2), c2*c1) in DAGCombine,
12868 // if the folding leads to worse code.
12869 bool AArch64TargetLowering::isMulAddWithConstProfitable(
12870     const SDValue &AddNode, const SDValue &ConstNode) const {
12871   // Let the DAGCombiner decide for vector types and large types.
12872   const EVT VT = AddNode.getValueType();
12873   if (VT.isVector() || VT.getScalarSizeInBits() > 64)
12874     return true;
12875 
12876   // It is worse if c1 is legal add immediate, while c1*c2 is not
12877   // and has to be composed by at least two instructions.
12878   const ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12879   const ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12880   const int64_t C1 = C1Node->getSExtValue();
12881   const APInt C1C2 = C1Node->getAPIntValue() * C2Node->getAPIntValue();
12882   if (!isLegalAddImmediate(C1) || isLegalAddImmediate(C1C2.getSExtValue()))
12883     return true;
12884   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
12885   AArch64_IMM::expandMOVImm(C1C2.getZExtValue(), VT.getSizeInBits(), Insn);
12886   if (Insn.size() > 1)
12887     return false;
12888 
12889   // Default to true and let the DAGCombiner decide.
12890   return true;
12891 }
12892 
12893 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
12894 // immediates is the same as for an add or a sub.
12895 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
12896   return isLegalAddImmediate(Immed);
12897 }
12898 
12899 /// isLegalAddressingMode - Return true if the addressing mode represented
12900 /// by AM is legal for this target, for a load/store of the specified type.
12901 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
12902                                                   const AddrMode &AM, Type *Ty,
12903                                                   unsigned AS, Instruction *I) const {
12904   // AArch64 has five basic addressing modes:
12905   //  reg
12906   //  reg + 9-bit signed offset
12907   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
12908   //  reg1 + reg2
12909   //  reg + SIZE_IN_BYTES * reg
12910 
12911   // No global is ever allowed as a base.
12912   if (AM.BaseGV)
12913     return false;
12914 
12915   // No reg+reg+imm addressing.
12916   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
12917     return false;
12918 
12919   // FIXME: Update this method to support scalable addressing modes.
12920   if (isa<ScalableVectorType>(Ty)) {
12921     uint64_t VecElemNumBytes =
12922         DL.getTypeSizeInBits(cast<VectorType>(Ty)->getElementType()) / 8;
12923     return AM.HasBaseReg && !AM.BaseOffs &&
12924            (AM.Scale == 0 || (uint64_t)AM.Scale == VecElemNumBytes);
12925   }
12926 
12927   // check reg + imm case:
12928   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
12929   uint64_t NumBytes = 0;
12930   if (Ty->isSized()) {
12931     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
12932     NumBytes = NumBits / 8;
12933     if (!isPowerOf2_64(NumBits))
12934       NumBytes = 0;
12935   }
12936 
12937   if (!AM.Scale) {
12938     int64_t Offset = AM.BaseOffs;
12939 
12940     // 9-bit signed offset
12941     if (isInt<9>(Offset))
12942       return true;
12943 
12944     // 12-bit unsigned offset
12945     unsigned shift = Log2_64(NumBytes);
12946     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
12947         // Must be a multiple of NumBytes (NumBytes is a power of 2)
12948         (Offset >> shift) << shift == Offset)
12949       return true;
12950     return false;
12951   }
12952 
12953   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
12954 
12955   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
12956 }
12957 
12958 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
12959   // Consider splitting large offset of struct or array.
12960   return true;
12961 }
12962 
12963 InstructionCost AArch64TargetLowering::getScalingFactorCost(
12964     const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const {
12965   // Scaling factors are not free at all.
12966   // Operands                     | Rt Latency
12967   // -------------------------------------------
12968   // Rt, [Xn, Xm]                 | 4
12969   // -------------------------------------------
12970   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
12971   // Rt, [Xn, Wm, <extend> #imm]  |
12972   if (isLegalAddressingMode(DL, AM, Ty, AS))
12973     // Scale represents reg2 * scale, thus account for 1 if
12974     // it is not equal to 0 or 1.
12975     return AM.Scale != 0 && AM.Scale != 1;
12976   return -1;
12977 }
12978 
12979 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
12980     const MachineFunction &MF, EVT VT) const {
12981   VT = VT.getScalarType();
12982 
12983   if (!VT.isSimple())
12984     return false;
12985 
12986   switch (VT.getSimpleVT().SimpleTy) {
12987   case MVT::f16:
12988     return Subtarget->hasFullFP16();
12989   case MVT::f32:
12990   case MVT::f64:
12991     return true;
12992   default:
12993     break;
12994   }
12995 
12996   return false;
12997 }
12998 
12999 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
13000                                                        Type *Ty) const {
13001   switch (Ty->getScalarType()->getTypeID()) {
13002   case Type::FloatTyID:
13003   case Type::DoubleTyID:
13004     return true;
13005   default:
13006     return false;
13007   }
13008 }
13009 
13010 bool AArch64TargetLowering::generateFMAsInMachineCombiner(
13011     EVT VT, CodeGenOpt::Level OptLevel) const {
13012   return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector() &&
13013          !useSVEForFixedLengthVectorVT(VT);
13014 }
13015 
13016 const MCPhysReg *
13017 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
13018   // LR is a callee-save register, but we must treat it as clobbered by any call
13019   // site. Hence we include LR in the scratch registers, which are in turn added
13020   // as implicit-defs for stackmaps and patchpoints.
13021   static const MCPhysReg ScratchRegs[] = {
13022     AArch64::X16, AArch64::X17, AArch64::LR, 0
13023   };
13024   return ScratchRegs;
13025 }
13026 
13027 bool
13028 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13029                                                      CombineLevel Level) const {
13030   N = N->getOperand(0).getNode();
13031   EVT VT = N->getValueType(0);
13032     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
13033     // it with shift to let it be lowered to UBFX.
13034   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
13035       isa<ConstantSDNode>(N->getOperand(1))) {
13036     uint64_t TruncMask = N->getConstantOperandVal(1);
13037     if (isMask_64(TruncMask) &&
13038       N->getOperand(0).getOpcode() == ISD::SRL &&
13039       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
13040       return false;
13041   }
13042   return true;
13043 }
13044 
13045 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13046                                                               Type *Ty) const {
13047   assert(Ty->isIntegerTy());
13048 
13049   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13050   if (BitSize == 0)
13051     return false;
13052 
13053   int64_t Val = Imm.getSExtValue();
13054   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
13055     return true;
13056 
13057   if ((int64_t)Val < 0)
13058     Val = ~Val;
13059   if (BitSize == 32)
13060     Val &= (1LL << 32) - 1;
13061 
13062   unsigned LZ = countLeadingZeros((uint64_t)Val);
13063   unsigned Shift = (63 - LZ) / 16;
13064   // MOVZ is free so return true for one or fewer MOVK.
13065   return Shift < 3;
13066 }
13067 
13068 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13069                                                     unsigned Index) const {
13070   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13071     return false;
13072 
13073   return (Index == 0 || Index == ResVT.getVectorMinNumElements());
13074 }
13075 
13076 /// Turn vector tests of the signbit in the form of:
13077 ///   xor (sra X, elt_size(X)-1), -1
13078 /// into:
13079 ///   cmge X, X, #0
13080 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
13081                                          const AArch64Subtarget *Subtarget) {
13082   EVT VT = N->getValueType(0);
13083   if (!Subtarget->hasNEON() || !VT.isVector())
13084     return SDValue();
13085 
13086   // There must be a shift right algebraic before the xor, and the xor must be a
13087   // 'not' operation.
13088   SDValue Shift = N->getOperand(0);
13089   SDValue Ones = N->getOperand(1);
13090   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
13091       !ISD::isBuildVectorAllOnes(Ones.getNode()))
13092     return SDValue();
13093 
13094   // The shift should be smearing the sign bit across each vector element.
13095   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
13096   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
13097   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
13098     return SDValue();
13099 
13100   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
13101 }
13102 
13103 // Given a vecreduce_add node, detect the below pattern and convert it to the
13104 // node sequence with UABDL, [S|U]ADB and UADDLP.
13105 //
13106 // i32 vecreduce_add(
13107 //  v16i32 abs(
13108 //    v16i32 sub(
13109 //     v16i32 [sign|zero]_extend(v16i8 a), v16i32 [sign|zero]_extend(v16i8 b))))
13110 // =================>
13111 // i32 vecreduce_add(
13112 //   v4i32 UADDLP(
13113 //     v8i16 add(
13114 //       v8i16 zext(
13115 //         v8i8 [S|U]ABD low8:v16i8 a, low8:v16i8 b
13116 //       v8i16 zext(
13117 //         v8i8 [S|U]ABD high8:v16i8 a, high8:v16i8 b
13118 static SDValue performVecReduceAddCombineWithUADDLP(SDNode *N,
13119                                                     SelectionDAG &DAG) {
13120   // Assumed i32 vecreduce_add
13121   if (N->getValueType(0) != MVT::i32)
13122     return SDValue();
13123 
13124   SDValue VecReduceOp0 = N->getOperand(0);
13125   unsigned Opcode = VecReduceOp0.getOpcode();
13126   // Assumed v16i32 abs
13127   if (Opcode != ISD::ABS || VecReduceOp0->getValueType(0) != MVT::v16i32)
13128     return SDValue();
13129 
13130   SDValue ABS = VecReduceOp0;
13131   // Assumed v16i32 sub
13132   if (ABS->getOperand(0)->getOpcode() != ISD::SUB ||
13133       ABS->getOperand(0)->getValueType(0) != MVT::v16i32)
13134     return SDValue();
13135 
13136   SDValue SUB = ABS->getOperand(0);
13137   unsigned Opcode0 = SUB->getOperand(0).getOpcode();
13138   unsigned Opcode1 = SUB->getOperand(1).getOpcode();
13139   // Assumed v16i32 type
13140   if (SUB->getOperand(0)->getValueType(0) != MVT::v16i32 ||
13141       SUB->getOperand(1)->getValueType(0) != MVT::v16i32)
13142     return SDValue();
13143 
13144   // Assumed zext or sext
13145   bool IsZExt = false;
13146   if (Opcode0 == ISD::ZERO_EXTEND && Opcode1 == ISD::ZERO_EXTEND) {
13147     IsZExt = true;
13148   } else if (Opcode0 == ISD::SIGN_EXTEND && Opcode1 == ISD::SIGN_EXTEND) {
13149     IsZExt = false;
13150   } else
13151     return SDValue();
13152 
13153   SDValue EXT0 = SUB->getOperand(0);
13154   SDValue EXT1 = SUB->getOperand(1);
13155   // Assumed zext's operand has v16i8 type
13156   if (EXT0->getOperand(0)->getValueType(0) != MVT::v16i8 ||
13157       EXT1->getOperand(0)->getValueType(0) != MVT::v16i8)
13158     return SDValue();
13159 
13160   // Pattern is dectected. Let's convert it to sequence of nodes.
13161   SDLoc DL(N);
13162 
13163   // First, create the node pattern of UABD/SABD.
13164   SDValue UABDHigh8Op0 =
13165       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
13166                   DAG.getConstant(8, DL, MVT::i64));
13167   SDValue UABDHigh8Op1 =
13168       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
13169                   DAG.getConstant(8, DL, MVT::i64));
13170   SDValue UABDHigh8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
13171                                   UABDHigh8Op0, UABDHigh8Op1);
13172   SDValue UABDL = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDHigh8);
13173 
13174   // Second, create the node pattern of UABAL.
13175   SDValue UABDLo8Op0 =
13176       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
13177                   DAG.getConstant(0, DL, MVT::i64));
13178   SDValue UABDLo8Op1 =
13179       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
13180                   DAG.getConstant(0, DL, MVT::i64));
13181   SDValue UABDLo8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
13182                                 UABDLo8Op0, UABDLo8Op1);
13183   SDValue ZExtUABD = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDLo8);
13184   SDValue UABAL = DAG.getNode(ISD::ADD, DL, MVT::v8i16, UABDL, ZExtUABD);
13185 
13186   // Third, create the node of UADDLP.
13187   SDValue UADDLP = DAG.getNode(AArch64ISD::UADDLP, DL, MVT::v4i32, UABAL);
13188 
13189   // Fourth, create the node of VECREDUCE_ADD.
13190   return DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, UADDLP);
13191 }
13192 
13193 // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce
13194 //   vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one))
13195 //   vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B))
13196 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
13197                                           const AArch64Subtarget *ST) {
13198   if (!ST->hasDotProd())
13199     return performVecReduceAddCombineWithUADDLP(N, DAG);
13200 
13201   SDValue Op0 = N->getOperand(0);
13202   if (N->getValueType(0) != MVT::i32 ||
13203       Op0.getValueType().getVectorElementType() != MVT::i32)
13204     return SDValue();
13205 
13206   unsigned ExtOpcode = Op0.getOpcode();
13207   SDValue A = Op0;
13208   SDValue B;
13209   if (ExtOpcode == ISD::MUL) {
13210     A = Op0.getOperand(0);
13211     B = Op0.getOperand(1);
13212     if (A.getOpcode() != B.getOpcode() ||
13213         A.getOperand(0).getValueType() != B.getOperand(0).getValueType())
13214       return SDValue();
13215     ExtOpcode = A.getOpcode();
13216   }
13217   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
13218     return SDValue();
13219 
13220   EVT Op0VT = A.getOperand(0).getValueType();
13221   if (Op0VT != MVT::v8i8 && Op0VT != MVT::v16i8)
13222     return SDValue();
13223 
13224   SDLoc DL(Op0);
13225   // For non-mla reductions B can be set to 1. For MLA we take the operand of
13226   // the extend B.
13227   if (!B)
13228     B = DAG.getConstant(1, DL, Op0VT);
13229   else
13230     B = B.getOperand(0);
13231 
13232   SDValue Zeros =
13233       DAG.getConstant(0, DL, Op0VT == MVT::v8i8 ? MVT::v2i32 : MVT::v4i32);
13234   auto DotOpcode =
13235       (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT;
13236   SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros,
13237                             A.getOperand(0), B);
13238   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
13239 }
13240 
13241 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
13242                                  TargetLowering::DAGCombinerInfo &DCI,
13243                                  const AArch64Subtarget *Subtarget) {
13244   if (DCI.isBeforeLegalizeOps())
13245     return SDValue();
13246 
13247   return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
13248 }
13249 
13250 SDValue
13251 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13252                                      SelectionDAG &DAG,
13253                                      SmallVectorImpl<SDNode *> &Created) const {
13254   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
13255   if (isIntDivCheap(N->getValueType(0), Attr))
13256     return SDValue(N,0); // Lower SDIV as SDIV
13257 
13258   EVT VT = N->getValueType(0);
13259 
13260   // For scalable and fixed types, mark them as cheap so we can handle it much
13261   // later. This allows us to handle larger than legal types.
13262   if (VT.isScalableVector() || Subtarget->useSVEForFixedLengthVectors())
13263     return SDValue(N, 0);
13264 
13265   // fold (sdiv X, pow2)
13266   if ((VT != MVT::i32 && VT != MVT::i64) ||
13267       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
13268     return SDValue();
13269 
13270   SDLoc DL(N);
13271   SDValue N0 = N->getOperand(0);
13272   unsigned Lg2 = Divisor.countTrailingZeros();
13273   SDValue Zero = DAG.getConstant(0, DL, VT);
13274   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
13275 
13276   // Add (N0 < 0) ? Pow2 - 1 : 0;
13277   SDValue CCVal;
13278   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
13279   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
13280   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
13281 
13282   Created.push_back(Cmp.getNode());
13283   Created.push_back(Add.getNode());
13284   Created.push_back(CSel.getNode());
13285 
13286   // Divide by pow2.
13287   SDValue SRA =
13288       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
13289 
13290   // If we're dividing by a positive value, we're done.  Otherwise, we must
13291   // negate the result.
13292   if (Divisor.isNonNegative())
13293     return SRA;
13294 
13295   Created.push_back(SRA.getNode());
13296   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
13297 }
13298 
13299 static bool IsSVECntIntrinsic(SDValue S) {
13300   switch(getIntrinsicID(S.getNode())) {
13301   default:
13302     break;
13303   case Intrinsic::aarch64_sve_cntb:
13304   case Intrinsic::aarch64_sve_cnth:
13305   case Intrinsic::aarch64_sve_cntw:
13306   case Intrinsic::aarch64_sve_cntd:
13307     return true;
13308   }
13309   return false;
13310 }
13311 
13312 /// Calculates what the pre-extend type is, based on the extension
13313 /// operation node provided by \p Extend.
13314 ///
13315 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
13316 /// pre-extend type is pulled directly from the operand, while other extend
13317 /// operations need a bit more inspection to get this information.
13318 ///
13319 /// \param Extend The SDNode from the DAG that represents the extend operation
13320 /// \param DAG The SelectionDAG hosting the \p Extend node
13321 ///
13322 /// \returns The type representing the \p Extend source type, or \p MVT::Other
13323 /// if no valid type can be determined
13324 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) {
13325   switch (Extend.getOpcode()) {
13326   case ISD::SIGN_EXTEND:
13327   case ISD::ZERO_EXTEND:
13328     return Extend.getOperand(0).getValueType();
13329   case ISD::AssertSext:
13330   case ISD::AssertZext:
13331   case ISD::SIGN_EXTEND_INREG: {
13332     VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
13333     if (!TypeNode)
13334       return MVT::Other;
13335     return TypeNode->getVT();
13336   }
13337   case ISD::AND: {
13338     ConstantSDNode *Constant =
13339         dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
13340     if (!Constant)
13341       return MVT::Other;
13342 
13343     uint32_t Mask = Constant->getZExtValue();
13344 
13345     if (Mask == UCHAR_MAX)
13346       return MVT::i8;
13347     else if (Mask == USHRT_MAX)
13348       return MVT::i16;
13349     else if (Mask == UINT_MAX)
13350       return MVT::i32;
13351 
13352     return MVT::Other;
13353   }
13354   default:
13355     return MVT::Other;
13356   }
13357 
13358   llvm_unreachable("Code path unhandled in calculatePreExtendType!");
13359 }
13360 
13361 /// Combines a dup(sext/zext) node pattern into sext/zext(dup)
13362 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
13363 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle,
13364                                                 SelectionDAG &DAG) {
13365 
13366   ShuffleVectorSDNode *ShuffleNode =
13367       dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode());
13368   if (!ShuffleNode)
13369     return SDValue();
13370 
13371   // Ensuring the mask is zero before continuing
13372   if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0)
13373     return SDValue();
13374 
13375   SDValue InsertVectorElt = VectorShuffle.getOperand(0);
13376 
13377   if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
13378     return SDValue();
13379 
13380   SDValue InsertLane = InsertVectorElt.getOperand(2);
13381   ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode());
13382   // Ensures the insert is inserting into lane 0
13383   if (!Constant || Constant->getZExtValue() != 0)
13384     return SDValue();
13385 
13386   SDValue Extend = InsertVectorElt.getOperand(1);
13387   unsigned ExtendOpcode = Extend.getOpcode();
13388 
13389   bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
13390                 ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
13391                 ExtendOpcode == ISD::AssertSext;
13392   if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
13393       ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
13394     return SDValue();
13395 
13396   EVT TargetType = VectorShuffle.getValueType();
13397   EVT PreExtendType = calculatePreExtendType(Extend, DAG);
13398 
13399   if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 &&
13400        TargetType != MVT::v2i64) ||
13401       (PreExtendType == MVT::Other))
13402     return SDValue();
13403 
13404   // Restrict valid pre-extend data type
13405   if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 &&
13406       PreExtendType != MVT::i32)
13407     return SDValue();
13408 
13409   EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType);
13410 
13411   if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount())
13412     return SDValue();
13413 
13414   if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2)
13415     return SDValue();
13416 
13417   SDLoc DL(VectorShuffle);
13418 
13419   SDValue InsertVectorNode = DAG.getNode(
13420       InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT),
13421       DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType),
13422       DAG.getConstant(0, DL, MVT::i64));
13423 
13424   std::vector<int> ShuffleMask(TargetType.getVectorNumElements());
13425 
13426   SDValue VectorShuffleNode =
13427       DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode,
13428                            DAG.getUNDEF(PreExtendVT), ShuffleMask);
13429 
13430   SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13431                                    DL, TargetType, VectorShuffleNode);
13432 
13433   return ExtendNode;
13434 }
13435 
13436 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
13437 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
13438 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
13439   // If the value type isn't a vector, none of the operands are going to be dups
13440   if (!Mul->getValueType(0).isVector())
13441     return SDValue();
13442 
13443   SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG);
13444   SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG);
13445 
13446   // Neither operands have been changed, don't make any further changes
13447   if (!Op0 && !Op1)
13448     return SDValue();
13449 
13450   SDLoc DL(Mul);
13451   return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0),
13452                      Op0 ? Op0 : Mul->getOperand(0),
13453                      Op1 ? Op1 : Mul->getOperand(1));
13454 }
13455 
13456 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
13457                                  TargetLowering::DAGCombinerInfo &DCI,
13458                                  const AArch64Subtarget *Subtarget) {
13459 
13460   if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
13461     return Ext;
13462 
13463   if (DCI.isBeforeLegalizeOps())
13464     return SDValue();
13465 
13466   // Canonicalize X*(Y+1) -> X*Y+X and (X+1)*Y -> X*Y+Y,
13467   // and in MachineCombiner pass, add+mul will be combined into madd.
13468   // Similarly, X*(1-Y) -> X - X*Y and (1-Y)*X -> X - Y*X.
13469   SDLoc DL(N);
13470   EVT VT = N->getValueType(0);
13471   SDValue N0 = N->getOperand(0);
13472   SDValue N1 = N->getOperand(1);
13473   SDValue MulOper;
13474   unsigned AddSubOpc;
13475 
13476   auto IsAddSubWith1 = [&](SDValue V) -> bool {
13477     AddSubOpc = V->getOpcode();
13478     if ((AddSubOpc == ISD::ADD || AddSubOpc == ISD::SUB) && V->hasOneUse()) {
13479       SDValue Opnd = V->getOperand(1);
13480       MulOper = V->getOperand(0);
13481       if (AddSubOpc == ISD::SUB)
13482         std::swap(Opnd, MulOper);
13483       if (auto C = dyn_cast<ConstantSDNode>(Opnd))
13484         return C->isOne();
13485     }
13486     return false;
13487   };
13488 
13489   if (IsAddSubWith1(N0)) {
13490     SDValue MulVal = DAG.getNode(ISD::MUL, DL, VT, N1, MulOper);
13491     return DAG.getNode(AddSubOpc, DL, VT, N1, MulVal);
13492   }
13493 
13494   if (IsAddSubWith1(N1)) {
13495     SDValue MulVal = DAG.getNode(ISD::MUL, DL, VT, N0, MulOper);
13496     return DAG.getNode(AddSubOpc, DL, VT, N0, MulVal);
13497   }
13498 
13499   // The below optimizations require a constant RHS.
13500   if (!isa<ConstantSDNode>(N1))
13501     return SDValue();
13502 
13503   ConstantSDNode *C = cast<ConstantSDNode>(N1);
13504   const APInt &ConstValue = C->getAPIntValue();
13505 
13506   // Allow the scaling to be folded into the `cnt` instruction by preventing
13507   // the scaling to be obscured here. This makes it easier to pattern match.
13508   if (IsSVECntIntrinsic(N0) ||
13509      (N0->getOpcode() == ISD::TRUNCATE &&
13510       (IsSVECntIntrinsic(N0->getOperand(0)))))
13511        if (ConstValue.sge(1) && ConstValue.sle(16))
13512          return SDValue();
13513 
13514   // Multiplication of a power of two plus/minus one can be done more
13515   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
13516   // future CPUs have a cheaper MADD instruction, this may need to be
13517   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
13518   // 64-bit is 5 cycles, so this is always a win.
13519   // More aggressively, some multiplications N0 * C can be lowered to
13520   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
13521   // e.g. 6=3*2=(2+1)*2.
13522   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
13523   // which equals to (1+2)*16-(1+2).
13524 
13525   // TrailingZeroes is used to test if the mul can be lowered to
13526   // shift+add+shift.
13527   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
13528   if (TrailingZeroes) {
13529     // Conservatively do not lower to shift+add+shift if the mul might be
13530     // folded into smul or umul.
13531     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
13532                             isZeroExtended(N0.getNode(), DAG)))
13533       return SDValue();
13534     // Conservatively do not lower to shift+add+shift if the mul might be
13535     // folded into madd or msub.
13536     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
13537                            N->use_begin()->getOpcode() == ISD::SUB))
13538       return SDValue();
13539   }
13540   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
13541   // and shift+add+shift.
13542   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
13543 
13544   unsigned ShiftAmt;
13545   // Is the shifted value the LHS operand of the add/sub?
13546   bool ShiftValUseIsN0 = true;
13547   // Do we need to negate the result?
13548   bool NegateResult = false;
13549 
13550   if (ConstValue.isNonNegative()) {
13551     // (mul x, 2^N + 1) => (add (shl x, N), x)
13552     // (mul x, 2^N - 1) => (sub (shl x, N), x)
13553     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
13554     APInt SCVMinus1 = ShiftedConstValue - 1;
13555     APInt CVPlus1 = ConstValue + 1;
13556     if (SCVMinus1.isPowerOf2()) {
13557       ShiftAmt = SCVMinus1.logBase2();
13558       AddSubOpc = ISD::ADD;
13559     } else if (CVPlus1.isPowerOf2()) {
13560       ShiftAmt = CVPlus1.logBase2();
13561       AddSubOpc = ISD::SUB;
13562     } else
13563       return SDValue();
13564   } else {
13565     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
13566     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
13567     APInt CVNegPlus1 = -ConstValue + 1;
13568     APInt CVNegMinus1 = -ConstValue - 1;
13569     if (CVNegPlus1.isPowerOf2()) {
13570       ShiftAmt = CVNegPlus1.logBase2();
13571       AddSubOpc = ISD::SUB;
13572       ShiftValUseIsN0 = false;
13573     } else if (CVNegMinus1.isPowerOf2()) {
13574       ShiftAmt = CVNegMinus1.logBase2();
13575       AddSubOpc = ISD::ADD;
13576       NegateResult = true;
13577     } else
13578       return SDValue();
13579   }
13580 
13581   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
13582                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
13583 
13584   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
13585   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
13586   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
13587   assert(!(NegateResult && TrailingZeroes) &&
13588          "NegateResult and TrailingZeroes cannot both be true for now.");
13589   // Negate the result.
13590   if (NegateResult)
13591     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
13592   // Shift the result.
13593   if (TrailingZeroes)
13594     return DAG.getNode(ISD::SHL, DL, VT, Res,
13595                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
13596   return Res;
13597 }
13598 
13599 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
13600                                                          SelectionDAG &DAG) {
13601   // Take advantage of vector comparisons producing 0 or -1 in each lane to
13602   // optimize away operation when it's from a constant.
13603   //
13604   // The general transformation is:
13605   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
13606   //       AND(VECTOR_CMP(x,y), constant2)
13607   //    constant2 = UNARYOP(constant)
13608 
13609   // Early exit if this isn't a vector operation, the operand of the
13610   // unary operation isn't a bitwise AND, or if the sizes of the operations
13611   // aren't the same.
13612   EVT VT = N->getValueType(0);
13613   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
13614       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
13615       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
13616     return SDValue();
13617 
13618   // Now check that the other operand of the AND is a constant. We could
13619   // make the transformation for non-constant splats as well, but it's unclear
13620   // that would be a benefit as it would not eliminate any operations, just
13621   // perform one more step in scalar code before moving to the vector unit.
13622   if (BuildVectorSDNode *BV =
13623           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
13624     // Bail out if the vector isn't a constant.
13625     if (!BV->isConstant())
13626       return SDValue();
13627 
13628     // Everything checks out. Build up the new and improved node.
13629     SDLoc DL(N);
13630     EVT IntVT = BV->getValueType(0);
13631     // Create a new constant of the appropriate type for the transformed
13632     // DAG.
13633     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
13634     // The AND node needs bitcasts to/from an integer vector type around it.
13635     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
13636     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
13637                                  N->getOperand(0)->getOperand(0), MaskConst);
13638     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
13639     return Res;
13640   }
13641 
13642   return SDValue();
13643 }
13644 
13645 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
13646                                      const AArch64Subtarget *Subtarget) {
13647   // First try to optimize away the conversion when it's conditionally from
13648   // a constant. Vectors only.
13649   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
13650     return Res;
13651 
13652   EVT VT = N->getValueType(0);
13653   if (VT != MVT::f32 && VT != MVT::f64)
13654     return SDValue();
13655 
13656   // Only optimize when the source and destination types have the same width.
13657   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
13658     return SDValue();
13659 
13660   // If the result of an integer load is only used by an integer-to-float
13661   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
13662   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
13663   SDValue N0 = N->getOperand(0);
13664   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
13665       // Do not change the width of a volatile load.
13666       !cast<LoadSDNode>(N0)->isVolatile()) {
13667     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13668     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
13669                                LN0->getPointerInfo(), LN0->getAlignment(),
13670                                LN0->getMemOperand()->getFlags());
13671 
13672     // Make sure successors of the original load stay after it by updating them
13673     // to use the new Chain.
13674     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
13675 
13676     unsigned Opcode =
13677         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
13678     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
13679   }
13680 
13681   return SDValue();
13682 }
13683 
13684 /// Fold a floating-point multiply by power of two into floating-point to
13685 /// fixed-point conversion.
13686 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
13687                                      TargetLowering::DAGCombinerInfo &DCI,
13688                                      const AArch64Subtarget *Subtarget) {
13689   if (!Subtarget->hasNEON())
13690     return SDValue();
13691 
13692   if (!N->getValueType(0).isSimple())
13693     return SDValue();
13694 
13695   SDValue Op = N->getOperand(0);
13696   if (!Op.getValueType().isSimple() || Op.getOpcode() != ISD::FMUL)
13697     return SDValue();
13698 
13699   if (!Op.getValueType().is64BitVector() && !Op.getValueType().is128BitVector())
13700     return SDValue();
13701 
13702   SDValue ConstVec = Op->getOperand(1);
13703   if (!isa<BuildVectorSDNode>(ConstVec))
13704     return SDValue();
13705 
13706   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13707   uint32_t FloatBits = FloatTy.getSizeInBits();
13708   if (FloatBits != 32 && FloatBits != 64 &&
13709       (FloatBits != 16 || !Subtarget->hasFullFP16()))
13710     return SDValue();
13711 
13712   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13713   uint32_t IntBits = IntTy.getSizeInBits();
13714   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
13715     return SDValue();
13716 
13717   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
13718   if (IntBits > FloatBits)
13719     return SDValue();
13720 
13721   BitVector UndefElements;
13722   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13723   int32_t Bits = IntBits == 64 ? 64 : 32;
13724   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
13725   if (C == -1 || C == 0 || C > Bits)
13726     return SDValue();
13727 
13728   EVT ResTy = Op.getValueType().changeVectorElementTypeToInteger();
13729   if (!DAG.getTargetLoweringInfo().isTypeLegal(ResTy))
13730     return SDValue();
13731 
13732   if (N->getOpcode() == ISD::FP_TO_SINT_SAT ||
13733       N->getOpcode() == ISD::FP_TO_UINT_SAT) {
13734     EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
13735     if (SatVT.getScalarSizeInBits() != IntBits)
13736       return SDValue();
13737   }
13738 
13739   SDLoc DL(N);
13740   bool IsSigned = (N->getOpcode() == ISD::FP_TO_SINT ||
13741                    N->getOpcode() == ISD::FP_TO_SINT_SAT);
13742   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
13743                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
13744   SDValue FixConv =
13745       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
13746                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
13747                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
13748   // We can handle smaller integers by generating an extra trunc.
13749   if (IntBits < FloatBits)
13750     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
13751 
13752   return FixConv;
13753 }
13754 
13755 /// Fold a floating-point divide by power of two into fixed-point to
13756 /// floating-point conversion.
13757 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
13758                                   TargetLowering::DAGCombinerInfo &DCI,
13759                                   const AArch64Subtarget *Subtarget) {
13760   if (!Subtarget->hasNEON())
13761     return SDValue();
13762 
13763   SDValue Op = N->getOperand(0);
13764   unsigned Opc = Op->getOpcode();
13765   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13766       !Op.getOperand(0).getValueType().isSimple() ||
13767       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
13768     return SDValue();
13769 
13770   SDValue ConstVec = N->getOperand(1);
13771   if (!isa<BuildVectorSDNode>(ConstVec))
13772     return SDValue();
13773 
13774   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13775   int32_t IntBits = IntTy.getSizeInBits();
13776   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
13777     return SDValue();
13778 
13779   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13780   int32_t FloatBits = FloatTy.getSizeInBits();
13781   if (FloatBits != 32 && FloatBits != 64)
13782     return SDValue();
13783 
13784   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
13785   if (IntBits > FloatBits)
13786     return SDValue();
13787 
13788   BitVector UndefElements;
13789   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13790   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
13791   if (C == -1 || C == 0 || C > FloatBits)
13792     return SDValue();
13793 
13794   MVT ResTy;
13795   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13796   switch (NumLanes) {
13797   default:
13798     return SDValue();
13799   case 2:
13800     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
13801     break;
13802   case 4:
13803     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
13804     break;
13805   }
13806 
13807   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
13808     return SDValue();
13809 
13810   SDLoc DL(N);
13811   SDValue ConvInput = Op.getOperand(0);
13812   bool IsSigned = Opc == ISD::SINT_TO_FP;
13813   if (IntBits < FloatBits)
13814     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
13815                             ResTy, ConvInput);
13816 
13817   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
13818                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
13819   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
13820                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
13821                      DAG.getConstant(C, DL, MVT::i32));
13822 }
13823 
13824 /// An EXTR instruction is made up of two shifts, ORed together. This helper
13825 /// searches for and classifies those shifts.
13826 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
13827                          bool &FromHi) {
13828   if (N.getOpcode() == ISD::SHL)
13829     FromHi = false;
13830   else if (N.getOpcode() == ISD::SRL)
13831     FromHi = true;
13832   else
13833     return false;
13834 
13835   if (!isa<ConstantSDNode>(N.getOperand(1)))
13836     return false;
13837 
13838   ShiftAmount = N->getConstantOperandVal(1);
13839   Src = N->getOperand(0);
13840   return true;
13841 }
13842 
13843 /// EXTR instruction extracts a contiguous chunk of bits from two existing
13844 /// registers viewed as a high/low pair. This function looks for the pattern:
13845 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
13846 /// with an EXTR. Can't quite be done in TableGen because the two immediates
13847 /// aren't independent.
13848 static SDValue tryCombineToEXTR(SDNode *N,
13849                                 TargetLowering::DAGCombinerInfo &DCI) {
13850   SelectionDAG &DAG = DCI.DAG;
13851   SDLoc DL(N);
13852   EVT VT = N->getValueType(0);
13853 
13854   assert(N->getOpcode() == ISD::OR && "Unexpected root");
13855 
13856   if (VT != MVT::i32 && VT != MVT::i64)
13857     return SDValue();
13858 
13859   SDValue LHS;
13860   uint32_t ShiftLHS = 0;
13861   bool LHSFromHi = false;
13862   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
13863     return SDValue();
13864 
13865   SDValue RHS;
13866   uint32_t ShiftRHS = 0;
13867   bool RHSFromHi = false;
13868   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
13869     return SDValue();
13870 
13871   // If they're both trying to come from the high part of the register, they're
13872   // not really an EXTR.
13873   if (LHSFromHi == RHSFromHi)
13874     return SDValue();
13875 
13876   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
13877     return SDValue();
13878 
13879   if (LHSFromHi) {
13880     std::swap(LHS, RHS);
13881     std::swap(ShiftLHS, ShiftRHS);
13882   }
13883 
13884   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
13885                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
13886 }
13887 
13888 static SDValue tryCombineToBSL(SDNode *N,
13889                                 TargetLowering::DAGCombinerInfo &DCI) {
13890   EVT VT = N->getValueType(0);
13891   SelectionDAG &DAG = DCI.DAG;
13892   SDLoc DL(N);
13893 
13894   if (!VT.isVector())
13895     return SDValue();
13896 
13897   // The combining code currently only works for NEON vectors. In particular,
13898   // it does not work for SVE when dealing with vectors wider than 128 bits.
13899   if (!VT.is64BitVector() && !VT.is128BitVector())
13900     return SDValue();
13901 
13902   SDValue N0 = N->getOperand(0);
13903   if (N0.getOpcode() != ISD::AND)
13904     return SDValue();
13905 
13906   SDValue N1 = N->getOperand(1);
13907   if (N1.getOpcode() != ISD::AND)
13908     return SDValue();
13909 
13910   // InstCombine does (not (neg a)) => (add a -1).
13911   // Try: (or (and (neg a) b) (and (add a -1) c)) => (bsl (neg a) b c)
13912   // Loop over all combinations of AND operands.
13913   for (int i = 1; i >= 0; --i) {
13914     for (int j = 1; j >= 0; --j) {
13915       SDValue O0 = N0->getOperand(i);
13916       SDValue O1 = N1->getOperand(j);
13917       SDValue Sub, Add, SubSibling, AddSibling;
13918 
13919       // Find a SUB and an ADD operand, one from each AND.
13920       if (O0.getOpcode() == ISD::SUB && O1.getOpcode() == ISD::ADD) {
13921         Sub = O0;
13922         Add = O1;
13923         SubSibling = N0->getOperand(1 - i);
13924         AddSibling = N1->getOperand(1 - j);
13925       } else if (O0.getOpcode() == ISD::ADD && O1.getOpcode() == ISD::SUB) {
13926         Add = O0;
13927         Sub = O1;
13928         AddSibling = N0->getOperand(1 - i);
13929         SubSibling = N1->getOperand(1 - j);
13930       } else
13931         continue;
13932 
13933       if (!ISD::isBuildVectorAllZeros(Sub.getOperand(0).getNode()))
13934         continue;
13935 
13936       // Constant ones is always righthand operand of the Add.
13937       if (!ISD::isBuildVectorAllOnes(Add.getOperand(1).getNode()))
13938         continue;
13939 
13940       if (Sub.getOperand(1) != Add.getOperand(0))
13941         continue;
13942 
13943       return DAG.getNode(AArch64ISD::BSP, DL, VT, Sub, SubSibling, AddSibling);
13944     }
13945   }
13946 
13947   // (or (and a b) (and (not a) c)) => (bsl a b c)
13948   // We only have to look for constant vectors here since the general, variable
13949   // case can be handled in TableGen.
13950   unsigned Bits = VT.getScalarSizeInBits();
13951   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
13952   for (int i = 1; i >= 0; --i)
13953     for (int j = 1; j >= 0; --j) {
13954       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
13955       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
13956       if (!BVN0 || !BVN1)
13957         continue;
13958 
13959       bool FoundMatch = true;
13960       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
13961         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
13962         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
13963         if (!CN0 || !CN1 ||
13964             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
13965           FoundMatch = false;
13966           break;
13967         }
13968       }
13969 
13970       if (FoundMatch)
13971         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
13972                            N0->getOperand(1 - i), N1->getOperand(1 - j));
13973     }
13974 
13975   return SDValue();
13976 }
13977 
13978 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13979                                 const AArch64Subtarget *Subtarget) {
13980   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
13981   SelectionDAG &DAG = DCI.DAG;
13982   EVT VT = N->getValueType(0);
13983 
13984   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13985     return SDValue();
13986 
13987   if (SDValue Res = tryCombineToEXTR(N, DCI))
13988     return Res;
13989 
13990   if (SDValue Res = tryCombineToBSL(N, DCI))
13991     return Res;
13992 
13993   return SDValue();
13994 }
13995 
13996 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
13997   if (!MemVT.getVectorElementType().isSimple())
13998     return false;
13999 
14000   uint64_t MaskForTy = 0ull;
14001   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
14002   case MVT::i8:
14003     MaskForTy = 0xffull;
14004     break;
14005   case MVT::i16:
14006     MaskForTy = 0xffffull;
14007     break;
14008   case MVT::i32:
14009     MaskForTy = 0xffffffffull;
14010     break;
14011   default:
14012     return false;
14013     break;
14014   }
14015 
14016   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
14017     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
14018       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
14019 
14020   return false;
14021 }
14022 
14023 static SDValue performSVEAndCombine(SDNode *N,
14024                                     TargetLowering::DAGCombinerInfo &DCI) {
14025   if (DCI.isBeforeLegalizeOps())
14026     return SDValue();
14027 
14028   SelectionDAG &DAG = DCI.DAG;
14029   SDValue Src = N->getOperand(0);
14030   unsigned Opc = Src->getOpcode();
14031 
14032   // Zero/any extend of an unsigned unpack
14033   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
14034     SDValue UnpkOp = Src->getOperand(0);
14035     SDValue Dup = N->getOperand(1);
14036 
14037     if (Dup.getOpcode() != AArch64ISD::DUP)
14038       return SDValue();
14039 
14040     SDLoc DL(N);
14041     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
14042     if (!C)
14043       return SDValue();
14044 
14045     uint64_t ExtVal = C->getZExtValue();
14046 
14047     // If the mask is fully covered by the unpack, we don't need to push
14048     // a new AND onto the operand
14049     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
14050     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
14051         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
14052         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
14053       return Src;
14054 
14055     // Truncate to prevent a DUP with an over wide constant
14056     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
14057 
14058     // Otherwise, make sure we propagate the AND to the operand
14059     // of the unpack
14060     Dup = DAG.getNode(AArch64ISD::DUP, DL,
14061                       UnpkOp->getValueType(0),
14062                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
14063 
14064     SDValue And = DAG.getNode(ISD::AND, DL,
14065                               UnpkOp->getValueType(0), UnpkOp, Dup);
14066 
14067     return DAG.getNode(Opc, DL, N->getValueType(0), And);
14068   }
14069 
14070   if (!EnableCombineMGatherIntrinsics)
14071     return SDValue();
14072 
14073   SDValue Mask = N->getOperand(1);
14074 
14075   if (!Src.hasOneUse())
14076     return SDValue();
14077 
14078   EVT MemVT;
14079 
14080   // SVE load instructions perform an implicit zero-extend, which makes them
14081   // perfect candidates for combining.
14082   switch (Opc) {
14083   case AArch64ISD::LD1_MERGE_ZERO:
14084   case AArch64ISD::LDNF1_MERGE_ZERO:
14085   case AArch64ISD::LDFF1_MERGE_ZERO:
14086     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
14087     break;
14088   case AArch64ISD::GLD1_MERGE_ZERO:
14089   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
14090   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
14091   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
14092   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
14093   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
14094   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
14095   case AArch64ISD::GLDFF1_MERGE_ZERO:
14096   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
14097   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
14098   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
14099   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
14100   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
14101   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
14102   case AArch64ISD::GLDNT1_MERGE_ZERO:
14103     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
14104     break;
14105   default:
14106     return SDValue();
14107   }
14108 
14109   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
14110     return Src;
14111 
14112   return SDValue();
14113 }
14114 
14115 static SDValue performANDCombine(SDNode *N,
14116                                  TargetLowering::DAGCombinerInfo &DCI) {
14117   SelectionDAG &DAG = DCI.DAG;
14118   SDValue LHS = N->getOperand(0);
14119   EVT VT = N->getValueType(0);
14120   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
14121     return SDValue();
14122 
14123   if (VT.isScalableVector())
14124     return performSVEAndCombine(N, DCI);
14125 
14126   // The combining code below works only for NEON vectors. In particular, it
14127   // does not work for SVE when dealing with vectors wider than 128 bits.
14128   if (!(VT.is64BitVector() || VT.is128BitVector()))
14129     return SDValue();
14130 
14131   BuildVectorSDNode *BVN =
14132       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
14133   if (!BVN)
14134     return SDValue();
14135 
14136   // AND does not accept an immediate, so check if we can use a BIC immediate
14137   // instruction instead. We do this here instead of using a (and x, (mvni imm))
14138   // pattern in isel, because some immediates may be lowered to the preferred
14139   // (and x, (movi imm)) form, even though an mvni representation also exists.
14140   APInt DefBits(VT.getSizeInBits(), 0);
14141   APInt UndefBits(VT.getSizeInBits(), 0);
14142   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
14143     SDValue NewOp;
14144 
14145     DefBits = ~DefBits;
14146     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
14147                                     DefBits, &LHS)) ||
14148         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
14149                                     DefBits, &LHS)))
14150       return NewOp;
14151 
14152     UndefBits = ~UndefBits;
14153     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
14154                                     UndefBits, &LHS)) ||
14155         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
14156                                     UndefBits, &LHS)))
14157       return NewOp;
14158   }
14159 
14160   return SDValue();
14161 }
14162 
14163 // Attempt to form urhadd(OpA, OpB) from
14164 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
14165 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
14166 // The original form of the first expression is
14167 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
14168 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
14169 // Before this function is called the srl will have been lowered to
14170 // AArch64ISD::VLSHR.
14171 // This pass can also recognize signed variants of the patterns that use sign
14172 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
14173 // shadd(OpA, OpB) from them.
14174 static SDValue
14175 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14176                              SelectionDAG &DAG) {
14177   EVT VT = N->getValueType(0);
14178 
14179   // Since we are looking for a right shift by a constant value of 1 and we are
14180   // operating on types at least 16 bits in length (sign/zero extended OpA and
14181   // OpB, which are at least 8 bits), it follows that the truncate will always
14182   // discard the shifted-in bit and therefore the right shift will be logical
14183   // regardless of the signedness of OpA and OpB.
14184   SDValue Shift = N->getOperand(0);
14185   if (Shift.getOpcode() != AArch64ISD::VLSHR)
14186     return SDValue();
14187 
14188   // Is the right shift using an immediate value of 1?
14189   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
14190   if (ShiftAmount != 1)
14191     return SDValue();
14192 
14193   SDValue ExtendOpA, ExtendOpB;
14194   SDValue ShiftOp0 = Shift.getOperand(0);
14195   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
14196   if (ShiftOp0Opc == ISD::SUB) {
14197 
14198     SDValue Xor = ShiftOp0.getOperand(1);
14199     if (Xor.getOpcode() != ISD::XOR)
14200       return SDValue();
14201 
14202     // Is the XOR using a constant amount of all ones in the right hand side?
14203     uint64_t C;
14204     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
14205       return SDValue();
14206 
14207     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
14208     APInt CAsAPInt(ElemSizeInBits, C);
14209     if (CAsAPInt != APInt::getAllOnes(ElemSizeInBits))
14210       return SDValue();
14211 
14212     ExtendOpA = Xor.getOperand(0);
14213     ExtendOpB = ShiftOp0.getOperand(0);
14214   } else if (ShiftOp0Opc == ISD::ADD) {
14215     ExtendOpA = ShiftOp0.getOperand(0);
14216     ExtendOpB = ShiftOp0.getOperand(1);
14217   } else
14218     return SDValue();
14219 
14220   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
14221   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
14222   if (!(ExtendOpAOpc == ExtendOpBOpc &&
14223         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
14224     return SDValue();
14225 
14226   // Is the result of the right shift being truncated to the same value type as
14227   // the original operands, OpA and OpB?
14228   SDValue OpA = ExtendOpA.getOperand(0);
14229   SDValue OpB = ExtendOpB.getOperand(0);
14230   EVT OpAVT = OpA.getValueType();
14231   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
14232   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
14233     return SDValue();
14234 
14235   SDLoc DL(N);
14236   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
14237   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
14238   unsigned HADDOpc = IsSignExtend
14239                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
14240                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
14241   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
14242 
14243   return ResultHADD;
14244 }
14245 
14246 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
14247   switch (Opcode) {
14248   case ISD::FADD:
14249     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
14250   case ISD::ADD:
14251     return VT == MVT::i64;
14252   default:
14253     return false;
14254   }
14255 }
14256 
14257 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
14258   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
14259   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
14260 
14261   EVT VT = N->getValueType(0);
14262   const bool FullFP16 =
14263       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
14264 
14265   // Rewrite for pairwise fadd pattern
14266   //   (f32 (extract_vector_elt
14267   //           (fadd (vXf32 Other)
14268   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
14269   // ->
14270   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
14271   //              (extract_vector_elt (vXf32 Other) 1))
14272   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
14273       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
14274     SDLoc DL(N0);
14275     SDValue N00 = N0->getOperand(0);
14276     SDValue N01 = N0->getOperand(1);
14277 
14278     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
14279     SDValue Other = N00;
14280 
14281     // And handle the commutative case.
14282     if (!Shuffle) {
14283       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
14284       Other = N01;
14285     }
14286 
14287     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
14288         Other == Shuffle->getOperand(0)) {
14289       return DAG.getNode(N0->getOpcode(), DL, VT,
14290                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
14291                                      DAG.getConstant(0, DL, MVT::i64)),
14292                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
14293                                      DAG.getConstant(1, DL, MVT::i64)));
14294     }
14295   }
14296 
14297   return SDValue();
14298 }
14299 
14300 static SDValue performConcatVectorsCombine(SDNode *N,
14301                                            TargetLowering::DAGCombinerInfo &DCI,
14302                                            SelectionDAG &DAG) {
14303   SDLoc dl(N);
14304   EVT VT = N->getValueType(0);
14305   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
14306   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
14307 
14308   if (VT.isScalableVector())
14309     return SDValue();
14310 
14311   // Optimize concat_vectors of truncated vectors, where the intermediate
14312   // type is illegal, to avoid said illegality,  e.g.,
14313   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
14314   //                          (v2i16 (truncate (v2i64)))))
14315   // ->
14316   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
14317   //                                    (v4i32 (bitcast (v2i64))),
14318   //                                    <0, 2, 4, 6>)))
14319   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
14320   // on both input and result type, so we might generate worse code.
14321   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
14322   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
14323       N1Opc == ISD::TRUNCATE) {
14324     SDValue N00 = N0->getOperand(0);
14325     SDValue N10 = N1->getOperand(0);
14326     EVT N00VT = N00.getValueType();
14327 
14328     if (N00VT == N10.getValueType() &&
14329         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
14330         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
14331       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
14332       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
14333       for (size_t i = 0; i < Mask.size(); ++i)
14334         Mask[i] = i * 2;
14335       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14336                          DAG.getVectorShuffle(
14337                              MidVT, dl,
14338                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
14339                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
14340     }
14341   }
14342 
14343   // Wait 'til after everything is legalized to try this. That way we have
14344   // legal vector types and such.
14345   if (DCI.isBeforeLegalizeOps())
14346     return SDValue();
14347 
14348   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
14349   // subvectors from the same original vectors. Combine these into a single
14350   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
14351   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
14352   //                                        extract_subvector (v16i8 OpB,
14353   //                                        <0>))),
14354   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
14355   //                                        extract_subvector (v16i8 OpB,
14356   //                                        <8>)))))
14357   // ->
14358   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
14359   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
14360       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
14361        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
14362     SDValue N00 = N0->getOperand(0);
14363     SDValue N01 = N0->getOperand(1);
14364     SDValue N10 = N1->getOperand(0);
14365     SDValue N11 = N1->getOperand(1);
14366 
14367     EVT N00VT = N00.getValueType();
14368     EVT N10VT = N10.getValueType();
14369 
14370     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
14371         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
14372         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
14373         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
14374       SDValue N00Source = N00->getOperand(0);
14375       SDValue N01Source = N01->getOperand(0);
14376       SDValue N10Source = N10->getOperand(0);
14377       SDValue N11Source = N11->getOperand(0);
14378 
14379       if (N00Source == N10Source && N01Source == N11Source &&
14380           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
14381         assert(N0.getValueType() == N1.getValueType());
14382 
14383         uint64_t N00Index = N00.getConstantOperandVal(1);
14384         uint64_t N01Index = N01.getConstantOperandVal(1);
14385         uint64_t N10Index = N10.getConstantOperandVal(1);
14386         uint64_t N11Index = N11.getConstantOperandVal(1);
14387 
14388         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
14389             N10Index == N00VT.getVectorNumElements())
14390           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
14391       }
14392     }
14393   }
14394 
14395   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
14396   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
14397   // canonicalise to that.
14398   if (N->getNumOperands() == 2 && N0 == N1 && VT.getVectorNumElements() == 2) {
14399     assert(VT.getScalarSizeInBits() == 64);
14400     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
14401                        DAG.getConstant(0, dl, MVT::i64));
14402   }
14403 
14404   // Canonicalise concat_vectors so that the right-hand vector has as few
14405   // bit-casts as possible before its real operation. The primary matching
14406   // destination for these operations will be the narrowing "2" instructions,
14407   // which depend on the operation being performed on this right-hand vector.
14408   // For example,
14409   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
14410   // becomes
14411   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
14412 
14413   if (N->getNumOperands() != 2 || N1Opc != ISD::BITCAST)
14414     return SDValue();
14415   SDValue RHS = N1->getOperand(0);
14416   MVT RHSTy = RHS.getValueType().getSimpleVT();
14417   // If the RHS is not a vector, this is not the pattern we're looking for.
14418   if (!RHSTy.isVector())
14419     return SDValue();
14420 
14421   LLVM_DEBUG(
14422       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
14423 
14424   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
14425                                   RHSTy.getVectorNumElements() * 2);
14426   return DAG.getNode(ISD::BITCAST, dl, VT,
14427                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
14428                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
14429                                  RHS));
14430 }
14431 
14432 static SDValue
14433 performInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14434                               SelectionDAG &DAG) {
14435   SDLoc DL(N);
14436   SDValue Vec = N->getOperand(0);
14437   SDValue SubVec = N->getOperand(1);
14438   uint64_t IdxVal = N->getConstantOperandVal(2);
14439   EVT VecVT = Vec.getValueType();
14440   EVT SubVT = SubVec.getValueType();
14441 
14442   // Only do this for legal fixed vector types.
14443   if (!VecVT.isFixedLengthVector() ||
14444       !DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
14445       !DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
14446     return SDValue();
14447 
14448   // Ignore widening patterns.
14449   if (IdxVal == 0 && Vec.isUndef())
14450     return SDValue();
14451 
14452   // Subvector must be half the width and an "aligned" insertion.
14453   unsigned NumSubElts = SubVT.getVectorNumElements();
14454   if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
14455       (IdxVal != 0 && IdxVal != NumSubElts))
14456     return SDValue();
14457 
14458   // Fold insert_subvector -> concat_vectors
14459   // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
14460   // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
14461   SDValue Lo, Hi;
14462   if (IdxVal == 0) {
14463     Lo = SubVec;
14464     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
14465                      DAG.getVectorIdxConstant(NumSubElts, DL));
14466   } else {
14467     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
14468                      DAG.getVectorIdxConstant(0, DL));
14469     Hi = SubVec;
14470   }
14471   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
14472 }
14473 
14474 static SDValue tryCombineFixedPointConvert(SDNode *N,
14475                                            TargetLowering::DAGCombinerInfo &DCI,
14476                                            SelectionDAG &DAG) {
14477   // Wait until after everything is legalized to try this. That way we have
14478   // legal vector types and such.
14479   if (DCI.isBeforeLegalizeOps())
14480     return SDValue();
14481   // Transform a scalar conversion of a value from a lane extract into a
14482   // lane extract of a vector conversion. E.g., from foo1 to foo2:
14483   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
14484   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
14485   //
14486   // The second form interacts better with instruction selection and the
14487   // register allocator to avoid cross-class register copies that aren't
14488   // coalescable due to a lane reference.
14489 
14490   // Check the operand and see if it originates from a lane extract.
14491   SDValue Op1 = N->getOperand(1);
14492   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14493     // Yep, no additional predication needed. Perform the transform.
14494     SDValue IID = N->getOperand(0);
14495     SDValue Shift = N->getOperand(2);
14496     SDValue Vec = Op1.getOperand(0);
14497     SDValue Lane = Op1.getOperand(1);
14498     EVT ResTy = N->getValueType(0);
14499     EVT VecResTy;
14500     SDLoc DL(N);
14501 
14502     // The vector width should be 128 bits by the time we get here, even
14503     // if it started as 64 bits (the extract_vector handling will have
14504     // done so).
14505     assert(Vec.getValueSizeInBits() == 128 &&
14506            "unexpected vector size on extract_vector_elt!");
14507     if (Vec.getValueType() == MVT::v4i32)
14508       VecResTy = MVT::v4f32;
14509     else if (Vec.getValueType() == MVT::v2i64)
14510       VecResTy = MVT::v2f64;
14511     else
14512       llvm_unreachable("unexpected vector type!");
14513 
14514     SDValue Convert =
14515         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
14516     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
14517   }
14518   return SDValue();
14519 }
14520 
14521 // AArch64 high-vector "long" operations are formed by performing the non-high
14522 // version on an extract_subvector of each operand which gets the high half:
14523 //
14524 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
14525 //
14526 // However, there are cases which don't have an extract_high explicitly, but
14527 // have another operation that can be made compatible with one for free. For
14528 // example:
14529 //
14530 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
14531 //
14532 // This routine does the actual conversion of such DUPs, once outer routines
14533 // have determined that everything else is in order.
14534 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
14535 // similarly here.
14536 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
14537   switch (N.getOpcode()) {
14538   case AArch64ISD::DUP:
14539   case AArch64ISD::DUPLANE8:
14540   case AArch64ISD::DUPLANE16:
14541   case AArch64ISD::DUPLANE32:
14542   case AArch64ISD::DUPLANE64:
14543   case AArch64ISD::MOVI:
14544   case AArch64ISD::MOVIshift:
14545   case AArch64ISD::MOVIedit:
14546   case AArch64ISD::MOVImsl:
14547   case AArch64ISD::MVNIshift:
14548   case AArch64ISD::MVNImsl:
14549     break;
14550   default:
14551     // FMOV could be supported, but isn't very useful, as it would only occur
14552     // if you passed a bitcast' floating point immediate to an eligible long
14553     // integer op (addl, smull, ...).
14554     return SDValue();
14555   }
14556 
14557   MVT NarrowTy = N.getSimpleValueType();
14558   if (!NarrowTy.is64BitVector())
14559     return SDValue();
14560 
14561   MVT ElementTy = NarrowTy.getVectorElementType();
14562   unsigned NumElems = NarrowTy.getVectorNumElements();
14563   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
14564 
14565   SDLoc dl(N);
14566   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
14567                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
14568                      DAG.getConstant(NumElems, dl, MVT::i64));
14569 }
14570 
14571 static bool isEssentiallyExtractHighSubvector(SDValue N) {
14572   if (N.getOpcode() == ISD::BITCAST)
14573     N = N.getOperand(0);
14574   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14575     return false;
14576   if (N.getOperand(0).getValueType().isScalableVector())
14577     return false;
14578   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
14579          N.getOperand(0).getValueType().getVectorNumElements() / 2;
14580 }
14581 
14582 /// Helper structure to keep track of ISD::SET_CC operands.
14583 struct GenericSetCCInfo {
14584   const SDValue *Opnd0;
14585   const SDValue *Opnd1;
14586   ISD::CondCode CC;
14587 };
14588 
14589 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
14590 struct AArch64SetCCInfo {
14591   const SDValue *Cmp;
14592   AArch64CC::CondCode CC;
14593 };
14594 
14595 /// Helper structure to keep track of SetCC information.
14596 union SetCCInfo {
14597   GenericSetCCInfo Generic;
14598   AArch64SetCCInfo AArch64;
14599 };
14600 
14601 /// Helper structure to be able to read SetCC information.  If set to
14602 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
14603 /// GenericSetCCInfo.
14604 struct SetCCInfoAndKind {
14605   SetCCInfo Info;
14606   bool IsAArch64;
14607 };
14608 
14609 /// Check whether or not \p Op is a SET_CC operation, either a generic or
14610 /// an
14611 /// AArch64 lowered one.
14612 /// \p SetCCInfo is filled accordingly.
14613 /// \post SetCCInfo is meanginfull only when this function returns true.
14614 /// \return True when Op is a kind of SET_CC operation.
14615 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
14616   // If this is a setcc, this is straight forward.
14617   if (Op.getOpcode() == ISD::SETCC) {
14618     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
14619     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
14620     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14621     SetCCInfo.IsAArch64 = false;
14622     return true;
14623   }
14624   // Otherwise, check if this is a matching csel instruction.
14625   // In other words:
14626   // - csel 1, 0, cc
14627   // - csel 0, 1, !cc
14628   if (Op.getOpcode() != AArch64ISD::CSEL)
14629     return false;
14630   // Set the information about the operands.
14631   // TODO: we want the operands of the Cmp not the csel
14632   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
14633   SetCCInfo.IsAArch64 = true;
14634   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
14635       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14636 
14637   // Check that the operands matches the constraints:
14638   // (1) Both operands must be constants.
14639   // (2) One must be 1 and the other must be 0.
14640   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
14641   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14642 
14643   // Check (1).
14644   if (!TValue || !FValue)
14645     return false;
14646 
14647   // Check (2).
14648   if (!TValue->isOne()) {
14649     // Update the comparison when we are interested in !cc.
14650     std::swap(TValue, FValue);
14651     SetCCInfo.Info.AArch64.CC =
14652         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
14653   }
14654   return TValue->isOne() && FValue->isZero();
14655 }
14656 
14657 // Returns true if Op is setcc or zext of setcc.
14658 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
14659   if (isSetCC(Op, Info))
14660     return true;
14661   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
14662     isSetCC(Op->getOperand(0), Info));
14663 }
14664 
14665 // The folding we want to perform is:
14666 // (add x, [zext] (setcc cc ...) )
14667 //   -->
14668 // (csel x, (add x, 1), !cc ...)
14669 //
14670 // The latter will get matched to a CSINC instruction.
14671 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
14672   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
14673   SDValue LHS = Op->getOperand(0);
14674   SDValue RHS = Op->getOperand(1);
14675   SetCCInfoAndKind InfoAndKind;
14676 
14677   // If both operands are a SET_CC, then we don't want to perform this
14678   // folding and create another csel as this results in more instructions
14679   // (and higher register usage).
14680   if (isSetCCOrZExtSetCC(LHS, InfoAndKind) &&
14681       isSetCCOrZExtSetCC(RHS, InfoAndKind))
14682     return SDValue();
14683 
14684   // If neither operand is a SET_CC, give up.
14685   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
14686     std::swap(LHS, RHS);
14687     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
14688       return SDValue();
14689   }
14690 
14691   // FIXME: This could be generatized to work for FP comparisons.
14692   EVT CmpVT = InfoAndKind.IsAArch64
14693                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
14694                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
14695   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
14696     return SDValue();
14697 
14698   SDValue CCVal;
14699   SDValue Cmp;
14700   SDLoc dl(Op);
14701   if (InfoAndKind.IsAArch64) {
14702     CCVal = DAG.getConstant(
14703         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
14704         MVT::i32);
14705     Cmp = *InfoAndKind.Info.AArch64.Cmp;
14706   } else
14707     Cmp = getAArch64Cmp(
14708         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
14709         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
14710         dl);
14711 
14712   EVT VT = Op->getValueType(0);
14713   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
14714   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
14715 }
14716 
14717 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
14718 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
14719   EVT VT = N->getValueType(0);
14720   // Only scalar integer and vector types.
14721   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
14722     return SDValue();
14723 
14724   SDValue LHS = N->getOperand(0);
14725   SDValue RHS = N->getOperand(1);
14726   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14727       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
14728     return SDValue();
14729 
14730   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14731   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
14732   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isZero())
14733     return SDValue();
14734 
14735   SDValue Op1 = LHS->getOperand(0);
14736   SDValue Op2 = RHS->getOperand(0);
14737   EVT OpVT1 = Op1.getValueType();
14738   EVT OpVT2 = Op2.getValueType();
14739   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
14740       Op2.getOpcode() != AArch64ISD::UADDV ||
14741       OpVT1.getVectorElementType() != VT)
14742     return SDValue();
14743 
14744   SDValue Val1 = Op1.getOperand(0);
14745   SDValue Val2 = Op2.getOperand(0);
14746   EVT ValVT = Val1->getValueType(0);
14747   SDLoc DL(N);
14748   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
14749   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14750                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
14751                      DAG.getConstant(0, DL, MVT::i64));
14752 }
14753 
14754 // ADD(UDOT(zero, x, y), A) -->  UDOT(A, x, y)
14755 static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) {
14756   EVT VT = N->getValueType(0);
14757   if (N->getOpcode() != ISD::ADD)
14758     return SDValue();
14759 
14760   SDValue Dot = N->getOperand(0);
14761   SDValue A = N->getOperand(1);
14762   // Handle commutivity
14763   auto isZeroDot = [](SDValue Dot) {
14764     return (Dot.getOpcode() == AArch64ISD::UDOT ||
14765             Dot.getOpcode() == AArch64ISD::SDOT) &&
14766            isZerosVector(Dot.getOperand(0).getNode());
14767   };
14768   if (!isZeroDot(Dot))
14769     std::swap(Dot, A);
14770   if (!isZeroDot(Dot))
14771     return SDValue();
14772 
14773   return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1),
14774                      Dot.getOperand(2));
14775 }
14776 
14777 // The basic add/sub long vector instructions have variants with "2" on the end
14778 // which act on the high-half of their inputs. They are normally matched by
14779 // patterns like:
14780 //
14781 // (add (zeroext (extract_high LHS)),
14782 //      (zeroext (extract_high RHS)))
14783 // -> uaddl2 vD, vN, vM
14784 //
14785 // However, if one of the extracts is something like a duplicate, this
14786 // instruction can still be used profitably. This function puts the DAG into a
14787 // more appropriate form for those patterns to trigger.
14788 static SDValue performAddSubLongCombine(SDNode *N,
14789                                         TargetLowering::DAGCombinerInfo &DCI,
14790                                         SelectionDAG &DAG) {
14791   if (DCI.isBeforeLegalizeOps())
14792     return SDValue();
14793 
14794   MVT VT = N->getSimpleValueType(0);
14795   if (!VT.is128BitVector()) {
14796     if (N->getOpcode() == ISD::ADD)
14797       return performSetccAddFolding(N, DAG);
14798     return SDValue();
14799   }
14800 
14801   // Make sure both branches are extended in the same way.
14802   SDValue LHS = N->getOperand(0);
14803   SDValue RHS = N->getOperand(1);
14804   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
14805        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
14806       LHS.getOpcode() != RHS.getOpcode())
14807     return SDValue();
14808 
14809   unsigned ExtType = LHS.getOpcode();
14810 
14811   // It's not worth doing if at least one of the inputs isn't already an
14812   // extract, but we don't know which it'll be so we have to try both.
14813   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
14814     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
14815     if (!RHS.getNode())
14816       return SDValue();
14817 
14818     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
14819   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
14820     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
14821     if (!LHS.getNode())
14822       return SDValue();
14823 
14824     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
14825   }
14826 
14827   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
14828 }
14829 
14830 static SDValue performAddSubCombine(SDNode *N,
14831                                     TargetLowering::DAGCombinerInfo &DCI,
14832                                     SelectionDAG &DAG) {
14833   // Try to change sum of two reductions.
14834   if (SDValue Val = performUADDVCombine(N, DAG))
14835     return Val;
14836   if (SDValue Val = performAddDotCombine(N, DAG))
14837     return Val;
14838 
14839   return performAddSubLongCombine(N, DCI, DAG);
14840 }
14841 
14842 // Massage DAGs which we can use the high-half "long" operations on into
14843 // something isel will recognize better. E.g.
14844 //
14845 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
14846 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
14847 //                     (extract_high (v2i64 (dup128 scalar)))))
14848 //
14849 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
14850                                        TargetLowering::DAGCombinerInfo &DCI,
14851                                        SelectionDAG &DAG) {
14852   if (DCI.isBeforeLegalizeOps())
14853     return SDValue();
14854 
14855   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
14856   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
14857   assert(LHS.getValueType().is64BitVector() &&
14858          RHS.getValueType().is64BitVector() &&
14859          "unexpected shape for long operation");
14860 
14861   // Either node could be a DUP, but it's not worth doing both of them (you'd
14862   // just as well use the non-high version) so look for a corresponding extract
14863   // operation on the other "wing".
14864   if (isEssentiallyExtractHighSubvector(LHS)) {
14865     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
14866     if (!RHS.getNode())
14867       return SDValue();
14868   } else if (isEssentiallyExtractHighSubvector(RHS)) {
14869     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
14870     if (!LHS.getNode())
14871       return SDValue();
14872   }
14873 
14874   if (IID == Intrinsic::not_intrinsic)
14875     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
14876 
14877   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
14878                      N->getOperand(0), LHS, RHS);
14879 }
14880 
14881 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
14882   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
14883   unsigned ElemBits = ElemTy.getSizeInBits();
14884 
14885   int64_t ShiftAmount;
14886   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
14887     APInt SplatValue, SplatUndef;
14888     unsigned SplatBitSize;
14889     bool HasAnyUndefs;
14890     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
14891                               HasAnyUndefs, ElemBits) ||
14892         SplatBitSize != ElemBits)
14893       return SDValue();
14894 
14895     ShiftAmount = SplatValue.getSExtValue();
14896   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14897     ShiftAmount = CVN->getSExtValue();
14898   } else
14899     return SDValue();
14900 
14901   unsigned Opcode;
14902   bool IsRightShift;
14903   switch (IID) {
14904   default:
14905     llvm_unreachable("Unknown shift intrinsic");
14906   case Intrinsic::aarch64_neon_sqshl:
14907     Opcode = AArch64ISD::SQSHL_I;
14908     IsRightShift = false;
14909     break;
14910   case Intrinsic::aarch64_neon_uqshl:
14911     Opcode = AArch64ISD::UQSHL_I;
14912     IsRightShift = false;
14913     break;
14914   case Intrinsic::aarch64_neon_srshl:
14915     Opcode = AArch64ISD::SRSHR_I;
14916     IsRightShift = true;
14917     break;
14918   case Intrinsic::aarch64_neon_urshl:
14919     Opcode = AArch64ISD::URSHR_I;
14920     IsRightShift = true;
14921     break;
14922   case Intrinsic::aarch64_neon_sqshlu:
14923     Opcode = AArch64ISD::SQSHLU_I;
14924     IsRightShift = false;
14925     break;
14926   case Intrinsic::aarch64_neon_sshl:
14927   case Intrinsic::aarch64_neon_ushl:
14928     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
14929     // left shift for positive shift amounts. Below, we only replace the current
14930     // node with VSHL, if this condition is met.
14931     Opcode = AArch64ISD::VSHL;
14932     IsRightShift = false;
14933     break;
14934   }
14935 
14936   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
14937     SDLoc dl(N);
14938     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
14939                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
14940   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
14941     SDLoc dl(N);
14942     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
14943                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
14944   }
14945 
14946   return SDValue();
14947 }
14948 
14949 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
14950 // the intrinsics must be legal and take an i32, this means there's almost
14951 // certainly going to be a zext in the DAG which we can eliminate.
14952 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
14953   SDValue AndN = N->getOperand(2);
14954   if (AndN.getOpcode() != ISD::AND)
14955     return SDValue();
14956 
14957   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
14958   if (!CMask || CMask->getZExtValue() != Mask)
14959     return SDValue();
14960 
14961   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
14962                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
14963 }
14964 
14965 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
14966                                            SelectionDAG &DAG) {
14967   SDLoc dl(N);
14968   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
14969                      DAG.getNode(Opc, dl,
14970                                  N->getOperand(1).getSimpleValueType(),
14971                                  N->getOperand(1)),
14972                      DAG.getConstant(0, dl, MVT::i64));
14973 }
14974 
14975 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
14976   SDLoc DL(N);
14977   SDValue Op1 = N->getOperand(1);
14978   SDValue Op2 = N->getOperand(2);
14979   EVT ScalarTy = Op2.getValueType();
14980   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
14981     ScalarTy = MVT::i32;
14982 
14983   // Lower index_vector(base, step) to mul(step step_vector(1)) + splat(base).
14984   SDValue StepVector = DAG.getStepVector(DL, N->getValueType(0));
14985   SDValue Step = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op2);
14986   SDValue Mul = DAG.getNode(ISD::MUL, DL, N->getValueType(0), StepVector, Step);
14987   SDValue Base = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op1);
14988   return DAG.getNode(ISD::ADD, DL, N->getValueType(0), Mul, Base);
14989 }
14990 
14991 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
14992   SDLoc dl(N);
14993   SDValue Scalar = N->getOperand(3);
14994   EVT ScalarTy = Scalar.getValueType();
14995 
14996   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
14997     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
14998 
14999   SDValue Passthru = N->getOperand(1);
15000   SDValue Pred = N->getOperand(2);
15001   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
15002                      Pred, Scalar, Passthru);
15003 }
15004 
15005 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
15006   SDLoc dl(N);
15007   LLVMContext &Ctx = *DAG.getContext();
15008   EVT VT = N->getValueType(0);
15009 
15010   assert(VT.isScalableVector() && "Expected a scalable vector.");
15011 
15012   // Current lowering only supports the SVE-ACLE types.
15013   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
15014     return SDValue();
15015 
15016   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
15017   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
15018   EVT ByteVT =
15019       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
15020 
15021   // Convert everything to the domain of EXT (i.e bytes).
15022   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
15023   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
15024   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
15025                             DAG.getConstant(ElemSize, dl, MVT::i32));
15026 
15027   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
15028   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
15029 }
15030 
15031 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
15032                                         TargetLowering::DAGCombinerInfo &DCI,
15033                                         SelectionDAG &DAG) {
15034   if (DCI.isBeforeLegalize())
15035     return SDValue();
15036 
15037   SDValue Comparator = N->getOperand(3);
15038   if (Comparator.getOpcode() == AArch64ISD::DUP ||
15039       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
15040     unsigned IID = getIntrinsicID(N);
15041     EVT VT = N->getValueType(0);
15042     EVT CmpVT = N->getOperand(2).getValueType();
15043     SDValue Pred = N->getOperand(1);
15044     SDValue Imm;
15045     SDLoc DL(N);
15046 
15047     switch (IID) {
15048     default:
15049       llvm_unreachable("Called with wrong intrinsic!");
15050       break;
15051 
15052     // Signed comparisons
15053     case Intrinsic::aarch64_sve_cmpeq_wide:
15054     case Intrinsic::aarch64_sve_cmpne_wide:
15055     case Intrinsic::aarch64_sve_cmpge_wide:
15056     case Intrinsic::aarch64_sve_cmpgt_wide:
15057     case Intrinsic::aarch64_sve_cmplt_wide:
15058     case Intrinsic::aarch64_sve_cmple_wide: {
15059       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
15060         int64_t ImmVal = CN->getSExtValue();
15061         if (ImmVal >= -16 && ImmVal <= 15)
15062           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
15063         else
15064           return SDValue();
15065       }
15066       break;
15067     }
15068     // Unsigned comparisons
15069     case Intrinsic::aarch64_sve_cmphs_wide:
15070     case Intrinsic::aarch64_sve_cmphi_wide:
15071     case Intrinsic::aarch64_sve_cmplo_wide:
15072     case Intrinsic::aarch64_sve_cmpls_wide:  {
15073       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
15074         uint64_t ImmVal = CN->getZExtValue();
15075         if (ImmVal <= 127)
15076           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
15077         else
15078           return SDValue();
15079       }
15080       break;
15081     }
15082     }
15083 
15084     if (!Imm)
15085       return SDValue();
15086 
15087     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
15088     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
15089                        N->getOperand(2), Splat, DAG.getCondCode(CC));
15090   }
15091 
15092   return SDValue();
15093 }
15094 
15095 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
15096                         AArch64CC::CondCode Cond) {
15097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15098 
15099   SDLoc DL(Op);
15100   assert(Op.getValueType().isScalableVector() &&
15101          TLI.isTypeLegal(Op.getValueType()) &&
15102          "Expected legal scalable vector type!");
15103 
15104   // Ensure target specific opcodes are using legal type.
15105   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
15106   SDValue TVal = DAG.getConstant(1, DL, OutVT);
15107   SDValue FVal = DAG.getConstant(0, DL, OutVT);
15108 
15109   // Set condition code (CC) flags.
15110   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
15111 
15112   // Convert CC to integer based on requested condition.
15113   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
15114   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
15115   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
15116   return DAG.getZExtOrTrunc(Res, DL, VT);
15117 }
15118 
15119 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
15120                                       SelectionDAG &DAG) {
15121   SDLoc DL(N);
15122 
15123   SDValue Pred = N->getOperand(1);
15124   SDValue VecToReduce = N->getOperand(2);
15125 
15126   // NOTE: The integer reduction's result type is not always linked to the
15127   // operand's element type so we construct it from the intrinsic's result type.
15128   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
15129   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
15130 
15131   // SVE reductions set the whole vector register with the first element
15132   // containing the reduction result, which we'll now extract.
15133   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15134   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
15135                      Zero);
15136 }
15137 
15138 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
15139                                      SelectionDAG &DAG) {
15140   SDLoc DL(N);
15141 
15142   SDValue Pred = N->getOperand(1);
15143   SDValue VecToReduce = N->getOperand(2);
15144 
15145   EVT ReduceVT = VecToReduce.getValueType();
15146   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
15147 
15148   // SVE reductions set the whole vector register with the first element
15149   // containing the reduction result, which we'll now extract.
15150   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15151   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
15152                      Zero);
15153 }
15154 
15155 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
15156                                             SelectionDAG &DAG) {
15157   SDLoc DL(N);
15158 
15159   SDValue Pred = N->getOperand(1);
15160   SDValue InitVal = N->getOperand(2);
15161   SDValue VecToReduce = N->getOperand(3);
15162   EVT ReduceVT = VecToReduce.getValueType();
15163 
15164   // Ordered reductions use the first lane of the result vector as the
15165   // reduction's initial value.
15166   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15167   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
15168                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
15169 
15170   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
15171 
15172   // SVE reductions set the whole vector register with the first element
15173   // containing the reduction result, which we'll now extract.
15174   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
15175                      Zero);
15176 }
15177 
15178 static bool isAllInactivePredicate(SDValue N) {
15179   // Look through cast.
15180   while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST)
15181     N = N.getOperand(0);
15182 
15183   return ISD::isConstantSplatVectorAllZeros(N.getNode());
15184 }
15185 
15186 static bool isAllActivePredicate(SelectionDAG &DAG, SDValue N) {
15187   unsigned NumElts = N.getValueType().getVectorMinNumElements();
15188 
15189   // Look through cast.
15190   while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST) {
15191     N = N.getOperand(0);
15192     // When reinterpreting from a type with fewer elements the "new" elements
15193     // are not active, so bail if they're likely to be used.
15194     if (N.getValueType().getVectorMinNumElements() < NumElts)
15195       return false;
15196   }
15197 
15198   // "ptrue p.<ty>, all" can be considered all active when <ty> is the same size
15199   // or smaller than the implicit element type represented by N.
15200   // NOTE: A larger element count implies a smaller element type.
15201   if (N.getOpcode() == AArch64ISD::PTRUE &&
15202       N.getConstantOperandVal(0) == AArch64SVEPredPattern::all)
15203     return N.getValueType().getVectorMinNumElements() >= NumElts;
15204 
15205   // If we're compiling for a specific vector-length, we can check if the
15206   // pattern's VL equals that of the scalable vector at runtime.
15207   if (N.getOpcode() == AArch64ISD::PTRUE) {
15208     const auto &Subtarget =
15209         static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
15210     unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
15211     unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
15212     if (MaxSVESize && MinSVESize == MaxSVESize) {
15213       unsigned VScale = MaxSVESize / AArch64::SVEBitsPerBlock;
15214       unsigned PatNumElts =
15215           getNumElementsFromSVEPredPattern(N.getConstantOperandVal(0));
15216       return PatNumElts == (NumElts * VScale);
15217     }
15218   }
15219 
15220   return false;
15221 }
15222 
15223 // If a merged operation has no inactive lanes we can relax it to a predicated
15224 // or unpredicated operation, which potentially allows better isel (perhaps
15225 // using immediate forms) or relaxing register reuse requirements.
15226 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned Opc,
15227                                        SelectionDAG &DAG, bool UnpredOp = false,
15228                                        bool SwapOperands = false) {
15229   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
15230   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
15231   SDValue Pg = N->getOperand(1);
15232   SDValue Op1 = N->getOperand(SwapOperands ? 3 : 2);
15233   SDValue Op2 = N->getOperand(SwapOperands ? 2 : 3);
15234 
15235   // ISD way to specify an all active predicate.
15236   if (isAllActivePredicate(DAG, Pg)) {
15237     if (UnpredOp)
15238       return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Op1, Op2);
15239 
15240     return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Pg, Op1, Op2);
15241   }
15242 
15243   // FUTURE: SplatVector(true)
15244   return SDValue();
15245 }
15246 
15247 static SDValue performIntrinsicCombine(SDNode *N,
15248                                        TargetLowering::DAGCombinerInfo &DCI,
15249                                        const AArch64Subtarget *Subtarget) {
15250   SelectionDAG &DAG = DCI.DAG;
15251   unsigned IID = getIntrinsicID(N);
15252   switch (IID) {
15253   default:
15254     break;
15255   case Intrinsic::aarch64_neon_vcvtfxs2fp:
15256   case Intrinsic::aarch64_neon_vcvtfxu2fp:
15257     return tryCombineFixedPointConvert(N, DCI, DAG);
15258   case Intrinsic::aarch64_neon_saddv:
15259     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
15260   case Intrinsic::aarch64_neon_uaddv:
15261     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
15262   case Intrinsic::aarch64_neon_sminv:
15263     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
15264   case Intrinsic::aarch64_neon_uminv:
15265     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
15266   case Intrinsic::aarch64_neon_smaxv:
15267     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
15268   case Intrinsic::aarch64_neon_umaxv:
15269     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
15270   case Intrinsic::aarch64_neon_fmax:
15271     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
15272                        N->getOperand(1), N->getOperand(2));
15273   case Intrinsic::aarch64_neon_fmin:
15274     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
15275                        N->getOperand(1), N->getOperand(2));
15276   case Intrinsic::aarch64_neon_fmaxnm:
15277     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
15278                        N->getOperand(1), N->getOperand(2));
15279   case Intrinsic::aarch64_neon_fminnm:
15280     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
15281                        N->getOperand(1), N->getOperand(2));
15282   case Intrinsic::aarch64_neon_smull:
15283   case Intrinsic::aarch64_neon_umull:
15284   case Intrinsic::aarch64_neon_pmull:
15285   case Intrinsic::aarch64_neon_sqdmull:
15286     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
15287   case Intrinsic::aarch64_neon_sqshl:
15288   case Intrinsic::aarch64_neon_uqshl:
15289   case Intrinsic::aarch64_neon_sqshlu:
15290   case Intrinsic::aarch64_neon_srshl:
15291   case Intrinsic::aarch64_neon_urshl:
15292   case Intrinsic::aarch64_neon_sshl:
15293   case Intrinsic::aarch64_neon_ushl:
15294     return tryCombineShiftImm(IID, N, DAG);
15295   case Intrinsic::aarch64_crc32b:
15296   case Intrinsic::aarch64_crc32cb:
15297     return tryCombineCRC32(0xff, N, DAG);
15298   case Intrinsic::aarch64_crc32h:
15299   case Intrinsic::aarch64_crc32ch:
15300     return tryCombineCRC32(0xffff, N, DAG);
15301   case Intrinsic::aarch64_sve_saddv:
15302     // There is no i64 version of SADDV because the sign is irrelevant.
15303     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
15304       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
15305     else
15306       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
15307   case Intrinsic::aarch64_sve_uaddv:
15308     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
15309   case Intrinsic::aarch64_sve_smaxv:
15310     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
15311   case Intrinsic::aarch64_sve_umaxv:
15312     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
15313   case Intrinsic::aarch64_sve_sminv:
15314     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
15315   case Intrinsic::aarch64_sve_uminv:
15316     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
15317   case Intrinsic::aarch64_sve_orv:
15318     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
15319   case Intrinsic::aarch64_sve_eorv:
15320     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
15321   case Intrinsic::aarch64_sve_andv:
15322     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
15323   case Intrinsic::aarch64_sve_index:
15324     return LowerSVEIntrinsicIndex(N, DAG);
15325   case Intrinsic::aarch64_sve_dup:
15326     return LowerSVEIntrinsicDUP(N, DAG);
15327   case Intrinsic::aarch64_sve_dup_x:
15328     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
15329                        N->getOperand(1));
15330   case Intrinsic::aarch64_sve_ext:
15331     return LowerSVEIntrinsicEXT(N, DAG);
15332   case Intrinsic::aarch64_sve_mul:
15333     return convertMergedOpToPredOp(N, AArch64ISD::MUL_PRED, DAG);
15334   case Intrinsic::aarch64_sve_smulh:
15335     return convertMergedOpToPredOp(N, AArch64ISD::MULHS_PRED, DAG);
15336   case Intrinsic::aarch64_sve_umulh:
15337     return convertMergedOpToPredOp(N, AArch64ISD::MULHU_PRED, DAG);
15338   case Intrinsic::aarch64_sve_smin:
15339     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
15340   case Intrinsic::aarch64_sve_umin:
15341     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
15342   case Intrinsic::aarch64_sve_smax:
15343     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
15344   case Intrinsic::aarch64_sve_umax:
15345     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
15346   case Intrinsic::aarch64_sve_lsl:
15347     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
15348   case Intrinsic::aarch64_sve_lsr:
15349     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
15350   case Intrinsic::aarch64_sve_asr:
15351     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
15352   case Intrinsic::aarch64_sve_fadd:
15353     return convertMergedOpToPredOp(N, AArch64ISD::FADD_PRED, DAG);
15354   case Intrinsic::aarch64_sve_fsub:
15355     return convertMergedOpToPredOp(N, AArch64ISD::FSUB_PRED, DAG);
15356   case Intrinsic::aarch64_sve_fmul:
15357     return convertMergedOpToPredOp(N, AArch64ISD::FMUL_PRED, DAG);
15358   case Intrinsic::aarch64_sve_add:
15359     return convertMergedOpToPredOp(N, ISD::ADD, DAG, true);
15360   case Intrinsic::aarch64_sve_sub:
15361     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true);
15362   case Intrinsic::aarch64_sve_subr:
15363     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true, true);
15364   case Intrinsic::aarch64_sve_and:
15365     return convertMergedOpToPredOp(N, ISD::AND, DAG, true);
15366   case Intrinsic::aarch64_sve_bic:
15367     return convertMergedOpToPredOp(N, AArch64ISD::BIC, DAG, true);
15368   case Intrinsic::aarch64_sve_eor:
15369     return convertMergedOpToPredOp(N, ISD::XOR, DAG, true);
15370   case Intrinsic::aarch64_sve_orr:
15371     return convertMergedOpToPredOp(N, ISD::OR, DAG, true);
15372   case Intrinsic::aarch64_sve_sqadd:
15373     return convertMergedOpToPredOp(N, ISD::SADDSAT, DAG, true);
15374   case Intrinsic::aarch64_sve_sqsub:
15375     return convertMergedOpToPredOp(N, ISD::SSUBSAT, DAG, true);
15376   case Intrinsic::aarch64_sve_uqadd:
15377     return convertMergedOpToPredOp(N, ISD::UADDSAT, DAG, true);
15378   case Intrinsic::aarch64_sve_uqsub:
15379     return convertMergedOpToPredOp(N, ISD::USUBSAT, DAG, true);
15380   case Intrinsic::aarch64_sve_sqadd_x:
15381     return DAG.getNode(ISD::SADDSAT, SDLoc(N), N->getValueType(0),
15382                        N->getOperand(1), N->getOperand(2));
15383   case Intrinsic::aarch64_sve_sqsub_x:
15384     return DAG.getNode(ISD::SSUBSAT, SDLoc(N), N->getValueType(0),
15385                        N->getOperand(1), N->getOperand(2));
15386   case Intrinsic::aarch64_sve_uqadd_x:
15387     return DAG.getNode(ISD::UADDSAT, SDLoc(N), N->getValueType(0),
15388                        N->getOperand(1), N->getOperand(2));
15389   case Intrinsic::aarch64_sve_uqsub_x:
15390     return DAG.getNode(ISD::USUBSAT, SDLoc(N), N->getValueType(0),
15391                        N->getOperand(1), N->getOperand(2));
15392   case Intrinsic::aarch64_sve_asrd:
15393     return DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, SDLoc(N), N->getValueType(0),
15394                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
15395   case Intrinsic::aarch64_sve_cmphs:
15396     if (!N->getOperand(2).getValueType().isFloatingPoint())
15397       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15398                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
15399                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
15400     break;
15401   case Intrinsic::aarch64_sve_cmphi:
15402     if (!N->getOperand(2).getValueType().isFloatingPoint())
15403       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15404                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
15405                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
15406     break;
15407   case Intrinsic::aarch64_sve_fcmpge:
15408   case Intrinsic::aarch64_sve_cmpge:
15409     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15410                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
15411                        N->getOperand(3), DAG.getCondCode(ISD::SETGE));
15412     break;
15413   case Intrinsic::aarch64_sve_fcmpgt:
15414   case Intrinsic::aarch64_sve_cmpgt:
15415     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15416                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
15417                        N->getOperand(3), DAG.getCondCode(ISD::SETGT));
15418     break;
15419   case Intrinsic::aarch64_sve_fcmpeq:
15420   case Intrinsic::aarch64_sve_cmpeq:
15421     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15422                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
15423                        N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
15424     break;
15425   case Intrinsic::aarch64_sve_fcmpne:
15426   case Intrinsic::aarch64_sve_cmpne:
15427     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15428                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
15429                        N->getOperand(3), DAG.getCondCode(ISD::SETNE));
15430     break;
15431   case Intrinsic::aarch64_sve_fcmpuo:
15432     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
15433                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
15434                        N->getOperand(3), DAG.getCondCode(ISD::SETUO));
15435     break;
15436   case Intrinsic::aarch64_sve_fadda:
15437     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
15438   case Intrinsic::aarch64_sve_faddv:
15439     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
15440   case Intrinsic::aarch64_sve_fmaxnmv:
15441     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
15442   case Intrinsic::aarch64_sve_fmaxv:
15443     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
15444   case Intrinsic::aarch64_sve_fminnmv:
15445     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
15446   case Intrinsic::aarch64_sve_fminv:
15447     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
15448   case Intrinsic::aarch64_sve_sel:
15449     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
15450                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
15451   case Intrinsic::aarch64_sve_cmpeq_wide:
15452     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
15453   case Intrinsic::aarch64_sve_cmpne_wide:
15454     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
15455   case Intrinsic::aarch64_sve_cmpge_wide:
15456     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
15457   case Intrinsic::aarch64_sve_cmpgt_wide:
15458     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
15459   case Intrinsic::aarch64_sve_cmplt_wide:
15460     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
15461   case Intrinsic::aarch64_sve_cmple_wide:
15462     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
15463   case Intrinsic::aarch64_sve_cmphs_wide:
15464     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
15465   case Intrinsic::aarch64_sve_cmphi_wide:
15466     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
15467   case Intrinsic::aarch64_sve_cmplo_wide:
15468     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
15469   case Intrinsic::aarch64_sve_cmpls_wide:
15470     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
15471   case Intrinsic::aarch64_sve_ptest_any:
15472     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
15473                     AArch64CC::ANY_ACTIVE);
15474   case Intrinsic::aarch64_sve_ptest_first:
15475     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
15476                     AArch64CC::FIRST_ACTIVE);
15477   case Intrinsic::aarch64_sve_ptest_last:
15478     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
15479                     AArch64CC::LAST_ACTIVE);
15480   }
15481   return SDValue();
15482 }
15483 
15484 static bool isCheapToExtend(const SDValue &N) {
15485   unsigned OC = N->getOpcode();
15486   return OC == ISD::LOAD || OC == ISD::MLOAD ||
15487          ISD::isConstantSplatVectorAllZeros(N.getNode());
15488 }
15489 
15490 static SDValue
15491 performSignExtendSetCCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
15492                               SelectionDAG &DAG) {
15493   // If we have (sext (setcc A B)) and A and B are cheap to extend,
15494   // we can move the sext into the arguments and have the same result. For
15495   // example, if A and B are both loads, we can make those extending loads and
15496   // avoid an extra instruction. This pattern appears often in VLS code
15497   // generation where the inputs to the setcc have a different size to the
15498   // instruction that wants to use the result of the setcc.
15499   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
15500          N->getOperand(0)->getOpcode() == ISD::SETCC);
15501   const SDValue SetCC = N->getOperand(0);
15502 
15503   const SDValue CCOp0 = SetCC.getOperand(0);
15504   const SDValue CCOp1 = SetCC.getOperand(1);
15505   if (!CCOp0->getValueType(0).isInteger() ||
15506       !CCOp1->getValueType(0).isInteger())
15507     return SDValue();
15508 
15509   ISD::CondCode Code =
15510       cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get();
15511 
15512   ISD::NodeType ExtType =
15513       isSignedIntSetCC(Code) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15514 
15515   if (isCheapToExtend(SetCC.getOperand(0)) &&
15516       isCheapToExtend(SetCC.getOperand(1))) {
15517     const SDValue Ext1 =
15518         DAG.getNode(ExtType, SDLoc(N), N->getValueType(0), CCOp0);
15519     const SDValue Ext2 =
15520         DAG.getNode(ExtType, SDLoc(N), N->getValueType(0), CCOp1);
15521 
15522     return DAG.getSetCC(
15523         SDLoc(SetCC), N->getValueType(0), Ext1, Ext2,
15524         cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get());
15525   }
15526 
15527   return SDValue();
15528 }
15529 
15530 static SDValue performExtendCombine(SDNode *N,
15531                                     TargetLowering::DAGCombinerInfo &DCI,
15532                                     SelectionDAG &DAG) {
15533   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
15534   // we can convert that DUP into another extract_high (of a bigger DUP), which
15535   // helps the backend to decide that an sabdl2 would be useful, saving a real
15536   // extract_high operation.
15537   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
15538       (N->getOperand(0).getOpcode() == ISD::ABDU ||
15539        N->getOperand(0).getOpcode() == ISD::ABDS)) {
15540     SDNode *ABDNode = N->getOperand(0).getNode();
15541     SDValue NewABD =
15542         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
15543     if (!NewABD.getNode())
15544       return SDValue();
15545 
15546     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
15547   }
15548 
15549   if (N->getValueType(0).isFixedLengthVector() &&
15550       N->getOpcode() == ISD::SIGN_EXTEND &&
15551       N->getOperand(0)->getOpcode() == ISD::SETCC)
15552     return performSignExtendSetCCCombine(N, DCI, DAG);
15553 
15554   return SDValue();
15555 }
15556 
15557 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
15558                                SDValue SplatVal, unsigned NumVecElts) {
15559   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
15560   unsigned OrigAlignment = St.getAlignment();
15561   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
15562 
15563   // Create scalar stores. This is at least as good as the code sequence for a
15564   // split unaligned store which is a dup.s, ext.b, and two stores.
15565   // Most of the time the three stores should be replaced by store pair
15566   // instructions (stp).
15567   SDLoc DL(&St);
15568   SDValue BasePtr = St.getBasePtr();
15569   uint64_t BaseOffset = 0;
15570 
15571   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
15572   SDValue NewST1 =
15573       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
15574                    OrigAlignment, St.getMemOperand()->getFlags());
15575 
15576   // As this in ISel, we will not merge this add which may degrade results.
15577   if (BasePtr->getOpcode() == ISD::ADD &&
15578       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
15579     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
15580     BasePtr = BasePtr->getOperand(0);
15581   }
15582 
15583   unsigned Offset = EltOffset;
15584   while (--NumVecElts) {
15585     unsigned Alignment = MinAlign(OrigAlignment, Offset);
15586     SDValue OffsetPtr =
15587         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
15588                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
15589     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
15590                           PtrInfo.getWithOffset(Offset), Alignment,
15591                           St.getMemOperand()->getFlags());
15592     Offset += EltOffset;
15593   }
15594   return NewST1;
15595 }
15596 
15597 // Returns an SVE type that ContentTy can be trivially sign or zero extended
15598 // into.
15599 static MVT getSVEContainerType(EVT ContentTy) {
15600   assert(ContentTy.isSimple() && "No SVE containers for extended types");
15601 
15602   switch (ContentTy.getSimpleVT().SimpleTy) {
15603   default:
15604     llvm_unreachable("No known SVE container for this MVT type");
15605   case MVT::nxv2i8:
15606   case MVT::nxv2i16:
15607   case MVT::nxv2i32:
15608   case MVT::nxv2i64:
15609   case MVT::nxv2f32:
15610   case MVT::nxv2f64:
15611     return MVT::nxv2i64;
15612   case MVT::nxv4i8:
15613   case MVT::nxv4i16:
15614   case MVT::nxv4i32:
15615   case MVT::nxv4f32:
15616     return MVT::nxv4i32;
15617   case MVT::nxv8i8:
15618   case MVT::nxv8i16:
15619   case MVT::nxv8f16:
15620   case MVT::nxv8bf16:
15621     return MVT::nxv8i16;
15622   case MVT::nxv16i8:
15623     return MVT::nxv16i8;
15624   }
15625 }
15626 
15627 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
15628   SDLoc DL(N);
15629   EVT VT = N->getValueType(0);
15630 
15631   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
15632     return SDValue();
15633 
15634   EVT ContainerVT = VT;
15635   if (ContainerVT.isInteger())
15636     ContainerVT = getSVEContainerType(ContainerVT);
15637 
15638   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
15639   SDValue Ops[] = { N->getOperand(0), // Chain
15640                     N->getOperand(2), // Pg
15641                     N->getOperand(3), // Base
15642                     DAG.getValueType(VT) };
15643 
15644   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
15645   SDValue LoadChain = SDValue(Load.getNode(), 1);
15646 
15647   if (ContainerVT.isInteger() && (VT != ContainerVT))
15648     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
15649 
15650   return DAG.getMergeValues({ Load, LoadChain }, DL);
15651 }
15652 
15653 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
15654   SDLoc DL(N);
15655   EVT VT = N->getValueType(0);
15656   EVT PtrTy = N->getOperand(3).getValueType();
15657 
15658   if (VT == MVT::nxv8bf16 &&
15659       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15660     return SDValue();
15661 
15662   EVT LoadVT = VT;
15663   if (VT.isFloatingPoint())
15664     LoadVT = VT.changeTypeToInteger();
15665 
15666   auto *MINode = cast<MemIntrinsicSDNode>(N);
15667   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
15668   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
15669                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
15670                                 MINode->getOperand(2), PassThru,
15671                                 MINode->getMemoryVT(), MINode->getMemOperand(),
15672                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
15673 
15674    if (VT.isFloatingPoint()) {
15675      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
15676      return DAG.getMergeValues(Ops, DL);
15677    }
15678 
15679   return L;
15680 }
15681 
15682 template <unsigned Opcode>
15683 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
15684   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
15685                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
15686                 "Unsupported opcode.");
15687   SDLoc DL(N);
15688   EVT VT = N->getValueType(0);
15689   if (VT == MVT::nxv8bf16 &&
15690       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15691     return SDValue();
15692 
15693   EVT LoadVT = VT;
15694   if (VT.isFloatingPoint())
15695     LoadVT = VT.changeTypeToInteger();
15696 
15697   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
15698   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
15699   SDValue LoadChain = SDValue(Load.getNode(), 1);
15700 
15701   if (VT.isFloatingPoint())
15702     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
15703 
15704   return DAG.getMergeValues({Load, LoadChain}, DL);
15705 }
15706 
15707 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
15708   SDLoc DL(N);
15709   SDValue Data = N->getOperand(2);
15710   EVT DataVT = Data.getValueType();
15711   EVT HwSrcVt = getSVEContainerType(DataVT);
15712   SDValue InputVT = DAG.getValueType(DataVT);
15713 
15714   if (DataVT == MVT::nxv8bf16 &&
15715       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15716     return SDValue();
15717 
15718   if (DataVT.isFloatingPoint())
15719     InputVT = DAG.getValueType(HwSrcVt);
15720 
15721   SDValue SrcNew;
15722   if (Data.getValueType().isFloatingPoint())
15723     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
15724   else
15725     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
15726 
15727   SDValue Ops[] = { N->getOperand(0), // Chain
15728                     SrcNew,
15729                     N->getOperand(4), // Base
15730                     N->getOperand(3), // Pg
15731                     InputVT
15732                   };
15733 
15734   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
15735 }
15736 
15737 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
15738   SDLoc DL(N);
15739 
15740   SDValue Data = N->getOperand(2);
15741   EVT DataVT = Data.getValueType();
15742   EVT PtrTy = N->getOperand(4).getValueType();
15743 
15744   if (DataVT == MVT::nxv8bf16 &&
15745       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15746     return SDValue();
15747 
15748   if (DataVT.isFloatingPoint())
15749     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
15750 
15751   auto *MINode = cast<MemIntrinsicSDNode>(N);
15752   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
15753                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
15754                             MINode->getMemoryVT(), MINode->getMemOperand(),
15755                             ISD::UNINDEXED, false, false);
15756 }
15757 
15758 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
15759 /// load store optimizer pass will merge them to store pair stores.  This should
15760 /// be better than a movi to create the vector zero followed by a vector store
15761 /// if the zero constant is not re-used, since one instructions and one register
15762 /// live range will be removed.
15763 ///
15764 /// For example, the final generated code should be:
15765 ///
15766 ///   stp xzr, xzr, [x0]
15767 ///
15768 /// instead of:
15769 ///
15770 ///   movi v0.2d, #0
15771 ///   str q0, [x0]
15772 ///
15773 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
15774   SDValue StVal = St.getValue();
15775   EVT VT = StVal.getValueType();
15776 
15777   // Avoid scalarizing zero splat stores for scalable vectors.
15778   if (VT.isScalableVector())
15779     return SDValue();
15780 
15781   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
15782   // 2, 3 or 4 i32 elements.
15783   int NumVecElts = VT.getVectorNumElements();
15784   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
15785          VT.getVectorElementType().getSizeInBits() == 64) ||
15786         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
15787          VT.getVectorElementType().getSizeInBits() == 32)))
15788     return SDValue();
15789 
15790   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
15791     return SDValue();
15792 
15793   // If the zero constant has more than one use then the vector store could be
15794   // better since the constant mov will be amortized and stp q instructions
15795   // should be able to be formed.
15796   if (!StVal.hasOneUse())
15797     return SDValue();
15798 
15799   // If the store is truncating then it's going down to i16 or smaller, which
15800   // means it can be implemented in a single store anyway.
15801   if (St.isTruncatingStore())
15802     return SDValue();
15803 
15804   // If the immediate offset of the address operand is too large for the stp
15805   // instruction, then bail out.
15806   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
15807     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
15808     if (Offset < -512 || Offset > 504)
15809       return SDValue();
15810   }
15811 
15812   for (int I = 0; I < NumVecElts; ++I) {
15813     SDValue EltVal = StVal.getOperand(I);
15814     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
15815       return SDValue();
15816   }
15817 
15818   // Use a CopyFromReg WZR/XZR here to prevent
15819   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
15820   SDLoc DL(&St);
15821   unsigned ZeroReg;
15822   EVT ZeroVT;
15823   if (VT.getVectorElementType().getSizeInBits() == 32) {
15824     ZeroReg = AArch64::WZR;
15825     ZeroVT = MVT::i32;
15826   } else {
15827     ZeroReg = AArch64::XZR;
15828     ZeroVT = MVT::i64;
15829   }
15830   SDValue SplatVal =
15831       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
15832   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
15833 }
15834 
15835 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
15836 /// value. The load store optimizer pass will merge them to store pair stores.
15837 /// This has better performance than a splat of the scalar followed by a split
15838 /// vector store. Even if the stores are not merged it is four stores vs a dup,
15839 /// followed by an ext.b and two stores.
15840 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
15841   SDValue StVal = St.getValue();
15842   EVT VT = StVal.getValueType();
15843 
15844   // Don't replace floating point stores, they possibly won't be transformed to
15845   // stp because of the store pair suppress pass.
15846   if (VT.isFloatingPoint())
15847     return SDValue();
15848 
15849   // We can express a splat as store pair(s) for 2 or 4 elements.
15850   unsigned NumVecElts = VT.getVectorNumElements();
15851   if (NumVecElts != 4 && NumVecElts != 2)
15852     return SDValue();
15853 
15854   // If the store is truncating then it's going down to i16 or smaller, which
15855   // means it can be implemented in a single store anyway.
15856   if (St.isTruncatingStore())
15857     return SDValue();
15858 
15859   // Check that this is a splat.
15860   // Make sure that each of the relevant vector element locations are inserted
15861   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
15862   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
15863   SDValue SplatVal;
15864   for (unsigned I = 0; I < NumVecElts; ++I) {
15865     // Check for insert vector elements.
15866     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
15867       return SDValue();
15868 
15869     // Check that same value is inserted at each vector element.
15870     if (I == 0)
15871       SplatVal = StVal.getOperand(1);
15872     else if (StVal.getOperand(1) != SplatVal)
15873       return SDValue();
15874 
15875     // Check insert element index.
15876     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
15877     if (!CIndex)
15878       return SDValue();
15879     uint64_t IndexVal = CIndex->getZExtValue();
15880     if (IndexVal >= NumVecElts)
15881       return SDValue();
15882     IndexNotInserted.reset(IndexVal);
15883 
15884     StVal = StVal.getOperand(0);
15885   }
15886   // Check that all vector element locations were inserted to.
15887   if (IndexNotInserted.any())
15888       return SDValue();
15889 
15890   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
15891 }
15892 
15893 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
15894                            SelectionDAG &DAG,
15895                            const AArch64Subtarget *Subtarget) {
15896 
15897   StoreSDNode *S = cast<StoreSDNode>(N);
15898   if (S->isVolatile() || S->isIndexed())
15899     return SDValue();
15900 
15901   SDValue StVal = S->getValue();
15902   EVT VT = StVal.getValueType();
15903 
15904   if (!VT.isFixedLengthVector())
15905     return SDValue();
15906 
15907   // If we get a splat of zeros, convert this vector store to a store of
15908   // scalars. They will be merged into store pairs of xzr thereby removing one
15909   // instruction and one register.
15910   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
15911     return ReplacedZeroSplat;
15912 
15913   // FIXME: The logic for deciding if an unaligned store should be split should
15914   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
15915   // a call to that function here.
15916 
15917   if (!Subtarget->isMisaligned128StoreSlow())
15918     return SDValue();
15919 
15920   // Don't split at -Oz.
15921   if (DAG.getMachineFunction().getFunction().hasMinSize())
15922     return SDValue();
15923 
15924   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
15925   // those up regresses performance on micro-benchmarks and olden/bh.
15926   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
15927     return SDValue();
15928 
15929   // Split unaligned 16B stores. They are terrible for performance.
15930   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
15931   // extensions can use this to mark that it does not want splitting to happen
15932   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
15933   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
15934   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
15935       S->getAlignment() <= 2)
15936     return SDValue();
15937 
15938   // If we get a splat of a scalar convert this vector store to a store of
15939   // scalars. They will be merged into store pairs thereby removing two
15940   // instructions.
15941   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
15942     return ReplacedSplat;
15943 
15944   SDLoc DL(S);
15945 
15946   // Split VT into two.
15947   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
15948   unsigned NumElts = HalfVT.getVectorNumElements();
15949   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
15950                                    DAG.getConstant(0, DL, MVT::i64));
15951   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
15952                                    DAG.getConstant(NumElts, DL, MVT::i64));
15953   SDValue BasePtr = S->getBasePtr();
15954   SDValue NewST1 =
15955       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
15956                    S->getAlignment(), S->getMemOperand()->getFlags());
15957   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
15958                                   DAG.getConstant(8, DL, MVT::i64));
15959   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
15960                       S->getPointerInfo(), S->getAlignment(),
15961                       S->getMemOperand()->getFlags());
15962 }
15963 
15964 static SDValue performSpliceCombine(SDNode *N, SelectionDAG &DAG) {
15965   assert(N->getOpcode() == AArch64ISD::SPLICE && "Unexepected Opcode!");
15966 
15967   // splice(pg, op1, undef) -> op1
15968   if (N->getOperand(2).isUndef())
15969     return N->getOperand(1);
15970 
15971   return SDValue();
15972 }
15973 
15974 static SDValue performUnpackCombine(SDNode *N, SelectionDAG &DAG) {
15975   assert((N->getOpcode() == AArch64ISD::UUNPKHI ||
15976           N->getOpcode() == AArch64ISD::UUNPKLO) &&
15977          "Unexpected Opcode!");
15978 
15979   // uunpklo/hi undef -> undef
15980   if (N->getOperand(0).isUndef())
15981     return DAG.getUNDEF(N->getValueType(0));
15982 
15983   return SDValue();
15984 }
15985 
15986 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
15987   SDLoc DL(N);
15988   SDValue Op0 = N->getOperand(0);
15989   SDValue Op1 = N->getOperand(1);
15990   EVT ResVT = N->getValueType(0);
15991 
15992   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
15993   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
15994     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
15995       SDValue X = Op0.getOperand(0).getOperand(0);
15996       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
15997     }
15998   }
15999 
16000   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
16001   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
16002     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
16003       SDValue Z = Op1.getOperand(0).getOperand(1);
16004       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
16005     }
16006   }
16007 
16008   return SDValue();
16009 }
16010 
16011 static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) {
16012   unsigned Opc = N->getOpcode();
16013 
16014   assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads
16015            Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) ||
16016           (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads
16017            Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) &&
16018          "Invalid opcode.");
16019 
16020   const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO ||
16021                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
16022   const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO ||
16023                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
16024   const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO ||
16025                         Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO ||
16026                         Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO ||
16027                         Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO;
16028 
16029   SDLoc DL(N);
16030   SDValue Chain = N->getOperand(0);
16031   SDValue Pg = N->getOperand(1);
16032   SDValue Base = N->getOperand(2);
16033   SDValue Offset = N->getOperand(3);
16034   SDValue Ty = N->getOperand(4);
16035 
16036   EVT ResVT = N->getValueType(0);
16037 
16038   const auto OffsetOpc = Offset.getOpcode();
16039   const bool OffsetIsZExt =
16040       OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU;
16041   const bool OffsetIsSExt =
16042       OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU;
16043 
16044   // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible.
16045   if (!Extended && (OffsetIsSExt || OffsetIsZExt)) {
16046     SDValue ExtPg = Offset.getOperand(0);
16047     VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode());
16048     EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType();
16049 
16050     // If the predicate for the sign- or zero-extended offset is the
16051     // same as the predicate used for this load and the sign-/zero-extension
16052     // was from a 32-bits...
16053     if (ExtPg == Pg && ExtFromEVT == MVT::i32) {
16054       SDValue UnextendedOffset = Offset.getOperand(1);
16055 
16056       unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true);
16057       if (Signed)
16058         NewOpc = getSignExtendedGatherOpcode(NewOpc);
16059 
16060       return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other},
16061                          {Chain, Pg, Base, UnextendedOffset, Ty});
16062     }
16063   }
16064 
16065   return SDValue();
16066 }
16067 
16068 /// Optimize a vector shift instruction and its operand if shifted out
16069 /// bits are not used.
16070 static SDValue performVectorShiftCombine(SDNode *N,
16071                                          const AArch64TargetLowering &TLI,
16072                                          TargetLowering::DAGCombinerInfo &DCI) {
16073   assert(N->getOpcode() == AArch64ISD::VASHR ||
16074          N->getOpcode() == AArch64ISD::VLSHR);
16075 
16076   SDValue Op = N->getOperand(0);
16077   unsigned OpScalarSize = Op.getScalarValueSizeInBits();
16078 
16079   unsigned ShiftImm = N->getConstantOperandVal(1);
16080   assert(OpScalarSize > ShiftImm && "Invalid shift imm");
16081 
16082   APInt ShiftedOutBits = APInt::getLowBitsSet(OpScalarSize, ShiftImm);
16083   APInt DemandedMask = ~ShiftedOutBits;
16084 
16085   if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
16086     return SDValue(N, 0);
16087 
16088   return SDValue();
16089 }
16090 
16091 static SDValue performSunpkloCombine(SDNode *N, SelectionDAG &DAG) {
16092   // sunpklo(sext(pred)) -> sext(extract_low_half(pred))
16093   // This transform works in partnership with performSetCCPunpkCombine to
16094   // remove unnecessary transfer of predicates into standard registers and back
16095   if (N->getOperand(0).getOpcode() == ISD::SIGN_EXTEND &&
16096       N->getOperand(0)->getOperand(0)->getValueType(0).getScalarType() ==
16097           MVT::i1) {
16098     SDValue CC = N->getOperand(0)->getOperand(0);
16099     auto VT = CC->getValueType(0).getHalfNumVectorElementsVT(*DAG.getContext());
16100     SDValue Unpk = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT, CC,
16101                                DAG.getVectorIdxConstant(0, SDLoc(N)));
16102     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), N->getValueType(0), Unpk);
16103   }
16104 
16105   return SDValue();
16106 }
16107 
16108 /// Target-specific DAG combine function for post-increment LD1 (lane) and
16109 /// post-increment LD1R.
16110 static SDValue performPostLD1Combine(SDNode *N,
16111                                      TargetLowering::DAGCombinerInfo &DCI,
16112                                      bool IsLaneOp) {
16113   if (DCI.isBeforeLegalizeOps())
16114     return SDValue();
16115 
16116   SelectionDAG &DAG = DCI.DAG;
16117   EVT VT = N->getValueType(0);
16118 
16119   if (!VT.is128BitVector() && !VT.is64BitVector())
16120     return SDValue();
16121 
16122   unsigned LoadIdx = IsLaneOp ? 1 : 0;
16123   SDNode *LD = N->getOperand(LoadIdx).getNode();
16124   // If it is not LOAD, can not do such combine.
16125   if (LD->getOpcode() != ISD::LOAD)
16126     return SDValue();
16127 
16128   // The vector lane must be a constant in the LD1LANE opcode.
16129   SDValue Lane;
16130   if (IsLaneOp) {
16131     Lane = N->getOperand(2);
16132     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
16133     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
16134       return SDValue();
16135   }
16136 
16137   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
16138   EVT MemVT = LoadSDN->getMemoryVT();
16139   // Check if memory operand is the same type as the vector element.
16140   if (MemVT != VT.getVectorElementType())
16141     return SDValue();
16142 
16143   // Check if there are other uses. If so, do not combine as it will introduce
16144   // an extra load.
16145   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
16146        ++UI) {
16147     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
16148       continue;
16149     if (*UI != N)
16150       return SDValue();
16151   }
16152 
16153   SDValue Addr = LD->getOperand(1);
16154   SDValue Vector = N->getOperand(0);
16155   // Search for a use of the address operand that is an increment.
16156   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
16157        Addr.getNode()->use_end(); UI != UE; ++UI) {
16158     SDNode *User = *UI;
16159     if (User->getOpcode() != ISD::ADD
16160         || UI.getUse().getResNo() != Addr.getResNo())
16161       continue;
16162 
16163     // If the increment is a constant, it must match the memory ref size.
16164     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16165     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
16166       uint32_t IncVal = CInc->getZExtValue();
16167       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
16168       if (IncVal != NumBytes)
16169         continue;
16170       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
16171     }
16172 
16173     // To avoid cycle construction make sure that neither the load nor the add
16174     // are predecessors to each other or the Vector.
16175     SmallPtrSet<const SDNode *, 32> Visited;
16176     SmallVector<const SDNode *, 16> Worklist;
16177     Visited.insert(Addr.getNode());
16178     Worklist.push_back(User);
16179     Worklist.push_back(LD);
16180     Worklist.push_back(Vector.getNode());
16181     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
16182         SDNode::hasPredecessorHelper(User, Visited, Worklist))
16183       continue;
16184 
16185     SmallVector<SDValue, 8> Ops;
16186     Ops.push_back(LD->getOperand(0));  // Chain
16187     if (IsLaneOp) {
16188       Ops.push_back(Vector);           // The vector to be inserted
16189       Ops.push_back(Lane);             // The lane to be inserted in the vector
16190     }
16191     Ops.push_back(Addr);
16192     Ops.push_back(Inc);
16193 
16194     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
16195     SDVTList SDTys = DAG.getVTList(Tys);
16196     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
16197     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
16198                                            MemVT,
16199                                            LoadSDN->getMemOperand());
16200 
16201     // Update the uses.
16202     SDValue NewResults[] = {
16203         SDValue(LD, 0),            // The result of load
16204         SDValue(UpdN.getNode(), 2) // Chain
16205     };
16206     DCI.CombineTo(LD, NewResults);
16207     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
16208     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
16209 
16210     break;
16211   }
16212   return SDValue();
16213 }
16214 
16215 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
16216 /// address translation.
16217 static bool performTBISimplification(SDValue Addr,
16218                                      TargetLowering::DAGCombinerInfo &DCI,
16219                                      SelectionDAG &DAG) {
16220   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
16221   KnownBits Known;
16222   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16223                                         !DCI.isBeforeLegalizeOps());
16224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16225   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
16226     DCI.CommitTargetLoweringOpt(TLO);
16227     return true;
16228   }
16229   return false;
16230 }
16231 
16232 static SDValue foldTruncStoreOfExt(SelectionDAG &DAG, SDNode *N) {
16233   assert((N->getOpcode() == ISD::STORE || N->getOpcode() == ISD::MSTORE) &&
16234          "Expected STORE dag node in input!");
16235 
16236   if (auto Store = dyn_cast<StoreSDNode>(N)) {
16237     if (!Store->isTruncatingStore() || Store->isIndexed())
16238       return SDValue();
16239     SDValue Ext = Store->getValue();
16240     auto ExtOpCode = Ext.getOpcode();
16241     if (ExtOpCode != ISD::ZERO_EXTEND && ExtOpCode != ISD::SIGN_EXTEND &&
16242         ExtOpCode != ISD::ANY_EXTEND)
16243       return SDValue();
16244     SDValue Orig = Ext->getOperand(0);
16245     if (Store->getMemoryVT() != Orig.getValueType())
16246       return SDValue();
16247     return DAG.getStore(Store->getChain(), SDLoc(Store), Orig,
16248                         Store->getBasePtr(), Store->getMemOperand());
16249   }
16250 
16251   return SDValue();
16252 }
16253 
16254 static SDValue performSTORECombine(SDNode *N,
16255                                    TargetLowering::DAGCombinerInfo &DCI,
16256                                    SelectionDAG &DAG,
16257                                    const AArch64Subtarget *Subtarget) {
16258   StoreSDNode *ST = cast<StoreSDNode>(N);
16259   SDValue Chain = ST->getChain();
16260   SDValue Value = ST->getValue();
16261   SDValue Ptr = ST->getBasePtr();
16262 
16263   // If this is an FP_ROUND followed by a store, fold this into a truncating
16264   // store. We can do this even if this is already a truncstore.
16265   // We purposefully don't care about legality of the nodes here as we know
16266   // they can be split down into something legal.
16267   if (DCI.isBeforeLegalizeOps() && Value.getOpcode() == ISD::FP_ROUND &&
16268       Value.getNode()->hasOneUse() && ST->isUnindexed() &&
16269       Subtarget->useSVEForFixedLengthVectors() &&
16270       Value.getValueType().isFixedLengthVector() &&
16271       Value.getValueType().getFixedSizeInBits() >=
16272           Subtarget->getMinSVEVectorSizeInBits())
16273     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
16274                              ST->getMemoryVT(), ST->getMemOperand());
16275 
16276   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
16277     return Split;
16278 
16279   if (Subtarget->supportsAddressTopByteIgnored() &&
16280       performTBISimplification(N->getOperand(2), DCI, DAG))
16281     return SDValue(N, 0);
16282 
16283   if (SDValue Store = foldTruncStoreOfExt(DAG, N))
16284     return Store;
16285 
16286   return SDValue();
16287 }
16288 
16289 /// Target-specific DAG combine function for NEON load/store intrinsics
16290 /// to merge base address updates.
16291 static SDValue performNEONPostLDSTCombine(SDNode *N,
16292                                           TargetLowering::DAGCombinerInfo &DCI,
16293                                           SelectionDAG &DAG) {
16294   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16295     return SDValue();
16296 
16297   unsigned AddrOpIdx = N->getNumOperands() - 1;
16298   SDValue Addr = N->getOperand(AddrOpIdx);
16299 
16300   // Search for a use of the address operand that is an increment.
16301   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
16302        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
16303     SDNode *User = *UI;
16304     if (User->getOpcode() != ISD::ADD ||
16305         UI.getUse().getResNo() != Addr.getResNo())
16306       continue;
16307 
16308     // Check that the add is independent of the load/store.  Otherwise, folding
16309     // it would create a cycle.
16310     SmallPtrSet<const SDNode *, 32> Visited;
16311     SmallVector<const SDNode *, 16> Worklist;
16312     Visited.insert(Addr.getNode());
16313     Worklist.push_back(N);
16314     Worklist.push_back(User);
16315     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
16316         SDNode::hasPredecessorHelper(User, Visited, Worklist))
16317       continue;
16318 
16319     // Find the new opcode for the updating load/store.
16320     bool IsStore = false;
16321     bool IsLaneOp = false;
16322     bool IsDupOp = false;
16323     unsigned NewOpc = 0;
16324     unsigned NumVecs = 0;
16325     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16326     switch (IntNo) {
16327     default: llvm_unreachable("unexpected intrinsic for Neon base update");
16328     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
16329       NumVecs = 2; break;
16330     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
16331       NumVecs = 3; break;
16332     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
16333       NumVecs = 4; break;
16334     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
16335       NumVecs = 2; IsStore = true; break;
16336     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
16337       NumVecs = 3; IsStore = true; break;
16338     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
16339       NumVecs = 4; IsStore = true; break;
16340     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
16341       NumVecs = 2; break;
16342     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
16343       NumVecs = 3; break;
16344     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
16345       NumVecs = 4; break;
16346     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
16347       NumVecs = 2; IsStore = true; break;
16348     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
16349       NumVecs = 3; IsStore = true; break;
16350     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
16351       NumVecs = 4; IsStore = true; break;
16352     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
16353       NumVecs = 2; IsDupOp = true; break;
16354     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
16355       NumVecs = 3; IsDupOp = true; break;
16356     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
16357       NumVecs = 4; IsDupOp = true; break;
16358     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
16359       NumVecs = 2; IsLaneOp = true; break;
16360     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
16361       NumVecs = 3; IsLaneOp = true; break;
16362     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
16363       NumVecs = 4; IsLaneOp = true; break;
16364     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
16365       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
16366     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
16367       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
16368     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
16369       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
16370     }
16371 
16372     EVT VecTy;
16373     if (IsStore)
16374       VecTy = N->getOperand(2).getValueType();
16375     else
16376       VecTy = N->getValueType(0);
16377 
16378     // If the increment is a constant, it must match the memory ref size.
16379     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16380     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
16381       uint32_t IncVal = CInc->getZExtValue();
16382       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16383       if (IsLaneOp || IsDupOp)
16384         NumBytes /= VecTy.getVectorNumElements();
16385       if (IncVal != NumBytes)
16386         continue;
16387       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
16388     }
16389     SmallVector<SDValue, 8> Ops;
16390     Ops.push_back(N->getOperand(0)); // Incoming chain
16391     // Load lane and store have vector list as input.
16392     if (IsLaneOp || IsStore)
16393       for (unsigned i = 2; i < AddrOpIdx; ++i)
16394         Ops.push_back(N->getOperand(i));
16395     Ops.push_back(Addr); // Base register
16396     Ops.push_back(Inc);
16397 
16398     // Return Types.
16399     EVT Tys[6];
16400     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
16401     unsigned n;
16402     for (n = 0; n < NumResultVecs; ++n)
16403       Tys[n] = VecTy;
16404     Tys[n++] = MVT::i64;  // Type of write back register
16405     Tys[n] = MVT::Other;  // Type of the chain
16406     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
16407 
16408     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
16409     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
16410                                            MemInt->getMemoryVT(),
16411                                            MemInt->getMemOperand());
16412 
16413     // Update the uses.
16414     std::vector<SDValue> NewResults;
16415     for (unsigned i = 0; i < NumResultVecs; ++i) {
16416       NewResults.push_back(SDValue(UpdN.getNode(), i));
16417     }
16418     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
16419     DCI.CombineTo(N, NewResults);
16420     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16421 
16422     break;
16423   }
16424   return SDValue();
16425 }
16426 
16427 // Checks to see if the value is the prescribed width and returns information
16428 // about its extension mode.
16429 static
16430 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
16431   ExtType = ISD::NON_EXTLOAD;
16432   switch(V.getNode()->getOpcode()) {
16433   default:
16434     return false;
16435   case ISD::LOAD: {
16436     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
16437     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
16438        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
16439       ExtType = LoadNode->getExtensionType();
16440       return true;
16441     }
16442     return false;
16443   }
16444   case ISD::AssertSext: {
16445     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
16446     if ((TypeNode->getVT() == MVT::i8 && width == 8)
16447        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
16448       ExtType = ISD::SEXTLOAD;
16449       return true;
16450     }
16451     return false;
16452   }
16453   case ISD::AssertZext: {
16454     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
16455     if ((TypeNode->getVT() == MVT::i8 && width == 8)
16456        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
16457       ExtType = ISD::ZEXTLOAD;
16458       return true;
16459     }
16460     return false;
16461   }
16462   case ISD::Constant:
16463   case ISD::TargetConstant: {
16464     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
16465            1LL << (width - 1);
16466   }
16467   }
16468 
16469   return true;
16470 }
16471 
16472 // This function does a whole lot of voodoo to determine if the tests are
16473 // equivalent without and with a mask. Essentially what happens is that given a
16474 // DAG resembling:
16475 //
16476 //  +-------------+ +-------------+ +-------------+ +-------------+
16477 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
16478 //  +-------------+ +-------------+ +-------------+ +-------------+
16479 //           |           |           |               |
16480 //           V           V           |    +----------+
16481 //          +-------------+  +----+  |    |
16482 //          |     ADD     |  |0xff|  |    |
16483 //          +-------------+  +----+  |    |
16484 //                  |           |    |    |
16485 //                  V           V    |    |
16486 //                 +-------------+   |    |
16487 //                 |     AND     |   |    |
16488 //                 +-------------+   |    |
16489 //                      |            |    |
16490 //                      +-----+      |    |
16491 //                            |      |    |
16492 //                            V      V    V
16493 //                           +-------------+
16494 //                           |     CMP     |
16495 //                           +-------------+
16496 //
16497 // The AND node may be safely removed for some combinations of inputs. In
16498 // particular we need to take into account the extension type of the Input,
16499 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
16500 // width of the input (this can work for any width inputs, the above graph is
16501 // specific to 8 bits.
16502 //
16503 // The specific equations were worked out by generating output tables for each
16504 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
16505 // problem was simplified by working with 4 bit inputs, which means we only
16506 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
16507 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
16508 // patterns present in both extensions (0,7). For every distinct set of
16509 // AddConstant and CompConstants bit patterns we can consider the masked and
16510 // unmasked versions to be equivalent if the result of this function is true for
16511 // all 16 distinct bit patterns of for the current extension type of Input (w0).
16512 //
16513 //   sub      w8, w0, w1
16514 //   and      w10, w8, #0x0f
16515 //   cmp      w8, w2
16516 //   cset     w9, AArch64CC
16517 //   cmp      w10, w2
16518 //   cset     w11, AArch64CC
16519 //   cmp      w9, w11
16520 //   cset     w0, eq
16521 //   ret
16522 //
16523 // Since the above function shows when the outputs are equivalent it defines
16524 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
16525 // would be expensive to run during compiles. The equations below were written
16526 // in a test harness that confirmed they gave equivalent outputs to the above
16527 // for all inputs function, so they can be used determine if the removal is
16528 // legal instead.
16529 //
16530 // isEquivalentMaskless() is the code for testing if the AND can be removed
16531 // factored out of the DAG recognition as the DAG can take several forms.
16532 
16533 static bool isEquivalentMaskless(unsigned CC, unsigned width,
16534                                  ISD::LoadExtType ExtType, int AddConstant,
16535                                  int CompConstant) {
16536   // By being careful about our equations and only writing the in term
16537   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
16538   // make them generally applicable to all bit widths.
16539   int MaxUInt = (1 << width);
16540 
16541   // For the purposes of these comparisons sign extending the type is
16542   // equivalent to zero extending the add and displacing it by half the integer
16543   // width. Provided we are careful and make sure our equations are valid over
16544   // the whole range we can just adjust the input and avoid writing equations
16545   // for sign extended inputs.
16546   if (ExtType == ISD::SEXTLOAD)
16547     AddConstant -= (1 << (width-1));
16548 
16549   switch(CC) {
16550   case AArch64CC::LE:
16551   case AArch64CC::GT:
16552     if ((AddConstant == 0) ||
16553         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
16554         (AddConstant >= 0 && CompConstant < 0) ||
16555         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
16556       return true;
16557     break;
16558   case AArch64CC::LT:
16559   case AArch64CC::GE:
16560     if ((AddConstant == 0) ||
16561         (AddConstant >= 0 && CompConstant <= 0) ||
16562         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
16563       return true;
16564     break;
16565   case AArch64CC::HI:
16566   case AArch64CC::LS:
16567     if ((AddConstant >= 0 && CompConstant < 0) ||
16568        (AddConstant <= 0 && CompConstant >= -1 &&
16569         CompConstant < AddConstant + MaxUInt))
16570       return true;
16571    break;
16572   case AArch64CC::PL:
16573   case AArch64CC::MI:
16574     if ((AddConstant == 0) ||
16575         (AddConstant > 0 && CompConstant <= 0) ||
16576         (AddConstant < 0 && CompConstant <= AddConstant))
16577       return true;
16578     break;
16579   case AArch64CC::LO:
16580   case AArch64CC::HS:
16581     if ((AddConstant >= 0 && CompConstant <= 0) ||
16582         (AddConstant <= 0 && CompConstant >= 0 &&
16583          CompConstant <= AddConstant + MaxUInt))
16584       return true;
16585     break;
16586   case AArch64CC::EQ:
16587   case AArch64CC::NE:
16588     if ((AddConstant > 0 && CompConstant < 0) ||
16589         (AddConstant < 0 && CompConstant >= 0 &&
16590          CompConstant < AddConstant + MaxUInt) ||
16591         (AddConstant >= 0 && CompConstant >= 0 &&
16592          CompConstant >= AddConstant) ||
16593         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
16594       return true;
16595     break;
16596   case AArch64CC::VS:
16597   case AArch64CC::VC:
16598   case AArch64CC::AL:
16599   case AArch64CC::NV:
16600     return true;
16601   case AArch64CC::Invalid:
16602     break;
16603   }
16604 
16605   return false;
16606 }
16607 
16608 static
16609 SDValue performCONDCombine(SDNode *N,
16610                            TargetLowering::DAGCombinerInfo &DCI,
16611                            SelectionDAG &DAG, unsigned CCIndex,
16612                            unsigned CmpIndex) {
16613   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
16614   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
16615   unsigned CondOpcode = SubsNode->getOpcode();
16616 
16617   if (CondOpcode != AArch64ISD::SUBS)
16618     return SDValue();
16619 
16620   // There is a SUBS feeding this condition. Is it fed by a mask we can
16621   // use?
16622 
16623   SDNode *AndNode = SubsNode->getOperand(0).getNode();
16624   unsigned MaskBits = 0;
16625 
16626   if (AndNode->getOpcode() != ISD::AND)
16627     return SDValue();
16628 
16629   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
16630     uint32_t CNV = CN->getZExtValue();
16631     if (CNV == 255)
16632       MaskBits = 8;
16633     else if (CNV == 65535)
16634       MaskBits = 16;
16635   }
16636 
16637   if (!MaskBits)
16638     return SDValue();
16639 
16640   SDValue AddValue = AndNode->getOperand(0);
16641 
16642   if (AddValue.getOpcode() != ISD::ADD)
16643     return SDValue();
16644 
16645   // The basic dag structure is correct, grab the inputs and validate them.
16646 
16647   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
16648   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
16649   SDValue SubsInputValue = SubsNode->getOperand(1);
16650 
16651   // The mask is present and the provenance of all the values is a smaller type,
16652   // lets see if the mask is superfluous.
16653 
16654   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
16655       !isa<ConstantSDNode>(SubsInputValue.getNode()))
16656     return SDValue();
16657 
16658   ISD::LoadExtType ExtType;
16659 
16660   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
16661       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
16662       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
16663     return SDValue();
16664 
16665   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
16666                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
16667                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
16668     return SDValue();
16669 
16670   // The AND is not necessary, remove it.
16671 
16672   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
16673                                SubsNode->getValueType(1));
16674   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
16675 
16676   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
16677   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
16678 
16679   return SDValue(N, 0);
16680 }
16681 
16682 // Optimize compare with zero and branch.
16683 static SDValue performBRCONDCombine(SDNode *N,
16684                                     TargetLowering::DAGCombinerInfo &DCI,
16685                                     SelectionDAG &DAG) {
16686   MachineFunction &MF = DAG.getMachineFunction();
16687   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
16688   // will not be produced, as they are conditional branch instructions that do
16689   // not set flags.
16690   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
16691     return SDValue();
16692 
16693   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
16694     N = NV.getNode();
16695   SDValue Chain = N->getOperand(0);
16696   SDValue Dest = N->getOperand(1);
16697   SDValue CCVal = N->getOperand(2);
16698   SDValue Cmp = N->getOperand(3);
16699 
16700   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
16701   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
16702   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
16703     return SDValue();
16704 
16705   unsigned CmpOpc = Cmp.getOpcode();
16706   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
16707     return SDValue();
16708 
16709   // Only attempt folding if there is only one use of the flag and no use of the
16710   // value.
16711   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
16712     return SDValue();
16713 
16714   SDValue LHS = Cmp.getOperand(0);
16715   SDValue RHS = Cmp.getOperand(1);
16716 
16717   assert(LHS.getValueType() == RHS.getValueType() &&
16718          "Expected the value type to be the same for both operands!");
16719   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
16720     return SDValue();
16721 
16722   if (isNullConstant(LHS))
16723     std::swap(LHS, RHS);
16724 
16725   if (!isNullConstant(RHS))
16726     return SDValue();
16727 
16728   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
16729       LHS.getOpcode() == ISD::SRL)
16730     return SDValue();
16731 
16732   // Fold the compare into the branch instruction.
16733   SDValue BR;
16734   if (CC == AArch64CC::EQ)
16735     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
16736   else
16737     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
16738 
16739   // Do not add new nodes to DAG combiner worklist.
16740   DCI.CombineTo(N, BR, false);
16741 
16742   return SDValue();
16743 }
16744 
16745 // Optimize CSEL instructions
16746 static SDValue performCSELCombine(SDNode *N,
16747                                   TargetLowering::DAGCombinerInfo &DCI,
16748                                   SelectionDAG &DAG) {
16749   // CSEL x, x, cc -> x
16750   if (N->getOperand(0) == N->getOperand(1))
16751     return N->getOperand(0);
16752 
16753   return performCONDCombine(N, DCI, DAG, 2, 3);
16754 }
16755 
16756 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16757   assert(N->getOpcode() == ISD::SETCC && "Unexpected opcode!");
16758   SDValue LHS = N->getOperand(0);
16759   SDValue RHS = N->getOperand(1);
16760   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
16761 
16762   // setcc (csel 0, 1, cond, X), 1, ne ==> csel 0, 1, !cond, X
16763   if (Cond == ISD::SETNE && isOneConstant(RHS) &&
16764       LHS->getOpcode() == AArch64ISD::CSEL &&
16765       isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
16766       LHS->hasOneUse()) {
16767     SDLoc DL(N);
16768 
16769     // Invert CSEL's condition.
16770     auto *OpCC = cast<ConstantSDNode>(LHS.getOperand(2));
16771     auto OldCond = static_cast<AArch64CC::CondCode>(OpCC->getZExtValue());
16772     auto NewCond = getInvertedCondCode(OldCond);
16773 
16774     // csel 0, 1, !cond, X
16775     SDValue CSEL =
16776         DAG.getNode(AArch64ISD::CSEL, DL, LHS.getValueType(), LHS.getOperand(0),
16777                     LHS.getOperand(1), DAG.getConstant(NewCond, DL, MVT::i32),
16778                     LHS.getOperand(3));
16779     return DAG.getZExtOrTrunc(CSEL, DL, N->getValueType(0));
16780   }
16781 
16782   return SDValue();
16783 }
16784 
16785 static SDValue performSetCCPunpkCombine(SDNode *N, SelectionDAG &DAG) {
16786   // setcc_merge_zero pred
16787   //   (sign_extend (extract_subvector (setcc_merge_zero ... pred ...))), 0, ne
16788   //   => extract_subvector (inner setcc_merge_zero)
16789   SDValue Pred = N->getOperand(0);
16790   SDValue LHS = N->getOperand(1);
16791   SDValue RHS = N->getOperand(2);
16792   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
16793 
16794   if (Cond != ISD::SETNE || !isZerosVector(RHS.getNode()) ||
16795       LHS->getOpcode() != ISD::SIGN_EXTEND)
16796     return SDValue();
16797 
16798   SDValue Extract = LHS->getOperand(0);
16799   if (Extract->getOpcode() != ISD::EXTRACT_SUBVECTOR ||
16800       Extract->getValueType(0) != N->getValueType(0) ||
16801       Extract->getConstantOperandVal(1) != 0)
16802     return SDValue();
16803 
16804   SDValue InnerSetCC = Extract->getOperand(0);
16805   if (InnerSetCC->getOpcode() != AArch64ISD::SETCC_MERGE_ZERO)
16806     return SDValue();
16807 
16808   // By this point we've effectively got
16809   // zero_inactive_lanes_and_trunc_i1(sext_i1(A)). If we can prove A's inactive
16810   // lanes are already zero then the trunc(sext()) sequence is redundant and we
16811   // can operate on A directly.
16812   SDValue InnerPred = InnerSetCC.getOperand(0);
16813   if (Pred.getOpcode() == AArch64ISD::PTRUE &&
16814       InnerPred.getOpcode() == AArch64ISD::PTRUE &&
16815       Pred.getConstantOperandVal(0) == InnerPred.getConstantOperandVal(0) &&
16816       Pred->getConstantOperandVal(0) >= AArch64SVEPredPattern::vl1 &&
16817       Pred->getConstantOperandVal(0) <= AArch64SVEPredPattern::vl256)
16818     return Extract;
16819 
16820   return SDValue();
16821 }
16822 
16823 static SDValue performSetccMergeZeroCombine(SDNode *N, SelectionDAG &DAG) {
16824   assert(N->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
16825          "Unexpected opcode!");
16826 
16827   SDValue Pred = N->getOperand(0);
16828   SDValue LHS = N->getOperand(1);
16829   SDValue RHS = N->getOperand(2);
16830   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
16831 
16832   // setcc_merge_zero pred (sign_extend (setcc_merge_zero ... pred ...)), 0, ne
16833   //    => inner setcc_merge_zero
16834   if (Cond == ISD::SETNE && isZerosVector(RHS.getNode()) &&
16835       LHS->getOpcode() == ISD::SIGN_EXTEND &&
16836       LHS->getOperand(0)->getValueType(0) == N->getValueType(0) &&
16837       LHS->getOperand(0)->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
16838       LHS->getOperand(0)->getOperand(0) == Pred)
16839     return LHS->getOperand(0);
16840 
16841   if (SDValue V = performSetCCPunpkCombine(N, DAG))
16842     return V;
16843 
16844   return SDValue();
16845 }
16846 
16847 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
16848 // as well as whether the test should be inverted.  This code is required to
16849 // catch these cases (as opposed to standard dag combines) because
16850 // AArch64ISD::TBZ is matched during legalization.
16851 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
16852                                  SelectionDAG &DAG) {
16853 
16854   if (!Op->hasOneUse())
16855     return Op;
16856 
16857   // We don't handle undef/constant-fold cases below, as they should have
16858   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
16859   // etc.)
16860 
16861   // (tbz (trunc x), b) -> (tbz x, b)
16862   // This case is just here to enable more of the below cases to be caught.
16863   if (Op->getOpcode() == ISD::TRUNCATE &&
16864       Bit < Op->getValueType(0).getSizeInBits()) {
16865     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16866   }
16867 
16868   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
16869   if (Op->getOpcode() == ISD::ANY_EXTEND &&
16870       Bit < Op->getOperand(0).getValueSizeInBits()) {
16871     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16872   }
16873 
16874   if (Op->getNumOperands() != 2)
16875     return Op;
16876 
16877   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
16878   if (!C)
16879     return Op;
16880 
16881   switch (Op->getOpcode()) {
16882   default:
16883     return Op;
16884 
16885   // (tbz (and x, m), b) -> (tbz x, b)
16886   case ISD::AND:
16887     if ((C->getZExtValue() >> Bit) & 1)
16888       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16889     return Op;
16890 
16891   // (tbz (shl x, c), b) -> (tbz x, b-c)
16892   case ISD::SHL:
16893     if (C->getZExtValue() <= Bit &&
16894         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
16895       Bit = Bit - C->getZExtValue();
16896       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16897     }
16898     return Op;
16899 
16900   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
16901   case ISD::SRA:
16902     Bit = Bit + C->getZExtValue();
16903     if (Bit >= Op->getValueType(0).getSizeInBits())
16904       Bit = Op->getValueType(0).getSizeInBits() - 1;
16905     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16906 
16907   // (tbz (srl x, c), b) -> (tbz x, b+c)
16908   case ISD::SRL:
16909     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
16910       Bit = Bit + C->getZExtValue();
16911       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16912     }
16913     return Op;
16914 
16915   // (tbz (xor x, -1), b) -> (tbnz x, b)
16916   case ISD::XOR:
16917     if ((C->getZExtValue() >> Bit) & 1)
16918       Invert = !Invert;
16919     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16920   }
16921 }
16922 
16923 // Optimize test single bit zero/non-zero and branch.
16924 static SDValue performTBZCombine(SDNode *N,
16925                                  TargetLowering::DAGCombinerInfo &DCI,
16926                                  SelectionDAG &DAG) {
16927   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
16928   bool Invert = false;
16929   SDValue TestSrc = N->getOperand(1);
16930   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
16931 
16932   if (TestSrc == NewTestSrc)
16933     return SDValue();
16934 
16935   unsigned NewOpc = N->getOpcode();
16936   if (Invert) {
16937     if (NewOpc == AArch64ISD::TBZ)
16938       NewOpc = AArch64ISD::TBNZ;
16939     else {
16940       assert(NewOpc == AArch64ISD::TBNZ);
16941       NewOpc = AArch64ISD::TBZ;
16942     }
16943   }
16944 
16945   SDLoc DL(N);
16946   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
16947                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
16948 }
16949 
16950 // vselect (v1i1 setcc) ->
16951 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
16952 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
16953 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
16954 // such VSELECT.
16955 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
16956   SDValue N0 = N->getOperand(0);
16957   EVT CCVT = N0.getValueType();
16958 
16959   if (isAllActivePredicate(DAG, N0))
16960     return N->getOperand(1);
16961 
16962   if (isAllInactivePredicate(N0))
16963     return N->getOperand(2);
16964 
16965   // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform
16966   // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
16967   // supported types.
16968   SDValue SetCC = N->getOperand(0);
16969   if (SetCC.getOpcode() == ISD::SETCC &&
16970       SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) {
16971     SDValue CmpLHS = SetCC.getOperand(0);
16972     EVT VT = CmpLHS.getValueType();
16973     SDNode *CmpRHS = SetCC.getOperand(1).getNode();
16974     SDNode *SplatLHS = N->getOperand(1).getNode();
16975     SDNode *SplatRHS = N->getOperand(2).getNode();
16976     APInt SplatLHSVal;
16977     if (CmpLHS.getValueType() == N->getOperand(1).getValueType() &&
16978         VT.isSimple() &&
16979         is_contained(
16980             makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
16981                           MVT::v2i32, MVT::v4i32, MVT::v2i64}),
16982             VT.getSimpleVT().SimpleTy) &&
16983         ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) &&
16984         SplatLHSVal.isOne() && ISD::isConstantSplatVectorAllOnes(CmpRHS) &&
16985         ISD::isConstantSplatVectorAllOnes(SplatRHS)) {
16986       unsigned NumElts = VT.getVectorNumElements();
16987       SmallVector<SDValue, 8> Ops(
16988           NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N),
16989                                    VT.getScalarType()));
16990       SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops);
16991 
16992       auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val);
16993       auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1));
16994       return Or;
16995     }
16996   }
16997 
16998   if (N0.getOpcode() != ISD::SETCC ||
16999       CCVT.getVectorElementCount() != ElementCount::getFixed(1) ||
17000       CCVT.getVectorElementType() != MVT::i1)
17001     return SDValue();
17002 
17003   EVT ResVT = N->getValueType(0);
17004   EVT CmpVT = N0.getOperand(0).getValueType();
17005   // Only combine when the result type is of the same size as the compared
17006   // operands.
17007   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
17008     return SDValue();
17009 
17010   SDValue IfTrue = N->getOperand(1);
17011   SDValue IfFalse = N->getOperand(2);
17012   SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
17013                        N0.getOperand(0), N0.getOperand(1),
17014                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
17015   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
17016                      IfTrue, IfFalse);
17017 }
17018 
17019 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
17020 /// the compare-mask instructions rather than going via NZCV, even if LHS and
17021 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
17022 /// with a vector one followed by a DUP shuffle on the result.
17023 static SDValue performSelectCombine(SDNode *N,
17024                                     TargetLowering::DAGCombinerInfo &DCI) {
17025   SelectionDAG &DAG = DCI.DAG;
17026   SDValue N0 = N->getOperand(0);
17027   EVT ResVT = N->getValueType(0);
17028 
17029   if (N0.getOpcode() != ISD::SETCC)
17030     return SDValue();
17031 
17032   if (ResVT.isScalableVector())
17033     return SDValue();
17034 
17035   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
17036   // scalar SetCCResultType. We also don't expect vectors, because we assume
17037   // that selects fed by vector SETCCs are canonicalized to VSELECT.
17038   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
17039          "Scalar-SETCC feeding SELECT has unexpected result type!");
17040 
17041   // If NumMaskElts == 0, the comparison is larger than select result. The
17042   // largest real NEON comparison is 64-bits per lane, which means the result is
17043   // at most 32-bits and an illegal vector. Just bail out for now.
17044   EVT SrcVT = N0.getOperand(0).getValueType();
17045 
17046   // Don't try to do this optimization when the setcc itself has i1 operands.
17047   // There are no legal vectors of i1, so this would be pointless.
17048   if (SrcVT == MVT::i1)
17049     return SDValue();
17050 
17051   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
17052   if (!ResVT.isVector() || NumMaskElts == 0)
17053     return SDValue();
17054 
17055   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
17056   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
17057 
17058   // Also bail out if the vector CCVT isn't the same size as ResVT.
17059   // This can happen if the SETCC operand size doesn't divide the ResVT size
17060   // (e.g., f64 vs v3f32).
17061   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
17062     return SDValue();
17063 
17064   // Make sure we didn't create illegal types, if we're not supposed to.
17065   assert(DCI.isBeforeLegalize() ||
17066          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
17067 
17068   // First perform a vector comparison, where lane 0 is the one we're interested
17069   // in.
17070   SDLoc DL(N0);
17071   SDValue LHS =
17072       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
17073   SDValue RHS =
17074       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
17075   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
17076 
17077   // Now duplicate the comparison mask we want across all other lanes.
17078   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
17079   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
17080   Mask = DAG.getNode(ISD::BITCAST, DL,
17081                      ResVT.changeVectorElementTypeToInteger(), Mask);
17082 
17083   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
17084 }
17085 
17086 /// Get rid of unnecessary NVCASTs (that don't change the type).
17087 static SDValue performNVCASTCombine(SDNode *N) {
17088   if (N->getValueType(0) == N->getOperand(0).getValueType())
17089     return N->getOperand(0);
17090 
17091   return SDValue();
17092 }
17093 
17094 // If all users of the globaladdr are of the form (globaladdr + constant), find
17095 // the smallest constant, fold it into the globaladdr's offset and rewrite the
17096 // globaladdr as (globaladdr + constant) - constant.
17097 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
17098                                            const AArch64Subtarget *Subtarget,
17099                                            const TargetMachine &TM) {
17100   auto *GN = cast<GlobalAddressSDNode>(N);
17101   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
17102       AArch64II::MO_NO_FLAG)
17103     return SDValue();
17104 
17105   uint64_t MinOffset = -1ull;
17106   for (SDNode *N : GN->uses()) {
17107     if (N->getOpcode() != ISD::ADD)
17108       return SDValue();
17109     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
17110     if (!C)
17111       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17112     if (!C)
17113       return SDValue();
17114     MinOffset = std::min(MinOffset, C->getZExtValue());
17115   }
17116   uint64_t Offset = MinOffset + GN->getOffset();
17117 
17118   // Require that the new offset is larger than the existing one. Otherwise, we
17119   // can end up oscillating between two possible DAGs, for example,
17120   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
17121   if (Offset <= uint64_t(GN->getOffset()))
17122     return SDValue();
17123 
17124   // Check whether folding this offset is legal. It must not go out of bounds of
17125   // the referenced object to avoid violating the code model, and must be
17126   // smaller than 2^20 because this is the largest offset expressible in all
17127   // object formats. (The IMAGE_REL_ARM64_PAGEBASE_REL21 relocation in COFF
17128   // stores an immediate signed 21 bit offset.)
17129   //
17130   // This check also prevents us from folding negative offsets, which will end
17131   // up being treated in the same way as large positive ones. They could also
17132   // cause code model violations, and aren't really common enough to matter.
17133   if (Offset >= (1 << 20))
17134     return SDValue();
17135 
17136   const GlobalValue *GV = GN->getGlobal();
17137   Type *T = GV->getValueType();
17138   if (!T->isSized() ||
17139       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
17140     return SDValue();
17141 
17142   SDLoc DL(GN);
17143   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
17144   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
17145                      DAG.getConstant(MinOffset, DL, MVT::i64));
17146 }
17147 
17148 // Turns the vector of indices into a vector of byte offstes by scaling Offset
17149 // by (BitWidth / 8).
17150 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
17151                                           SDLoc DL, unsigned BitWidth) {
17152   assert(Offset.getValueType().isScalableVector() &&
17153          "This method is only for scalable vectors of offsets");
17154 
17155   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
17156   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
17157 
17158   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
17159 }
17160 
17161 /// Check if the value of \p OffsetInBytes can be used as an immediate for
17162 /// the gather load/prefetch and scatter store instructions with vector base and
17163 /// immediate offset addressing mode:
17164 ///
17165 ///      [<Zn>.[S|D]{, #<imm>}]
17166 ///
17167 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
17168 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
17169                                                   unsigned ScalarSizeInBytes) {
17170   // The immediate is not a multiple of the scalar size.
17171   if (OffsetInBytes % ScalarSizeInBytes)
17172     return false;
17173 
17174   // The immediate is out of range.
17175   if (OffsetInBytes / ScalarSizeInBytes > 31)
17176     return false;
17177 
17178   return true;
17179 }
17180 
17181 /// Check if the value of \p Offset represents a valid immediate for the SVE
17182 /// gather load/prefetch and scatter store instructiona with vector base and
17183 /// immediate offset addressing mode:
17184 ///
17185 ///      [<Zn>.[S|D]{, #<imm>}]
17186 ///
17187 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
17188 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
17189                                            unsigned ScalarSizeInBytes) {
17190   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
17191   return OffsetConst && isValidImmForSVEVecImmAddrMode(
17192                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
17193 }
17194 
17195 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
17196                                           unsigned Opcode,
17197                                           bool OnlyPackedOffsets = true) {
17198   const SDValue Src = N->getOperand(2);
17199   const EVT SrcVT = Src->getValueType(0);
17200   assert(SrcVT.isScalableVector() &&
17201          "Scatter stores are only possible for SVE vectors");
17202 
17203   SDLoc DL(N);
17204   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
17205 
17206   // Make sure that source data will fit into an SVE register
17207   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
17208     return SDValue();
17209 
17210   // For FPs, ACLE only supports _packed_ single and double precision types.
17211   if (SrcElVT.isFloatingPoint())
17212     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
17213       return SDValue();
17214 
17215   // Depending on the addressing mode, this is either a pointer or a vector of
17216   // pointers (that fits into one register)
17217   SDValue Base = N->getOperand(4);
17218   // Depending on the addressing mode, this is either a single offset or a
17219   // vector of offsets  (that fits into one register)
17220   SDValue Offset = N->getOperand(5);
17221 
17222   // For "scalar + vector of indices", just scale the indices. This only
17223   // applies to non-temporal scatters because there's no instruction that takes
17224   // indicies.
17225   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
17226     Offset =
17227         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
17228     Opcode = AArch64ISD::SSTNT1_PRED;
17229   }
17230 
17231   // In the case of non-temporal gather loads there's only one SVE instruction
17232   // per data-size: "scalar + vector", i.e.
17233   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
17234   // Since we do have intrinsics that allow the arguments to be in a different
17235   // order, we may need to swap them to match the spec.
17236   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
17237     std::swap(Base, Offset);
17238 
17239   // SST1_IMM requires that the offset is an immediate that is:
17240   //    * a multiple of #SizeInBytes,
17241   //    * in the range [0, 31 x #SizeInBytes],
17242   // where #SizeInBytes is the size in bytes of the stored items. For
17243   // immediates outside that range and non-immediate scalar offsets use SST1 or
17244   // SST1_UXTW instead.
17245   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
17246     if (!isValidImmForSVEVecImmAddrMode(Offset,
17247                                         SrcVT.getScalarSizeInBits() / 8)) {
17248       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
17249         Opcode = AArch64ISD::SST1_UXTW_PRED;
17250       else
17251         Opcode = AArch64ISD::SST1_PRED;
17252 
17253       std::swap(Base, Offset);
17254     }
17255   }
17256 
17257   auto &TLI = DAG.getTargetLoweringInfo();
17258   if (!TLI.isTypeLegal(Base.getValueType()))
17259     return SDValue();
17260 
17261   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
17262   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
17263   // nxv2i64. Legalize accordingly.
17264   if (!OnlyPackedOffsets &&
17265       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
17266     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
17267 
17268   if (!TLI.isTypeLegal(Offset.getValueType()))
17269     return SDValue();
17270 
17271   // Source value type that is representable in hardware
17272   EVT HwSrcVt = getSVEContainerType(SrcVT);
17273 
17274   // Keep the original type of the input data to store - this is needed to be
17275   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
17276   // FP values we want the integer equivalent, so just use HwSrcVt.
17277   SDValue InputVT = DAG.getValueType(SrcVT);
17278   if (SrcVT.isFloatingPoint())
17279     InputVT = DAG.getValueType(HwSrcVt);
17280 
17281   SDVTList VTs = DAG.getVTList(MVT::Other);
17282   SDValue SrcNew;
17283 
17284   if (Src.getValueType().isFloatingPoint())
17285     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
17286   else
17287     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
17288 
17289   SDValue Ops[] = {N->getOperand(0), // Chain
17290                    SrcNew,
17291                    N->getOperand(3), // Pg
17292                    Base,
17293                    Offset,
17294                    InputVT};
17295 
17296   return DAG.getNode(Opcode, DL, VTs, Ops);
17297 }
17298 
17299 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
17300                                         unsigned Opcode,
17301                                         bool OnlyPackedOffsets = true) {
17302   const EVT RetVT = N->getValueType(0);
17303   assert(RetVT.isScalableVector() &&
17304          "Gather loads are only possible for SVE vectors");
17305 
17306   SDLoc DL(N);
17307 
17308   // Make sure that the loaded data will fit into an SVE register
17309   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
17310     return SDValue();
17311 
17312   // Depending on the addressing mode, this is either a pointer or a vector of
17313   // pointers (that fits into one register)
17314   SDValue Base = N->getOperand(3);
17315   // Depending on the addressing mode, this is either a single offset or a
17316   // vector of offsets  (that fits into one register)
17317   SDValue Offset = N->getOperand(4);
17318 
17319   // For "scalar + vector of indices", just scale the indices. This only
17320   // applies to non-temporal gathers because there's no instruction that takes
17321   // indicies.
17322   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
17323     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
17324                                         RetVT.getScalarSizeInBits());
17325     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
17326   }
17327 
17328   // In the case of non-temporal gather loads there's only one SVE instruction
17329   // per data-size: "scalar + vector", i.e.
17330   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
17331   // Since we do have intrinsics that allow the arguments to be in a different
17332   // order, we may need to swap them to match the spec.
17333   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
17334       Offset.getValueType().isVector())
17335     std::swap(Base, Offset);
17336 
17337   // GLD{FF}1_IMM requires that the offset is an immediate that is:
17338   //    * a multiple of #SizeInBytes,
17339   //    * in the range [0, 31 x #SizeInBytes],
17340   // where #SizeInBytes is the size in bytes of the loaded items. For
17341   // immediates outside that range and non-immediate scalar offsets use
17342   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
17343   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
17344       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
17345     if (!isValidImmForSVEVecImmAddrMode(Offset,
17346                                         RetVT.getScalarSizeInBits() / 8)) {
17347       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
17348         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
17349                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
17350                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
17351       else
17352         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
17353                      ? AArch64ISD::GLD1_MERGE_ZERO
17354                      : AArch64ISD::GLDFF1_MERGE_ZERO;
17355 
17356       std::swap(Base, Offset);
17357     }
17358   }
17359 
17360   auto &TLI = DAG.getTargetLoweringInfo();
17361   if (!TLI.isTypeLegal(Base.getValueType()))
17362     return SDValue();
17363 
17364   // Some gather load variants allow unpacked offsets, but only as nxv2i32
17365   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
17366   // nxv2i64. Legalize accordingly.
17367   if (!OnlyPackedOffsets &&
17368       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
17369     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
17370 
17371   // Return value type that is representable in hardware
17372   EVT HwRetVt = getSVEContainerType(RetVT);
17373 
17374   // Keep the original output value type around - this is needed to be able to
17375   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
17376   // values we want the integer equivalent, so just use HwRetVT.
17377   SDValue OutVT = DAG.getValueType(RetVT);
17378   if (RetVT.isFloatingPoint())
17379     OutVT = DAG.getValueType(HwRetVt);
17380 
17381   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
17382   SDValue Ops[] = {N->getOperand(0), // Chain
17383                    N->getOperand(2), // Pg
17384                    Base, Offset, OutVT};
17385 
17386   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
17387   SDValue LoadChain = SDValue(Load.getNode(), 1);
17388 
17389   if (RetVT.isInteger() && (RetVT != HwRetVt))
17390     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
17391 
17392   // If the original return value was FP, bitcast accordingly. Doing it here
17393   // means that we can avoid adding TableGen patterns for FPs.
17394   if (RetVT.isFloatingPoint())
17395     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
17396 
17397   return DAG.getMergeValues({Load, LoadChain}, DL);
17398 }
17399 
17400 static SDValue
17401 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
17402                               SelectionDAG &DAG) {
17403   SDLoc DL(N);
17404   SDValue Src = N->getOperand(0);
17405   unsigned Opc = Src->getOpcode();
17406 
17407   // Sign extend of an unsigned unpack -> signed unpack
17408   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
17409 
17410     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
17411                                                : AArch64ISD::SUNPKLO;
17412 
17413     // Push the sign extend to the operand of the unpack
17414     // This is necessary where, for example, the operand of the unpack
17415     // is another unpack:
17416     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
17417     // ->
17418     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
17419     // ->
17420     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
17421     SDValue ExtOp = Src->getOperand(0);
17422     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
17423     EVT EltTy = VT.getVectorElementType();
17424     (void)EltTy;
17425 
17426     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
17427            "Sign extending from an invalid type");
17428 
17429     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
17430 
17431     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
17432                               ExtOp, DAG.getValueType(ExtVT));
17433 
17434     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
17435   }
17436 
17437   if (DCI.isBeforeLegalizeOps())
17438     return SDValue();
17439 
17440   if (!EnableCombineMGatherIntrinsics)
17441     return SDValue();
17442 
17443   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
17444   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
17445   unsigned NewOpc;
17446   unsigned MemVTOpNum = 4;
17447   switch (Opc) {
17448   case AArch64ISD::LD1_MERGE_ZERO:
17449     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
17450     MemVTOpNum = 3;
17451     break;
17452   case AArch64ISD::LDNF1_MERGE_ZERO:
17453     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
17454     MemVTOpNum = 3;
17455     break;
17456   case AArch64ISD::LDFF1_MERGE_ZERO:
17457     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
17458     MemVTOpNum = 3;
17459     break;
17460   case AArch64ISD::GLD1_MERGE_ZERO:
17461     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
17462     break;
17463   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
17464     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
17465     break;
17466   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
17467     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
17468     break;
17469   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
17470     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
17471     break;
17472   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
17473     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
17474     break;
17475   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
17476     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
17477     break;
17478   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
17479     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
17480     break;
17481   case AArch64ISD::GLDFF1_MERGE_ZERO:
17482     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
17483     break;
17484   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
17485     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
17486     break;
17487   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
17488     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
17489     break;
17490   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
17491     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
17492     break;
17493   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
17494     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
17495     break;
17496   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
17497     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
17498     break;
17499   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
17500     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
17501     break;
17502   case AArch64ISD::GLDNT1_MERGE_ZERO:
17503     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
17504     break;
17505   default:
17506     return SDValue();
17507   }
17508 
17509   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
17510   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
17511 
17512   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
17513     return SDValue();
17514 
17515   EVT DstVT = N->getValueType(0);
17516   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
17517 
17518   SmallVector<SDValue, 5> Ops;
17519   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
17520     Ops.push_back(Src->getOperand(I));
17521 
17522   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
17523   DCI.CombineTo(N, ExtLoad);
17524   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
17525 
17526   // Return N so it doesn't get rechecked
17527   return SDValue(N, 0);
17528 }
17529 
17530 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
17531 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
17532 /// != nxv2i32) do not need legalization.
17533 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
17534   const unsigned OffsetPos = 4;
17535   SDValue Offset = N->getOperand(OffsetPos);
17536 
17537   // Not an unpacked vector, bail out.
17538   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
17539     return SDValue();
17540 
17541   // Extend the unpacked offset vector to 64-bit lanes.
17542   SDLoc DL(N);
17543   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
17544   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
17545   // Replace the offset operand with the 64-bit one.
17546   Ops[OffsetPos] = Offset;
17547 
17548   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
17549 }
17550 
17551 /// Combines a node carrying the intrinsic
17552 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
17553 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
17554 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
17555 /// sve gather prefetch instruction with vector plus immediate addressing mode.
17556 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
17557                                                unsigned ScalarSizeInBytes) {
17558   const unsigned ImmPos = 4, OffsetPos = 3;
17559   // No need to combine the node if the immediate is valid...
17560   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
17561     return SDValue();
17562 
17563   // ...otherwise swap the offset base with the offset...
17564   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
17565   std::swap(Ops[ImmPos], Ops[OffsetPos]);
17566   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
17567   // `aarch64_sve_prfb_gather_uxtw_index`.
17568   SDLoc DL(N);
17569   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
17570                            MVT::i64);
17571 
17572   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
17573 }
17574 
17575 // Return true if the vector operation can guarantee only the first lane of its
17576 // result contains data, with all bits in other lanes set to zero.
17577 static bool isLanes1toNKnownZero(SDValue Op) {
17578   switch (Op.getOpcode()) {
17579   default:
17580     return false;
17581   case AArch64ISD::ANDV_PRED:
17582   case AArch64ISD::EORV_PRED:
17583   case AArch64ISD::FADDA_PRED:
17584   case AArch64ISD::FADDV_PRED:
17585   case AArch64ISD::FMAXNMV_PRED:
17586   case AArch64ISD::FMAXV_PRED:
17587   case AArch64ISD::FMINNMV_PRED:
17588   case AArch64ISD::FMINV_PRED:
17589   case AArch64ISD::ORV_PRED:
17590   case AArch64ISD::SADDV_PRED:
17591   case AArch64ISD::SMAXV_PRED:
17592   case AArch64ISD::SMINV_PRED:
17593   case AArch64ISD::UADDV_PRED:
17594   case AArch64ISD::UMAXV_PRED:
17595   case AArch64ISD::UMINV_PRED:
17596     return true;
17597   }
17598 }
17599 
17600 static SDValue removeRedundantInsertVectorElt(SDNode *N) {
17601   assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Unexpected node!");
17602   SDValue InsertVec = N->getOperand(0);
17603   SDValue InsertElt = N->getOperand(1);
17604   SDValue InsertIdx = N->getOperand(2);
17605 
17606   // We only care about inserts into the first element...
17607   if (!isNullConstant(InsertIdx))
17608     return SDValue();
17609   // ...of a zero'd vector...
17610   if (!ISD::isConstantSplatVectorAllZeros(InsertVec.getNode()))
17611     return SDValue();
17612   // ...where the inserted data was previously extracted...
17613   if (InsertElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17614     return SDValue();
17615 
17616   SDValue ExtractVec = InsertElt.getOperand(0);
17617   SDValue ExtractIdx = InsertElt.getOperand(1);
17618 
17619   // ...from the first element of a vector.
17620   if (!isNullConstant(ExtractIdx))
17621     return SDValue();
17622 
17623   // If we get here we are effectively trying to zero lanes 1-N of a vector.
17624 
17625   // Ensure there's no type conversion going on.
17626   if (N->getValueType(0) != ExtractVec.getValueType())
17627     return SDValue();
17628 
17629   if (!isLanes1toNKnownZero(ExtractVec))
17630     return SDValue();
17631 
17632   // The explicit zeroing is redundant.
17633   return ExtractVec;
17634 }
17635 
17636 static SDValue
17637 performInsertVectorEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
17638   if (SDValue Res = removeRedundantInsertVectorElt(N))
17639     return Res;
17640 
17641   return performPostLD1Combine(N, DCI, true);
17642 }
17643 
17644 SDValue performSVESpliceCombine(SDNode *N, SelectionDAG &DAG) {
17645   EVT Ty = N->getValueType(0);
17646   if (Ty.isInteger())
17647     return SDValue();
17648 
17649   EVT IntTy = Ty.changeVectorElementTypeToInteger();
17650   EVT ExtIntTy = getPackedSVEVectorVT(IntTy.getVectorElementCount());
17651   if (ExtIntTy.getVectorElementType().getScalarSizeInBits() <
17652       IntTy.getVectorElementType().getScalarSizeInBits())
17653     return SDValue();
17654 
17655   SDLoc DL(N);
17656   SDValue LHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(0)),
17657                                      DL, ExtIntTy);
17658   SDValue RHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(1)),
17659                                      DL, ExtIntTy);
17660   SDValue Idx = N->getOperand(2);
17661   SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ExtIntTy, LHS, RHS, Idx);
17662   SDValue Trunc = DAG.getAnyExtOrTrunc(Splice, DL, IntTy);
17663   return DAG.getBitcast(Ty, Trunc);
17664 }
17665 
17666 SDValue performFPExtendCombine(SDNode *N, SelectionDAG &DAG,
17667                                TargetLowering::DAGCombinerInfo &DCI,
17668                                const AArch64Subtarget *Subtarget) {
17669   SDValue N0 = N->getOperand(0);
17670   EVT VT = N->getValueType(0);
17671 
17672   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
17673   if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::FP_ROUND)
17674     return SDValue();
17675 
17676   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
17677   // We purposefully don't care about legality of the nodes here as we know
17678   // they can be split down into something legal.
17679   if (DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(N0.getNode()) &&
17680       N0.hasOneUse() && Subtarget->useSVEForFixedLengthVectors() &&
17681       VT.isFixedLengthVector() &&
17682       VT.getFixedSizeInBits() >= Subtarget->getMinSVEVectorSizeInBits()) {
17683     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
17684     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
17685                                      LN0->getChain(), LN0->getBasePtr(),
17686                                      N0.getValueType(), LN0->getMemOperand());
17687     DCI.CombineTo(N, ExtLoad);
17688     DCI.CombineTo(N0.getNode(),
17689                   DAG.getNode(ISD::FP_ROUND, SDLoc(N0), N0.getValueType(),
17690                               ExtLoad, DAG.getIntPtrConstant(1, SDLoc(N0))),
17691                   ExtLoad.getValue(1));
17692     return SDValue(N, 0); // Return N so it doesn't get rechecked!
17693   }
17694 
17695   return SDValue();
17696 }
17697 
17698 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
17699                                                  DAGCombinerInfo &DCI) const {
17700   SelectionDAG &DAG = DCI.DAG;
17701   switch (N->getOpcode()) {
17702   default:
17703     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
17704     break;
17705   case ISD::ADD:
17706   case ISD::SUB:
17707     return performAddSubCombine(N, DCI, DAG);
17708   case ISD::XOR:
17709     return performXorCombine(N, DAG, DCI, Subtarget);
17710   case ISD::MUL:
17711     return performMulCombine(N, DAG, DCI, Subtarget);
17712   case ISD::SINT_TO_FP:
17713   case ISD::UINT_TO_FP:
17714     return performIntToFpCombine(N, DAG, Subtarget);
17715   case ISD::FP_TO_SINT:
17716   case ISD::FP_TO_UINT:
17717   case ISD::FP_TO_SINT_SAT:
17718   case ISD::FP_TO_UINT_SAT:
17719     return performFpToIntCombine(N, DAG, DCI, Subtarget);
17720   case ISD::FDIV:
17721     return performFDivCombine(N, DAG, DCI, Subtarget);
17722   case ISD::OR:
17723     return performORCombine(N, DCI, Subtarget);
17724   case ISD::AND:
17725     return performANDCombine(N, DCI);
17726   case ISD::INTRINSIC_WO_CHAIN:
17727     return performIntrinsicCombine(N, DCI, Subtarget);
17728   case ISD::ANY_EXTEND:
17729   case ISD::ZERO_EXTEND:
17730   case ISD::SIGN_EXTEND:
17731     return performExtendCombine(N, DCI, DAG);
17732   case ISD::SIGN_EXTEND_INREG:
17733     return performSignExtendInRegCombine(N, DCI, DAG);
17734   case ISD::TRUNCATE:
17735     return performVectorTruncateCombine(N, DCI, DAG);
17736   case ISD::CONCAT_VECTORS:
17737     return performConcatVectorsCombine(N, DCI, DAG);
17738   case ISD::INSERT_SUBVECTOR:
17739     return performInsertSubvectorCombine(N, DCI, DAG);
17740   case ISD::SELECT:
17741     return performSelectCombine(N, DCI);
17742   case ISD::VSELECT:
17743     return performVSelectCombine(N, DCI.DAG);
17744   case ISD::SETCC:
17745     return performSETCCCombine(N, DAG);
17746   case ISD::LOAD:
17747     if (performTBISimplification(N->getOperand(1), DCI, DAG))
17748       return SDValue(N, 0);
17749     break;
17750   case ISD::STORE:
17751     return performSTORECombine(N, DCI, DAG, Subtarget);
17752   case ISD::VECTOR_SPLICE:
17753     return performSVESpliceCombine(N, DAG);
17754   case ISD::FP_EXTEND:
17755     return performFPExtendCombine(N, DAG, DCI, Subtarget);
17756   case AArch64ISD::BRCOND:
17757     return performBRCONDCombine(N, DCI, DAG);
17758   case AArch64ISD::TBNZ:
17759   case AArch64ISD::TBZ:
17760     return performTBZCombine(N, DCI, DAG);
17761   case AArch64ISD::CSEL:
17762     return performCSELCombine(N, DCI, DAG);
17763   case AArch64ISD::DUP:
17764     return performPostLD1Combine(N, DCI, false);
17765   case AArch64ISD::NVCAST:
17766     return performNVCASTCombine(N);
17767   case AArch64ISD::SPLICE:
17768     return performSpliceCombine(N, DAG);
17769   case AArch64ISD::UUNPKLO:
17770   case AArch64ISD::UUNPKHI:
17771     return performUnpackCombine(N, DAG);
17772   case AArch64ISD::UZP1:
17773     return performUzpCombine(N, DAG);
17774   case AArch64ISD::SETCC_MERGE_ZERO:
17775     return performSetccMergeZeroCombine(N, DAG);
17776   case AArch64ISD::GLD1_MERGE_ZERO:
17777   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
17778   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
17779   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
17780   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
17781   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
17782   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
17783   case AArch64ISD::GLD1S_MERGE_ZERO:
17784   case AArch64ISD::GLD1S_SCALED_MERGE_ZERO:
17785   case AArch64ISD::GLD1S_UXTW_MERGE_ZERO:
17786   case AArch64ISD::GLD1S_SXTW_MERGE_ZERO:
17787   case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO:
17788   case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO:
17789   case AArch64ISD::GLD1S_IMM_MERGE_ZERO:
17790     return performGLD1Combine(N, DAG);
17791   case AArch64ISD::VASHR:
17792   case AArch64ISD::VLSHR:
17793     return performVectorShiftCombine(N, *this, DCI);
17794   case AArch64ISD::SUNPKLO:
17795     return performSunpkloCombine(N, DAG);
17796   case ISD::INSERT_VECTOR_ELT:
17797     return performInsertVectorEltCombine(N, DCI);
17798   case ISD::EXTRACT_VECTOR_ELT:
17799     return performExtractVectorEltCombine(N, DAG);
17800   case ISD::VECREDUCE_ADD:
17801     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
17802   case ISD::INTRINSIC_VOID:
17803   case ISD::INTRINSIC_W_CHAIN:
17804     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
17805     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
17806       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
17807     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
17808       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
17809     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
17810       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
17811     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
17812       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
17813     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
17814     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
17815     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
17816     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
17817     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
17818     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
17819     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
17820     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
17821       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
17822     case Intrinsic::aarch64_neon_ld2:
17823     case Intrinsic::aarch64_neon_ld3:
17824     case Intrinsic::aarch64_neon_ld4:
17825     case Intrinsic::aarch64_neon_ld1x2:
17826     case Intrinsic::aarch64_neon_ld1x3:
17827     case Intrinsic::aarch64_neon_ld1x4:
17828     case Intrinsic::aarch64_neon_ld2lane:
17829     case Intrinsic::aarch64_neon_ld3lane:
17830     case Intrinsic::aarch64_neon_ld4lane:
17831     case Intrinsic::aarch64_neon_ld2r:
17832     case Intrinsic::aarch64_neon_ld3r:
17833     case Intrinsic::aarch64_neon_ld4r:
17834     case Intrinsic::aarch64_neon_st2:
17835     case Intrinsic::aarch64_neon_st3:
17836     case Intrinsic::aarch64_neon_st4:
17837     case Intrinsic::aarch64_neon_st1x2:
17838     case Intrinsic::aarch64_neon_st1x3:
17839     case Intrinsic::aarch64_neon_st1x4:
17840     case Intrinsic::aarch64_neon_st2lane:
17841     case Intrinsic::aarch64_neon_st3lane:
17842     case Intrinsic::aarch64_neon_st4lane:
17843       return performNEONPostLDSTCombine(N, DCI, DAG);
17844     case Intrinsic::aarch64_sve_ldnt1:
17845       return performLDNT1Combine(N, DAG);
17846     case Intrinsic::aarch64_sve_ld1rq:
17847       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
17848     case Intrinsic::aarch64_sve_ld1ro:
17849       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
17850     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
17851       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17852     case Intrinsic::aarch64_sve_ldnt1_gather:
17853       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17854     case Intrinsic::aarch64_sve_ldnt1_gather_index:
17855       return performGatherLoadCombine(N, DAG,
17856                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
17857     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
17858       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17859     case Intrinsic::aarch64_sve_ld1:
17860       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
17861     case Intrinsic::aarch64_sve_ldnf1:
17862       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
17863     case Intrinsic::aarch64_sve_ldff1:
17864       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
17865     case Intrinsic::aarch64_sve_st1:
17866       return performST1Combine(N, DAG);
17867     case Intrinsic::aarch64_sve_stnt1:
17868       return performSTNT1Combine(N, DAG);
17869     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
17870       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17871     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
17872       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17873     case Intrinsic::aarch64_sve_stnt1_scatter:
17874       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17875     case Intrinsic::aarch64_sve_stnt1_scatter_index:
17876       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
17877     case Intrinsic::aarch64_sve_ld1_gather:
17878       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
17879     case Intrinsic::aarch64_sve_ld1_gather_index:
17880       return performGatherLoadCombine(N, DAG,
17881                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
17882     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
17883       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
17884                                       /*OnlyPackedOffsets=*/false);
17885     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
17886       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
17887                                       /*OnlyPackedOffsets=*/false);
17888     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
17889       return performGatherLoadCombine(N, DAG,
17890                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
17891                                       /*OnlyPackedOffsets=*/false);
17892     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
17893       return performGatherLoadCombine(N, DAG,
17894                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
17895                                       /*OnlyPackedOffsets=*/false);
17896     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
17897       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
17898     case Intrinsic::aarch64_sve_ldff1_gather:
17899       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
17900     case Intrinsic::aarch64_sve_ldff1_gather_index:
17901       return performGatherLoadCombine(N, DAG,
17902                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
17903     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
17904       return performGatherLoadCombine(N, DAG,
17905                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
17906                                       /*OnlyPackedOffsets=*/false);
17907     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
17908       return performGatherLoadCombine(N, DAG,
17909                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
17910                                       /*OnlyPackedOffsets=*/false);
17911     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
17912       return performGatherLoadCombine(N, DAG,
17913                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
17914                                       /*OnlyPackedOffsets=*/false);
17915     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
17916       return performGatherLoadCombine(N, DAG,
17917                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
17918                                       /*OnlyPackedOffsets=*/false);
17919     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
17920       return performGatherLoadCombine(N, DAG,
17921                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
17922     case Intrinsic::aarch64_sve_st1_scatter:
17923       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
17924     case Intrinsic::aarch64_sve_st1_scatter_index:
17925       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
17926     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
17927       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
17928                                         /*OnlyPackedOffsets=*/false);
17929     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
17930       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
17931                                         /*OnlyPackedOffsets=*/false);
17932     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
17933       return performScatterStoreCombine(N, DAG,
17934                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
17935                                         /*OnlyPackedOffsets=*/false);
17936     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
17937       return performScatterStoreCombine(N, DAG,
17938                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
17939                                         /*OnlyPackedOffsets=*/false);
17940     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
17941       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
17942     case Intrinsic::aarch64_sve_tuple_get: {
17943       SDLoc DL(N);
17944       SDValue Chain = N->getOperand(0);
17945       SDValue Src1 = N->getOperand(2);
17946       SDValue Idx = N->getOperand(3);
17947 
17948       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
17949       EVT ResVT = N->getValueType(0);
17950       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
17951       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
17952       SDValue Val =
17953           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
17954       return DAG.getMergeValues({Val, Chain}, DL);
17955     }
17956     case Intrinsic::aarch64_sve_tuple_set: {
17957       SDLoc DL(N);
17958       SDValue Chain = N->getOperand(0);
17959       SDValue Tuple = N->getOperand(2);
17960       SDValue Idx = N->getOperand(3);
17961       SDValue Vec = N->getOperand(4);
17962 
17963       EVT TupleVT = Tuple.getValueType();
17964       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
17965 
17966       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
17967       uint64_t NumLanes =
17968           Vec.getValueType().getVectorElementCount().getKnownMinValue();
17969 
17970       if ((TupleLanes % NumLanes) != 0)
17971         report_fatal_error("invalid tuple vector!");
17972 
17973       uint64_t NumVecs = TupleLanes / NumLanes;
17974 
17975       SmallVector<SDValue, 4> Opnds;
17976       for (unsigned I = 0; I < NumVecs; ++I) {
17977         if (I == IdxConst)
17978           Opnds.push_back(Vec);
17979         else {
17980           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
17981           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
17982                                       Vec.getValueType(), Tuple, ExtIdx));
17983         }
17984       }
17985       SDValue Concat =
17986           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
17987       return DAG.getMergeValues({Concat, Chain}, DL);
17988     }
17989     case Intrinsic::aarch64_sve_tuple_create2:
17990     case Intrinsic::aarch64_sve_tuple_create3:
17991     case Intrinsic::aarch64_sve_tuple_create4: {
17992       SDLoc DL(N);
17993       SDValue Chain = N->getOperand(0);
17994 
17995       SmallVector<SDValue, 4> Opnds;
17996       for (unsigned I = 2; I < N->getNumOperands(); ++I)
17997         Opnds.push_back(N->getOperand(I));
17998 
17999       EVT VT = Opnds[0].getValueType();
18000       EVT EltVT = VT.getVectorElementType();
18001       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
18002                                     VT.getVectorElementCount() *
18003                                         (N->getNumOperands() - 2));
18004       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
18005       return DAG.getMergeValues({Concat, Chain}, DL);
18006     }
18007     case Intrinsic::aarch64_sve_ld2:
18008     case Intrinsic::aarch64_sve_ld3:
18009     case Intrinsic::aarch64_sve_ld4: {
18010       SDLoc DL(N);
18011       SDValue Chain = N->getOperand(0);
18012       SDValue Mask = N->getOperand(2);
18013       SDValue BasePtr = N->getOperand(3);
18014       SDValue LoadOps[] = {Chain, Mask, BasePtr};
18015       unsigned IntrinsicID =
18016           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18017       SDValue Result =
18018           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
18019       return DAG.getMergeValues({Result, Chain}, DL);
18020     }
18021     case Intrinsic::aarch64_rndr:
18022     case Intrinsic::aarch64_rndrrs: {
18023       unsigned IntrinsicID =
18024           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18025       auto Register =
18026           (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR
18027                                                   : AArch64SysReg::RNDRRS);
18028       SDLoc DL(N);
18029       SDValue A = DAG.getNode(
18030           AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other),
18031           N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64));
18032       SDValue B = DAG.getNode(
18033           AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32),
18034           DAG.getConstant(0, DL, MVT::i32),
18035           DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1));
18036       return DAG.getMergeValues(
18037           {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL);
18038     }
18039     default:
18040       break;
18041     }
18042     break;
18043   case ISD::GlobalAddress:
18044     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
18045   }
18046   return SDValue();
18047 }
18048 
18049 // Check if the return value is used as only a return value, as otherwise
18050 // we can't perform a tail-call. In particular, we need to check for
18051 // target ISD nodes that are returns and any other "odd" constructs
18052 // that the generic analysis code won't necessarily catch.
18053 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
18054                                                SDValue &Chain) const {
18055   if (N->getNumValues() != 1)
18056     return false;
18057   if (!N->hasNUsesOfValue(1, 0))
18058     return false;
18059 
18060   SDValue TCChain = Chain;
18061   SDNode *Copy = *N->use_begin();
18062   if (Copy->getOpcode() == ISD::CopyToReg) {
18063     // If the copy has a glue operand, we conservatively assume it isn't safe to
18064     // perform a tail call.
18065     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
18066         MVT::Glue)
18067       return false;
18068     TCChain = Copy->getOperand(0);
18069   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
18070     return false;
18071 
18072   bool HasRet = false;
18073   for (SDNode *Node : Copy->uses()) {
18074     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
18075       return false;
18076     HasRet = true;
18077   }
18078 
18079   if (!HasRet)
18080     return false;
18081 
18082   Chain = TCChain;
18083   return true;
18084 }
18085 
18086 // Return whether the an instruction can potentially be optimized to a tail
18087 // call. This will cause the optimizers to attempt to move, or duplicate,
18088 // return instructions to help enable tail call optimizations for this
18089 // instruction.
18090 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
18091   return CI->isTailCall();
18092 }
18093 
18094 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
18095                                                    SDValue &Offset,
18096                                                    ISD::MemIndexedMode &AM,
18097                                                    bool &IsInc,
18098                                                    SelectionDAG &DAG) const {
18099   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
18100     return false;
18101 
18102   Base = Op->getOperand(0);
18103   // All of the indexed addressing mode instructions take a signed
18104   // 9 bit immediate offset.
18105   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
18106     int64_t RHSC = RHS->getSExtValue();
18107     if (Op->getOpcode() == ISD::SUB)
18108       RHSC = -(uint64_t)RHSC;
18109     if (!isInt<9>(RHSC))
18110       return false;
18111     IsInc = (Op->getOpcode() == ISD::ADD);
18112     Offset = Op->getOperand(1);
18113     return true;
18114   }
18115   return false;
18116 }
18117 
18118 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
18119                                                       SDValue &Offset,
18120                                                       ISD::MemIndexedMode &AM,
18121                                                       SelectionDAG &DAG) const {
18122   EVT VT;
18123   SDValue Ptr;
18124   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
18125     VT = LD->getMemoryVT();
18126     Ptr = LD->getBasePtr();
18127   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
18128     VT = ST->getMemoryVT();
18129     Ptr = ST->getBasePtr();
18130   } else
18131     return false;
18132 
18133   bool IsInc;
18134   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
18135     return false;
18136   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
18137   return true;
18138 }
18139 
18140 bool AArch64TargetLowering::getPostIndexedAddressParts(
18141     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
18142     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
18143   EVT VT;
18144   SDValue Ptr;
18145   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
18146     VT = LD->getMemoryVT();
18147     Ptr = LD->getBasePtr();
18148   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
18149     VT = ST->getMemoryVT();
18150     Ptr = ST->getBasePtr();
18151   } else
18152     return false;
18153 
18154   bool IsInc;
18155   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
18156     return false;
18157   // Post-indexing updates the base, so it's not a valid transform
18158   // if that's not the same as the load's pointer.
18159   if (Ptr != Base)
18160     return false;
18161   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
18162   return true;
18163 }
18164 
18165 void AArch64TargetLowering::ReplaceBITCASTResults(
18166     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
18167   SDLoc DL(N);
18168   SDValue Op = N->getOperand(0);
18169   EVT VT = N->getValueType(0);
18170   EVT SrcVT = Op.getValueType();
18171 
18172   if (VT.isScalableVector() && !isTypeLegal(VT) && isTypeLegal(SrcVT)) {
18173     assert(!VT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
18174            "Expected fp->int bitcast!");
18175     SDValue CastResult = getSVESafeBitCast(getSVEContainerType(VT), Op, DAG);
18176     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, CastResult));
18177     return;
18178   }
18179 
18180   if (VT != MVT::i16 || (SrcVT != MVT::f16 && SrcVT != MVT::bf16))
18181     return;
18182 
18183   Op = SDValue(
18184       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
18185                          DAG.getUNDEF(MVT::i32), Op,
18186                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
18187       0);
18188   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
18189   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
18190 }
18191 
18192 static void ReplaceReductionResults(SDNode *N,
18193                                     SmallVectorImpl<SDValue> &Results,
18194                                     SelectionDAG &DAG, unsigned InterOp,
18195                                     unsigned AcrossOp) {
18196   EVT LoVT, HiVT;
18197   SDValue Lo, Hi;
18198   SDLoc dl(N);
18199   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
18200   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
18201   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
18202   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
18203   Results.push_back(SplitVal);
18204 }
18205 
18206 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
18207   SDLoc DL(N);
18208   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
18209   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
18210                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
18211                                        DAG.getConstant(64, DL, MVT::i64)));
18212   return std::make_pair(Lo, Hi);
18213 }
18214 
18215 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
18216     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
18217   SDValue In = N->getOperand(0);
18218   EVT InVT = In.getValueType();
18219 
18220   // Common code will handle these just fine.
18221   if (!InVT.isScalableVector() || !InVT.isInteger())
18222     return;
18223 
18224   SDLoc DL(N);
18225   EVT VT = N->getValueType(0);
18226 
18227   // The following checks bail if this is not a halving operation.
18228 
18229   ElementCount ResEC = VT.getVectorElementCount();
18230 
18231   if (InVT.getVectorElementCount() != (ResEC * 2))
18232     return;
18233 
18234   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
18235   if (!CIndex)
18236     return;
18237 
18238   unsigned Index = CIndex->getZExtValue();
18239   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
18240     return;
18241 
18242   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
18243   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
18244 
18245   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
18246   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
18247 }
18248 
18249 // Create an even/odd pair of X registers holding integer value V.
18250 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
18251   SDLoc dl(V.getNode());
18252   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
18253   SDValue VHi = DAG.getAnyExtOrTrunc(
18254       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
18255       dl, MVT::i64);
18256   if (DAG.getDataLayout().isBigEndian())
18257     std::swap (VLo, VHi);
18258   SDValue RegClass =
18259       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
18260   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
18261   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
18262   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
18263   return SDValue(
18264       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
18265 }
18266 
18267 static void ReplaceCMP_SWAP_128Results(SDNode *N,
18268                                        SmallVectorImpl<SDValue> &Results,
18269                                        SelectionDAG &DAG,
18270                                        const AArch64Subtarget *Subtarget) {
18271   assert(N->getValueType(0) == MVT::i128 &&
18272          "AtomicCmpSwap on types less than 128 should be legal");
18273 
18274   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
18275   if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
18276     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
18277     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
18278     SDValue Ops[] = {
18279         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
18280         createGPRPairNode(DAG, N->getOperand(3)), // Store value
18281         N->getOperand(1), // Ptr
18282         N->getOperand(0), // Chain in
18283     };
18284 
18285     unsigned Opcode;
18286     switch (MemOp->getMergedOrdering()) {
18287     case AtomicOrdering::Monotonic:
18288       Opcode = AArch64::CASPX;
18289       break;
18290     case AtomicOrdering::Acquire:
18291       Opcode = AArch64::CASPAX;
18292       break;
18293     case AtomicOrdering::Release:
18294       Opcode = AArch64::CASPLX;
18295       break;
18296     case AtomicOrdering::AcquireRelease:
18297     case AtomicOrdering::SequentiallyConsistent:
18298       Opcode = AArch64::CASPALX;
18299       break;
18300     default:
18301       llvm_unreachable("Unexpected ordering!");
18302     }
18303 
18304     MachineSDNode *CmpSwap = DAG.getMachineNode(
18305         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
18306     DAG.setNodeMemRefs(CmpSwap, {MemOp});
18307 
18308     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
18309     if (DAG.getDataLayout().isBigEndian())
18310       std::swap(SubReg1, SubReg2);
18311     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
18312                                             SDValue(CmpSwap, 0));
18313     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
18314                                             SDValue(CmpSwap, 0));
18315     Results.push_back(
18316         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
18317     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
18318     return;
18319   }
18320 
18321   unsigned Opcode;
18322   switch (MemOp->getMergedOrdering()) {
18323   case AtomicOrdering::Monotonic:
18324     Opcode = AArch64::CMP_SWAP_128_MONOTONIC;
18325     break;
18326   case AtomicOrdering::Acquire:
18327     Opcode = AArch64::CMP_SWAP_128_ACQUIRE;
18328     break;
18329   case AtomicOrdering::Release:
18330     Opcode = AArch64::CMP_SWAP_128_RELEASE;
18331     break;
18332   case AtomicOrdering::AcquireRelease:
18333   case AtomicOrdering::SequentiallyConsistent:
18334     Opcode = AArch64::CMP_SWAP_128;
18335     break;
18336   default:
18337     llvm_unreachable("Unexpected ordering!");
18338   }
18339 
18340   auto Desired = splitInt128(N->getOperand(2), DAG);
18341   auto New = splitInt128(N->getOperand(3), DAG);
18342   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
18343                    New.first,        New.second,    N->getOperand(0)};
18344   SDNode *CmpSwap = DAG.getMachineNode(
18345       Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other),
18346       Ops);
18347   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
18348 
18349   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
18350                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
18351   Results.push_back(SDValue(CmpSwap, 3));
18352 }
18353 
18354 void AArch64TargetLowering::ReplaceNodeResults(
18355     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
18356   switch (N->getOpcode()) {
18357   default:
18358     llvm_unreachable("Don't know how to custom expand this");
18359   case ISD::BITCAST:
18360     ReplaceBITCASTResults(N, Results, DAG);
18361     return;
18362   case ISD::VECREDUCE_ADD:
18363   case ISD::VECREDUCE_SMAX:
18364   case ISD::VECREDUCE_SMIN:
18365   case ISD::VECREDUCE_UMAX:
18366   case ISD::VECREDUCE_UMIN:
18367     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
18368     return;
18369 
18370   case ISD::CTPOP:
18371     if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG))
18372       Results.push_back(Result);
18373     return;
18374   case AArch64ISD::SADDV:
18375     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
18376     return;
18377   case AArch64ISD::UADDV:
18378     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
18379     return;
18380   case AArch64ISD::SMINV:
18381     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
18382     return;
18383   case AArch64ISD::UMINV:
18384     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
18385     return;
18386   case AArch64ISD::SMAXV:
18387     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
18388     return;
18389   case AArch64ISD::UMAXV:
18390     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
18391     return;
18392   case ISD::FP_TO_UINT:
18393   case ISD::FP_TO_SINT:
18394   case ISD::STRICT_FP_TO_SINT:
18395   case ISD::STRICT_FP_TO_UINT:
18396     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
18397     // Let normal code take care of it by not adding anything to Results.
18398     return;
18399   case ISD::ATOMIC_CMP_SWAP:
18400     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
18401     return;
18402   case ISD::ATOMIC_LOAD:
18403   case ISD::LOAD: {
18404     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
18405            "unexpected load's value type");
18406     MemSDNode *LoadNode = cast<MemSDNode>(N);
18407     if ((!LoadNode->isVolatile() && !LoadNode->isAtomic()) ||
18408         LoadNode->getMemoryVT() != MVT::i128) {
18409       // Non-volatile or atomic loads are optimized later in AArch64's load/store
18410       // optimizer.
18411       return;
18412     }
18413 
18414     SDValue Result = DAG.getMemIntrinsicNode(
18415         AArch64ISD::LDP, SDLoc(N),
18416         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
18417         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
18418         LoadNode->getMemOperand());
18419 
18420     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
18421                                Result.getValue(0), Result.getValue(1));
18422     Results.append({Pair, Result.getValue(2) /* Chain */});
18423     return;
18424   }
18425   case ISD::EXTRACT_SUBVECTOR:
18426     ReplaceExtractSubVectorResults(N, Results, DAG);
18427     return;
18428   case ISD::INSERT_SUBVECTOR:
18429     // Custom lowering has been requested for INSERT_SUBVECTOR -- but delegate
18430     // to common code for result type legalisation
18431     return;
18432   case ISD::INTRINSIC_WO_CHAIN: {
18433     EVT VT = N->getValueType(0);
18434     assert((VT == MVT::i8 || VT == MVT::i16) &&
18435            "custom lowering for unexpected type");
18436 
18437     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
18438     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
18439     switch (IntID) {
18440     default:
18441       return;
18442     case Intrinsic::aarch64_sve_clasta_n: {
18443       SDLoc DL(N);
18444       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
18445       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
18446                            N->getOperand(1), Op2, N->getOperand(3));
18447       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
18448       return;
18449     }
18450     case Intrinsic::aarch64_sve_clastb_n: {
18451       SDLoc DL(N);
18452       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
18453       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
18454                            N->getOperand(1), Op2, N->getOperand(3));
18455       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
18456       return;
18457     }
18458     case Intrinsic::aarch64_sve_lasta: {
18459       SDLoc DL(N);
18460       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
18461                            N->getOperand(1), N->getOperand(2));
18462       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
18463       return;
18464     }
18465     case Intrinsic::aarch64_sve_lastb: {
18466       SDLoc DL(N);
18467       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
18468                            N->getOperand(1), N->getOperand(2));
18469       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
18470       return;
18471     }
18472     }
18473   }
18474   }
18475 }
18476 
18477 bool AArch64TargetLowering::useLoadStackGuardNode() const {
18478   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
18479     return TargetLowering::useLoadStackGuardNode();
18480   return true;
18481 }
18482 
18483 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
18484   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
18485   // reciprocal if there are three or more FDIVs.
18486   return 3;
18487 }
18488 
18489 TargetLoweringBase::LegalizeTypeAction
18490 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
18491   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
18492   // v4i16, v2i32 instead of to promote.
18493   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
18494       VT == MVT::v1f32)
18495     return TypeWidenVector;
18496 
18497   return TargetLoweringBase::getPreferredVectorAction(VT);
18498 }
18499 
18500 // In v8.4a, ldp and stp instructions are guaranteed to be single-copy atomic
18501 // provided the address is 16-byte aligned.
18502 bool AArch64TargetLowering::isOpSuitableForLDPSTP(const Instruction *I) const {
18503   if (!Subtarget->hasLSE2())
18504     return false;
18505 
18506   if (auto LI = dyn_cast<LoadInst>(I))
18507     return LI->getType()->getPrimitiveSizeInBits() == 128 &&
18508            LI->getAlignment() >= 16;
18509 
18510   if (auto SI = dyn_cast<StoreInst>(I))
18511     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
18512            SI->getAlignment() >= 16;
18513 
18514   return false;
18515 }
18516 
18517 bool AArch64TargetLowering::shouldInsertFencesForAtomic(
18518     const Instruction *I) const {
18519   return isOpSuitableForLDPSTP(I);
18520 }
18521 
18522 // Loads and stores less than 128-bits are already atomic; ones above that
18523 // are doomed anyway, so defer to the default libcall and blame the OS when
18524 // things go wrong.
18525 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18526   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
18527   if (Size != 128)
18528     return false;
18529 
18530   return !isOpSuitableForLDPSTP(SI);
18531 }
18532 
18533 // Loads and stores less than 128-bits are already atomic; ones above that
18534 // are doomed anyway, so defer to the default libcall and blame the OS when
18535 // things go wrong.
18536 TargetLowering::AtomicExpansionKind
18537 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18538   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
18539 
18540   if (Size != 128 || isOpSuitableForLDPSTP(LI))
18541     return AtomicExpansionKind::None;
18542 
18543   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18544   // implement atomicrmw without spilling. If the target address is also on the
18545   // stack and close enough to the spill slot, this can lead to a situation
18546   // where the monitor always gets cleared and the atomic operation can never
18547   // succeed. So at -O0 lower this operation to a CAS loop.
18548   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
18549     return AtomicExpansionKind::CmpXChg;
18550 
18551   return AtomicExpansionKind::LLSC;
18552 }
18553 
18554 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
18555 TargetLowering::AtomicExpansionKind
18556 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18557   if (AI->isFloatingPointOperation())
18558     return AtomicExpansionKind::CmpXChg;
18559 
18560   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18561   if (Size > 128) return AtomicExpansionKind::None;
18562 
18563   // Nand is not supported in LSE.
18564   // Leave 128 bits to LLSC or CmpXChg.
18565   if (AI->getOperation() != AtomicRMWInst::Nand && Size < 128) {
18566     if (Subtarget->hasLSE())
18567       return AtomicExpansionKind::None;
18568     if (Subtarget->outlineAtomics()) {
18569       // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
18570       // Don't outline them unless
18571       // (1) high level <atomic> support approved:
18572       //   http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
18573       // (2) low level libgcc and compiler-rt support implemented by:
18574       //   min/max outline atomics helpers
18575       if (AI->getOperation() != AtomicRMWInst::Min &&
18576           AI->getOperation() != AtomicRMWInst::Max &&
18577           AI->getOperation() != AtomicRMWInst::UMin &&
18578           AI->getOperation() != AtomicRMWInst::UMax) {
18579         return AtomicExpansionKind::None;
18580       }
18581     }
18582   }
18583 
18584   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18585   // implement atomicrmw without spilling. If the target address is also on the
18586   // stack and close enough to the spill slot, this can lead to a situation
18587   // where the monitor always gets cleared and the atomic operation can never
18588   // succeed. So at -O0 lower this operation to a CAS loop.
18589   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
18590     return AtomicExpansionKind::CmpXChg;
18591 
18592   return AtomicExpansionKind::LLSC;
18593 }
18594 
18595 TargetLowering::AtomicExpansionKind
18596 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
18597     AtomicCmpXchgInst *AI) const {
18598   // If subtarget has LSE, leave cmpxchg intact for codegen.
18599   if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
18600     return AtomicExpansionKind::None;
18601   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18602   // implement cmpxchg without spilling. If the address being exchanged is also
18603   // on the stack and close enough to the spill slot, this can lead to a
18604   // situation where the monitor always gets cleared and the atomic operation
18605   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
18606   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
18607     return AtomicExpansionKind::None;
18608 
18609   // 128-bit atomic cmpxchg is weird; AtomicExpand doesn't know how to expand
18610   // it.
18611   unsigned Size = AI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
18612   if (Size > 64)
18613     return AtomicExpansionKind::None;
18614 
18615   return AtomicExpansionKind::LLSC;
18616 }
18617 
18618 Value *AArch64TargetLowering::emitLoadLinked(IRBuilderBase &Builder,
18619                                              Type *ValueTy, Value *Addr,
18620                                              AtomicOrdering Ord) const {
18621   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18622   bool IsAcquire = isAcquireOrStronger(Ord);
18623 
18624   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
18625   // intrinsic must return {i64, i64} and we have to recombine them into a
18626   // single i128 here.
18627   if (ValueTy->getPrimitiveSizeInBits() == 128) {
18628     Intrinsic::ID Int =
18629         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
18630     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
18631 
18632     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18633     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
18634 
18635     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18636     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18637     Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
18638     Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
18639     return Builder.CreateOr(
18640         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 64)), "val64");
18641   }
18642 
18643   Type *Tys[] = { Addr->getType() };
18644   Intrinsic::ID Int =
18645       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
18646   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
18647 
18648   const DataLayout &DL = M->getDataLayout();
18649   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(ValueTy));
18650   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
18651 
18652   return Builder.CreateBitCast(Trunc, ValueTy);
18653 }
18654 
18655 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
18656     IRBuilderBase &Builder) const {
18657   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18658   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
18659 }
18660 
18661 Value *AArch64TargetLowering::emitStoreConditional(IRBuilderBase &Builder,
18662                                                    Value *Val, Value *Addr,
18663                                                    AtomicOrdering Ord) const {
18664   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18665   bool IsRelease = isReleaseOrStronger(Ord);
18666 
18667   // Since the intrinsics must have legal type, the i128 intrinsics take two
18668   // parameters: "i64, i64". We must marshal Val into the appropriate form
18669   // before the call.
18670   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
18671     Intrinsic::ID Int =
18672         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
18673     Function *Stxr = Intrinsic::getDeclaration(M, Int);
18674     Type *Int64Ty = Type::getInt64Ty(M->getContext());
18675 
18676     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
18677     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
18678     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18679     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
18680   }
18681 
18682   Intrinsic::ID Int =
18683       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
18684   Type *Tys[] = { Addr->getType() };
18685   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
18686 
18687   const DataLayout &DL = M->getDataLayout();
18688   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
18689   Val = Builder.CreateBitCast(Val, IntValTy);
18690 
18691   return Builder.CreateCall(Stxr,
18692                             {Builder.CreateZExtOrBitCast(
18693                                  Val, Stxr->getFunctionType()->getParamType(0)),
18694                              Addr});
18695 }
18696 
18697 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
18698     Type *Ty, CallingConv::ID CallConv, bool isVarArg,
18699     const DataLayout &DL) const {
18700   if (!Ty->isArrayTy()) {
18701     const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
18702     return TySize.isScalable() && TySize.getKnownMinSize() > 128;
18703   }
18704 
18705   // All non aggregate members of the type must have the same type
18706   SmallVector<EVT> ValueVTs;
18707   ComputeValueVTs(*this, DL, Ty, ValueVTs);
18708   return is_splat(ValueVTs);
18709 }
18710 
18711 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
18712                                                             EVT) const {
18713   return false;
18714 }
18715 
18716 static Value *UseTlsOffset(IRBuilderBase &IRB, unsigned Offset) {
18717   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
18718   Function *ThreadPointerFunc =
18719       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
18720   return IRB.CreatePointerCast(
18721       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
18722                              Offset),
18723       IRB.getInt8PtrTy()->getPointerTo(0));
18724 }
18725 
18726 Value *AArch64TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
18727   // Android provides a fixed TLS slot for the stack cookie. See the definition
18728   // of TLS_SLOT_STACK_GUARD in
18729   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
18730   if (Subtarget->isTargetAndroid())
18731     return UseTlsOffset(IRB, 0x28);
18732 
18733   // Fuchsia is similar.
18734   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
18735   if (Subtarget->isTargetFuchsia())
18736     return UseTlsOffset(IRB, -0x10);
18737 
18738   return TargetLowering::getIRStackGuard(IRB);
18739 }
18740 
18741 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
18742   // MSVC CRT provides functionalities for stack protection.
18743   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
18744     // MSVC CRT has a global variable holding security cookie.
18745     M.getOrInsertGlobal("__security_cookie",
18746                         Type::getInt8PtrTy(M.getContext()));
18747 
18748     // MSVC CRT has a function to validate security cookie.
18749     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
18750         "__security_check_cookie", Type::getVoidTy(M.getContext()),
18751         Type::getInt8PtrTy(M.getContext()));
18752     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
18753       F->setCallingConv(CallingConv::Win64);
18754       F->addParamAttr(0, Attribute::AttrKind::InReg);
18755     }
18756     return;
18757   }
18758   TargetLowering::insertSSPDeclarations(M);
18759 }
18760 
18761 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
18762   // MSVC CRT has a global variable holding security cookie.
18763   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18764     return M.getGlobalVariable("__security_cookie");
18765   return TargetLowering::getSDagStackGuard(M);
18766 }
18767 
18768 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
18769   // MSVC CRT has a function to validate security cookie.
18770   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18771     return M.getFunction("__security_check_cookie");
18772   return TargetLowering::getSSPStackGuardCheck(M);
18773 }
18774 
18775 Value *
18776 AArch64TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
18777   // Android provides a fixed TLS slot for the SafeStack pointer. See the
18778   // definition of TLS_SLOT_SAFESTACK in
18779   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
18780   if (Subtarget->isTargetAndroid())
18781     return UseTlsOffset(IRB, 0x48);
18782 
18783   // Fuchsia is similar.
18784   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
18785   if (Subtarget->isTargetFuchsia())
18786     return UseTlsOffset(IRB, -0x8);
18787 
18788   return TargetLowering::getSafeStackPointerLocation(IRB);
18789 }
18790 
18791 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
18792     const Instruction &AndI) const {
18793   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
18794   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
18795   // may be beneficial to sink in other cases, but we would have to check that
18796   // the cmp would not get folded into the br to form a cbz for these to be
18797   // beneficial.
18798   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
18799   if (!Mask)
18800     return false;
18801   return Mask->getValue().isPowerOf2();
18802 }
18803 
18804 bool AArch64TargetLowering::
18805     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
18806         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
18807         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
18808         SelectionDAG &DAG) const {
18809   // Does baseline recommend not to perform the fold by default?
18810   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
18811           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
18812     return false;
18813   // Else, if this is a vector shift, prefer 'shl'.
18814   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
18815 }
18816 
18817 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
18818                                               SDNode *N) const {
18819   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
18820       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
18821     return false;
18822   return true;
18823 }
18824 
18825 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
18826   // Update IsSplitCSR in AArch64unctionInfo.
18827   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
18828   AFI->setIsSplitCSR(true);
18829 }
18830 
18831 void AArch64TargetLowering::insertCopiesSplitCSR(
18832     MachineBasicBlock *Entry,
18833     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
18834   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
18835   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
18836   if (!IStart)
18837     return;
18838 
18839   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18840   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
18841   MachineBasicBlock::iterator MBBI = Entry->begin();
18842   for (const MCPhysReg *I = IStart; *I; ++I) {
18843     const TargetRegisterClass *RC = nullptr;
18844     if (AArch64::GPR64RegClass.contains(*I))
18845       RC = &AArch64::GPR64RegClass;
18846     else if (AArch64::FPR64RegClass.contains(*I))
18847       RC = &AArch64::FPR64RegClass;
18848     else
18849       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
18850 
18851     Register NewVR = MRI->createVirtualRegister(RC);
18852     // Create copy from CSR to a virtual register.
18853     // FIXME: this currently does not emit CFI pseudo-instructions, it works
18854     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
18855     // nounwind. If we want to generalize this later, we may need to emit
18856     // CFI pseudo-instructions.
18857     assert(Entry->getParent()->getFunction().hasFnAttribute(
18858                Attribute::NoUnwind) &&
18859            "Function should be nounwind in insertCopiesSplitCSR!");
18860     Entry->addLiveIn(*I);
18861     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
18862         .addReg(*I);
18863 
18864     // Insert the copy-back instructions right before the terminator.
18865     for (auto *Exit : Exits)
18866       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
18867               TII->get(TargetOpcode::COPY), *I)
18868           .addReg(NewVR);
18869   }
18870 }
18871 
18872 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
18873   // Integer division on AArch64 is expensive. However, when aggressively
18874   // optimizing for code size, we prefer to use a div instruction, as it is
18875   // usually smaller than the alternative sequence.
18876   // The exception to this is vector division. Since AArch64 doesn't have vector
18877   // integer division, leaving the division as-is is a loss even in terms of
18878   // size, because it will have to be scalarized, while the alternative code
18879   // sequence can be performed in vector form.
18880   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
18881   return OptSize && !VT.isVector();
18882 }
18883 
18884 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
18885   // We want inc-of-add for scalars and sub-of-not for vectors.
18886   return VT.isScalarInteger();
18887 }
18888 
18889 bool AArch64TargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
18890                                                  EVT VT) const {
18891   // v8f16 without fp16 need to be extended to v8f32, which is more difficult to
18892   // legalize.
18893   if (FPVT == MVT::v8f16 && !Subtarget->hasFullFP16())
18894     return false;
18895   return TargetLowering::shouldConvertFpToSat(Op, FPVT, VT);
18896 }
18897 
18898 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
18899   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
18900 }
18901 
18902 unsigned
18903 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
18904   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
18905     return getPointerTy(DL).getSizeInBits();
18906 
18907   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
18908 }
18909 
18910 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
18911   MachineFrameInfo &MFI = MF.getFrameInfo();
18912   // If we have any vulnerable SVE stack objects then the stack protector
18913   // needs to be placed at the top of the SVE stack area, as the SVE locals
18914   // are placed above the other locals, so we allocate it as if it were a
18915   // scalable vector.
18916   // FIXME: It may be worthwhile having a specific interface for this rather
18917   // than doing it here in finalizeLowering.
18918   if (MFI.hasStackProtectorIndex()) {
18919     for (unsigned int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
18920       if (MFI.getStackID(i) == TargetStackID::ScalableVector &&
18921           MFI.getObjectSSPLayout(i) != MachineFrameInfo::SSPLK_None) {
18922         MFI.setStackID(MFI.getStackProtectorIndex(),
18923                        TargetStackID::ScalableVector);
18924         MFI.setObjectAlignment(MFI.getStackProtectorIndex(), Align(16));
18925         break;
18926       }
18927     }
18928   }
18929   MFI.computeMaxCallFrameSize(MF);
18930   TargetLoweringBase::finalizeLowering(MF);
18931 }
18932 
18933 // Unlike X86, we let frame lowering assign offsets to all catch objects.
18934 bool AArch64TargetLowering::needsFixedCatchObjects() const {
18935   return false;
18936 }
18937 
18938 bool AArch64TargetLowering::shouldLocalize(
18939     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
18940   switch (MI.getOpcode()) {
18941   case TargetOpcode::G_GLOBAL_VALUE: {
18942     // On Darwin, TLS global vars get selected into function calls, which
18943     // we don't want localized, as they can get moved into the middle of a
18944     // another call sequence.
18945     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
18946     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
18947       return false;
18948     break;
18949   }
18950   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
18951   // localizable.
18952   case AArch64::ADRP:
18953   case AArch64::G_ADD_LOW:
18954     return true;
18955   default:
18956     break;
18957   }
18958   return TargetLoweringBase::shouldLocalize(MI, TTI);
18959 }
18960 
18961 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
18962   if (isa<ScalableVectorType>(Inst.getType()))
18963     return true;
18964 
18965   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
18966     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
18967       return true;
18968 
18969   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
18970     if (isa<ScalableVectorType>(AI->getAllocatedType()))
18971       return true;
18972   }
18973 
18974   return false;
18975 }
18976 
18977 // Return the largest legal scalable vector type that matches VT's element type.
18978 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
18979   assert(VT.isFixedLengthVector() &&
18980          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18981          "Expected legal fixed length vector!");
18982   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
18983   default:
18984     llvm_unreachable("unexpected element type for SVE container");
18985   case MVT::i8:
18986     return EVT(MVT::nxv16i8);
18987   case MVT::i16:
18988     return EVT(MVT::nxv8i16);
18989   case MVT::i32:
18990     return EVT(MVT::nxv4i32);
18991   case MVT::i64:
18992     return EVT(MVT::nxv2i64);
18993   case MVT::f16:
18994     return EVT(MVT::nxv8f16);
18995   case MVT::f32:
18996     return EVT(MVT::nxv4f32);
18997   case MVT::f64:
18998     return EVT(MVT::nxv2f64);
18999   }
19000 }
19001 
19002 // Return a PTRUE with active lanes corresponding to the extent of VT.
19003 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
19004                                                 EVT VT) {
19005   assert(VT.isFixedLengthVector() &&
19006          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
19007          "Expected legal fixed length vector!");
19008 
19009   Optional<unsigned> PgPattern =
19010       getSVEPredPatternFromNumElements(VT.getVectorNumElements());
19011   assert(PgPattern && "Unexpected element count for SVE predicate");
19012 
19013   // For vectors that are exactly getMaxSVEVectorSizeInBits big, we can use
19014   // AArch64SVEPredPattern::all, which can enable the use of unpredicated
19015   // variants of instructions when available.
19016   const auto &Subtarget =
19017       static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
19018   unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
19019   unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
19020   if (MaxSVESize && MinSVESize == MaxSVESize &&
19021       MaxSVESize == VT.getSizeInBits())
19022     PgPattern = AArch64SVEPredPattern::all;
19023 
19024   MVT MaskVT;
19025   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
19026   default:
19027     llvm_unreachable("unexpected element type for SVE predicate");
19028   case MVT::i8:
19029     MaskVT = MVT::nxv16i1;
19030     break;
19031   case MVT::i16:
19032   case MVT::f16:
19033     MaskVT = MVT::nxv8i1;
19034     break;
19035   case MVT::i32:
19036   case MVT::f32:
19037     MaskVT = MVT::nxv4i1;
19038     break;
19039   case MVT::i64:
19040   case MVT::f64:
19041     MaskVT = MVT::nxv2i1;
19042     break;
19043   }
19044 
19045   return getPTrue(DAG, DL, MaskVT, *PgPattern);
19046 }
19047 
19048 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
19049                                              EVT VT) {
19050   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
19051          "Expected legal scalable vector!");
19052   auto PredTy = VT.changeVectorElementType(MVT::i1);
19053   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
19054 }
19055 
19056 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
19057   if (VT.isFixedLengthVector())
19058     return getPredicateForFixedLengthVector(DAG, DL, VT);
19059 
19060   return getPredicateForScalableVector(DAG, DL, VT);
19061 }
19062 
19063 // Grow V to consume an entire SVE register.
19064 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
19065   assert(VT.isScalableVector() &&
19066          "Expected to convert into a scalable vector!");
19067   assert(V.getValueType().isFixedLengthVector() &&
19068          "Expected a fixed length vector operand!");
19069   SDLoc DL(V);
19070   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
19071   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
19072 }
19073 
19074 // Shrink V so it's just big enough to maintain a VT's worth of data.
19075 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
19076   assert(VT.isFixedLengthVector() &&
19077          "Expected to convert into a fixed length vector!");
19078   assert(V.getValueType().isScalableVector() &&
19079          "Expected a scalable vector operand!");
19080   SDLoc DL(V);
19081   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
19082   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
19083 }
19084 
19085 // Convert all fixed length vector loads larger than NEON to masked_loads.
19086 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
19087     SDValue Op, SelectionDAG &DAG) const {
19088   auto Load = cast<LoadSDNode>(Op);
19089 
19090   SDLoc DL(Op);
19091   EVT VT = Op.getValueType();
19092   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19093   EVT LoadVT = ContainerVT;
19094   EVT MemVT = Load->getMemoryVT();
19095 
19096   auto Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
19097 
19098   if (VT.isFloatingPoint() && Load->getExtensionType() == ISD::EXTLOAD) {
19099     LoadVT = ContainerVT.changeTypeToInteger();
19100     MemVT = MemVT.changeTypeToInteger();
19101   }
19102 
19103   auto NewLoad = DAG.getMaskedLoad(
19104       LoadVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(), Pg,
19105       DAG.getUNDEF(LoadVT), MemVT, Load->getMemOperand(),
19106       Load->getAddressingMode(), Load->getExtensionType());
19107 
19108   if (VT.isFloatingPoint() && Load->getExtensionType() == ISD::EXTLOAD) {
19109     EVT ExtendVT = ContainerVT.changeVectorElementType(
19110         Load->getMemoryVT().getVectorElementType());
19111 
19112     NewLoad = getSVESafeBitCast(ExtendVT, NewLoad, DAG);
19113     NewLoad = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
19114                           Pg, NewLoad, DAG.getUNDEF(ContainerVT));
19115   }
19116 
19117   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
19118   SDValue MergedValues[2] = {Result, Load->getChain()};
19119   return DAG.getMergeValues(MergedValues, DL);
19120 }
19121 
19122 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
19123                                                 SelectionDAG &DAG) {
19124   SDLoc DL(Mask);
19125   EVT InVT = Mask.getValueType();
19126   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
19127 
19128   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
19129 
19130   if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19131     return Pg;
19132 
19133   auto Op1 = convertToScalableVector(DAG, ContainerVT, Mask);
19134   auto Op2 = DAG.getConstant(0, DL, ContainerVT);
19135 
19136   return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, Pg.getValueType(),
19137                      {Pg, Op1, Op2, DAG.getCondCode(ISD::SETNE)});
19138 }
19139 
19140 // Convert all fixed length vector loads larger than NEON to masked_loads.
19141 SDValue AArch64TargetLowering::LowerFixedLengthVectorMLoadToSVE(
19142     SDValue Op, SelectionDAG &DAG) const {
19143   auto Load = cast<MaskedLoadSDNode>(Op);
19144 
19145   SDLoc DL(Op);
19146   EVT VT = Op.getValueType();
19147   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19148 
19149   SDValue Mask = convertFixedMaskToScalableVector(Load->getMask(), DAG);
19150 
19151   SDValue PassThru;
19152   bool IsPassThruZeroOrUndef = false;
19153 
19154   if (Load->getPassThru()->isUndef()) {
19155     PassThru = DAG.getUNDEF(ContainerVT);
19156     IsPassThruZeroOrUndef = true;
19157   } else {
19158     if (ContainerVT.isInteger())
19159       PassThru = DAG.getConstant(0, DL, ContainerVT);
19160     else
19161       PassThru = DAG.getConstantFP(0, DL, ContainerVT);
19162     if (isZerosVector(Load->getPassThru().getNode()))
19163       IsPassThruZeroOrUndef = true;
19164   }
19165 
19166   auto NewLoad = DAG.getMaskedLoad(
19167       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
19168       Mask, PassThru, Load->getMemoryVT(), Load->getMemOperand(),
19169       Load->getAddressingMode(), Load->getExtensionType());
19170 
19171   if (!IsPassThruZeroOrUndef) {
19172     SDValue OldPassThru =
19173         convertToScalableVector(DAG, ContainerVT, Load->getPassThru());
19174     NewLoad = DAG.getSelect(DL, ContainerVT, Mask, NewLoad, OldPassThru);
19175   }
19176 
19177   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
19178   SDValue MergedValues[2] = {Result, Load->getChain()};
19179   return DAG.getMergeValues(MergedValues, DL);
19180 }
19181 
19182 // Convert all fixed length vector stores larger than NEON to masked_stores.
19183 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
19184     SDValue Op, SelectionDAG &DAG) const {
19185   auto Store = cast<StoreSDNode>(Op);
19186 
19187   SDLoc DL(Op);
19188   EVT VT = Store->getValue().getValueType();
19189   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19190   EVT MemVT = Store->getMemoryVT();
19191 
19192   auto Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
19193   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
19194 
19195   if (VT.isFloatingPoint() && Store->isTruncatingStore()) {
19196     EVT TruncVT = ContainerVT.changeVectorElementType(
19197         Store->getMemoryVT().getVectorElementType());
19198     MemVT = MemVT.changeTypeToInteger();
19199     NewValue = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, TruncVT, Pg,
19200                            NewValue, DAG.getTargetConstant(0, DL, MVT::i64),
19201                            DAG.getUNDEF(TruncVT));
19202     NewValue =
19203         getSVESafeBitCast(ContainerVT.changeTypeToInteger(), NewValue, DAG);
19204   }
19205 
19206   return DAG.getMaskedStore(Store->getChain(), DL, NewValue,
19207                             Store->getBasePtr(), Store->getOffset(), Pg, MemVT,
19208                             Store->getMemOperand(), Store->getAddressingMode(),
19209                             Store->isTruncatingStore());
19210 }
19211 
19212 SDValue AArch64TargetLowering::LowerFixedLengthVectorMStoreToSVE(
19213     SDValue Op, SelectionDAG &DAG) const {
19214   auto *Store = cast<MaskedStoreSDNode>(Op);
19215 
19216   SDLoc DL(Op);
19217   EVT VT = Store->getValue().getValueType();
19218   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19219 
19220   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
19221   SDValue Mask = convertFixedMaskToScalableVector(Store->getMask(), DAG);
19222 
19223   return DAG.getMaskedStore(
19224       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
19225       Mask, Store->getMemoryVT(), Store->getMemOperand(),
19226       Store->getAddressingMode(), Store->isTruncatingStore());
19227 }
19228 
19229 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
19230     SDValue Op, SelectionDAG &DAG) const {
19231   SDLoc dl(Op);
19232   EVT VT = Op.getValueType();
19233   EVT EltVT = VT.getVectorElementType();
19234 
19235   bool Signed = Op.getOpcode() == ISD::SDIV;
19236   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
19237 
19238   bool Negated;
19239   uint64_t SplatVal;
19240   if (Signed && isPow2Splat(Op.getOperand(1), SplatVal, Negated)) {
19241     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19242     SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
19243     SDValue Op2 = DAG.getTargetConstant(Log2_64(SplatVal), dl, MVT::i32);
19244 
19245     SDValue Pg = getPredicateForFixedLengthVector(DAG, dl, VT);
19246     SDValue Res = DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, dl, ContainerVT, Pg, Op1, Op2);
19247     if (Negated)
19248       Res = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), Res);
19249 
19250     return convertFromScalableVector(DAG, VT, Res);
19251   }
19252 
19253   // Scalable vector i32/i64 DIV is supported.
19254   if (EltVT == MVT::i32 || EltVT == MVT::i64)
19255     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
19256 
19257   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
19258   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19259   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
19260   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
19261   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
19262 
19263   // If this is not a full vector, extend, div, and truncate it.
19264   EVT WidenedVT = VT.widenIntegerVectorElementType(*DAG.getContext());
19265   if (DAG.getTargetLoweringInfo().isTypeLegal(WidenedVT)) {
19266     unsigned ExtendOpcode = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19267     SDValue Op0 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(0));
19268     SDValue Op1 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(1));
19269     SDValue Div = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0, Op1);
19270     return DAG.getNode(ISD::TRUNCATE, dl, VT, Div);
19271   }
19272 
19273   // Convert the operands to scalable vectors.
19274   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
19275   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
19276 
19277   // Extend the scalable operands.
19278   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
19279   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
19280   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
19281   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
19282   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
19283   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
19284 
19285   // Convert back to fixed vectors so the DIV can be further lowered.
19286   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
19287   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
19288   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
19289   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
19290   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
19291                                  Op0Lo, Op1Lo);
19292   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
19293                                  Op0Hi, Op1Hi);
19294 
19295   // Convert again to scalable vectors to truncate.
19296   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
19297   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
19298   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
19299                                        ResultLo, ResultHi);
19300 
19301   return convertFromScalableVector(DAG, VT, ScalableResult);
19302 }
19303 
19304 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
19305     SDValue Op, SelectionDAG &DAG) const {
19306   EVT VT = Op.getValueType();
19307   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19308 
19309   SDLoc DL(Op);
19310   SDValue Val = Op.getOperand(0);
19311   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
19312   Val = convertToScalableVector(DAG, ContainerVT, Val);
19313 
19314   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
19315   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
19316 
19317   // Repeatedly unpack Val until the result is of the desired element type.
19318   switch (ContainerVT.getSimpleVT().SimpleTy) {
19319   default:
19320     llvm_unreachable("unimplemented container type");
19321   case MVT::nxv16i8:
19322     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
19323     if (VT.getVectorElementType() == MVT::i16)
19324       break;
19325     LLVM_FALLTHROUGH;
19326   case MVT::nxv8i16:
19327     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
19328     if (VT.getVectorElementType() == MVT::i32)
19329       break;
19330     LLVM_FALLTHROUGH;
19331   case MVT::nxv4i32:
19332     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
19333     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
19334     break;
19335   }
19336 
19337   return convertFromScalableVector(DAG, VT, Val);
19338 }
19339 
19340 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
19341     SDValue Op, SelectionDAG &DAG) const {
19342   EVT VT = Op.getValueType();
19343   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19344 
19345   SDLoc DL(Op);
19346   SDValue Val = Op.getOperand(0);
19347   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
19348   Val = convertToScalableVector(DAG, ContainerVT, Val);
19349 
19350   // Repeatedly truncate Val until the result is of the desired element type.
19351   switch (ContainerVT.getSimpleVT().SimpleTy) {
19352   default:
19353     llvm_unreachable("unimplemented container type");
19354   case MVT::nxv2i64:
19355     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
19356     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
19357     if (VT.getVectorElementType() == MVT::i32)
19358       break;
19359     LLVM_FALLTHROUGH;
19360   case MVT::nxv4i32:
19361     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
19362     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
19363     if (VT.getVectorElementType() == MVT::i16)
19364       break;
19365     LLVM_FALLTHROUGH;
19366   case MVT::nxv8i16:
19367     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
19368     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
19369     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
19370     break;
19371   }
19372 
19373   return convertFromScalableVector(DAG, VT, Val);
19374 }
19375 
19376 SDValue AArch64TargetLowering::LowerFixedLengthExtractVectorElt(
19377     SDValue Op, SelectionDAG &DAG) const {
19378   EVT VT = Op.getValueType();
19379   EVT InVT = Op.getOperand(0).getValueType();
19380   assert(InVT.isFixedLengthVector() && "Expected fixed length vector type!");
19381 
19382   SDLoc DL(Op);
19383   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
19384   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
19385 
19386   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Op.getOperand(1));
19387 }
19388 
19389 SDValue AArch64TargetLowering::LowerFixedLengthInsertVectorElt(
19390     SDValue Op, SelectionDAG &DAG) const {
19391   EVT VT = Op.getValueType();
19392   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19393 
19394   SDLoc DL(Op);
19395   EVT InVT = Op.getOperand(0).getValueType();
19396   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
19397   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
19398 
19399   auto ScalableRes = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, Op0,
19400                                  Op.getOperand(1), Op.getOperand(2));
19401 
19402   return convertFromScalableVector(DAG, VT, ScalableRes);
19403 }
19404 
19405 // Convert vector operation 'Op' to an equivalent predicated operation whereby
19406 // the original operation's type is used to construct a suitable predicate.
19407 // NOTE: The results for inactive lanes are undefined.
19408 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
19409                                                    SelectionDAG &DAG,
19410                                                    unsigned NewOp,
19411                                                    bool OverrideNEON) const {
19412   EVT VT = Op.getValueType();
19413   SDLoc DL(Op);
19414   auto Pg = getPredicateForVector(DAG, DL, VT);
19415 
19416   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
19417     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19418 
19419     // Create list of operands by converting existing ones to scalable types.
19420     SmallVector<SDValue, 4> Operands = {Pg};
19421     for (const SDValue &V : Op->op_values()) {
19422       if (isa<CondCodeSDNode>(V)) {
19423         Operands.push_back(V);
19424         continue;
19425       }
19426 
19427       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
19428         EVT VTArg = VTNode->getVT().getVectorElementType();
19429         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
19430         Operands.push_back(DAG.getValueType(NewVTArg));
19431         continue;
19432       }
19433 
19434       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
19435              "Only fixed length vectors are supported!");
19436       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
19437     }
19438 
19439     if (isMergePassthruOpcode(NewOp))
19440       Operands.push_back(DAG.getUNDEF(ContainerVT));
19441 
19442     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
19443     return convertFromScalableVector(DAG, VT, ScalableRes);
19444   }
19445 
19446   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
19447 
19448   SmallVector<SDValue, 4> Operands = {Pg};
19449   for (const SDValue &V : Op->op_values()) {
19450     assert((!V.getValueType().isVector() ||
19451             V.getValueType().isScalableVector()) &&
19452            "Only scalable vectors are supported!");
19453     Operands.push_back(V);
19454   }
19455 
19456   if (isMergePassthruOpcode(NewOp))
19457     Operands.push_back(DAG.getUNDEF(VT));
19458 
19459   return DAG.getNode(NewOp, DL, VT, Operands, Op->getFlags());
19460 }
19461 
19462 // If a fixed length vector operation has no side effects when applied to
19463 // undefined elements, we can safely use scalable vectors to perform the same
19464 // operation without needing to worry about predication.
19465 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
19466                                                  SelectionDAG &DAG) const {
19467   EVT VT = Op.getValueType();
19468   assert(useSVEForFixedLengthVectorVT(VT) &&
19469          "Only expected to lower fixed length vector operation!");
19470   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19471 
19472   // Create list of operands by converting existing ones to scalable types.
19473   SmallVector<SDValue, 4> Ops;
19474   for (const SDValue &V : Op->op_values()) {
19475     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
19476 
19477     // Pass through non-vector operands.
19478     if (!V.getValueType().isVector()) {
19479       Ops.push_back(V);
19480       continue;
19481     }
19482 
19483     // "cast" fixed length vector to a scalable vector.
19484     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
19485            "Only fixed length vectors are supported!");
19486     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
19487   }
19488 
19489   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
19490   return convertFromScalableVector(DAG, VT, ScalableRes);
19491 }
19492 
19493 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
19494     SelectionDAG &DAG) const {
19495   SDLoc DL(ScalarOp);
19496   SDValue AccOp = ScalarOp.getOperand(0);
19497   SDValue VecOp = ScalarOp.getOperand(1);
19498   EVT SrcVT = VecOp.getValueType();
19499   EVT ResVT = SrcVT.getVectorElementType();
19500 
19501   EVT ContainerVT = SrcVT;
19502   if (SrcVT.isFixedLengthVector()) {
19503     ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
19504     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
19505   }
19506 
19507   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
19508   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
19509 
19510   // Convert operands to Scalable.
19511   AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
19512                       DAG.getUNDEF(ContainerVT), AccOp, Zero);
19513 
19514   // Perform reduction.
19515   SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
19516                             Pg, AccOp, VecOp);
19517 
19518   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
19519 }
19520 
19521 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
19522                                                        SelectionDAG &DAG) const {
19523   SDLoc DL(ReduceOp);
19524   SDValue Op = ReduceOp.getOperand(0);
19525   EVT OpVT = Op.getValueType();
19526   EVT VT = ReduceOp.getValueType();
19527 
19528   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
19529     return SDValue();
19530 
19531   SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
19532 
19533   switch (ReduceOp.getOpcode()) {
19534   default:
19535     return SDValue();
19536   case ISD::VECREDUCE_OR:
19537     if (isAllActivePredicate(DAG, Pg))
19538       // The predicate can be 'Op' because
19539       // vecreduce_or(Op & <all true>) <=> vecreduce_or(Op).
19540       return getPTest(DAG, VT, Op, Op, AArch64CC::ANY_ACTIVE);
19541     else
19542       return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
19543   case ISD::VECREDUCE_AND: {
19544     Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
19545     return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
19546   }
19547   case ISD::VECREDUCE_XOR: {
19548     SDValue ID =
19549         DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
19550     SDValue Cntp =
19551         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
19552     return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
19553   }
19554   }
19555 
19556   return SDValue();
19557 }
19558 
19559 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
19560                                                    SDValue ScalarOp,
19561                                                    SelectionDAG &DAG) const {
19562   SDLoc DL(ScalarOp);
19563   SDValue VecOp = ScalarOp.getOperand(0);
19564   EVT SrcVT = VecOp.getValueType();
19565 
19566   if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
19567     EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
19568     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
19569   }
19570 
19571   // UADDV always returns an i64 result.
19572   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
19573                                                    SrcVT.getVectorElementType();
19574   EVT RdxVT = SrcVT;
19575   if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
19576     RdxVT = getPackedSVEVectorVT(ResVT);
19577 
19578   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
19579   SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
19580   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
19581                             Rdx, DAG.getConstant(0, DL, MVT::i64));
19582 
19583   // The VEC_REDUCE nodes expect an element size result.
19584   if (ResVT != ScalarOp.getValueType())
19585     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
19586 
19587   return Res;
19588 }
19589 
19590 SDValue
19591 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
19592     SelectionDAG &DAG) const {
19593   EVT VT = Op.getValueType();
19594   SDLoc DL(Op);
19595 
19596   EVT InVT = Op.getOperand(1).getValueType();
19597   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
19598   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
19599   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
19600 
19601   // Convert the mask to a predicated (NOTE: We don't need to worry about
19602   // inactive lanes since VSELECT is safe when given undefined elements).
19603   EVT MaskVT = Op.getOperand(0).getValueType();
19604   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
19605   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
19606   Mask = DAG.getNode(ISD::TRUNCATE, DL,
19607                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
19608 
19609   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
19610                                 Mask, Op1, Op2);
19611 
19612   return convertFromScalableVector(DAG, VT, ScalableRes);
19613 }
19614 
19615 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
19616     SDValue Op, SelectionDAG &DAG) const {
19617   SDLoc DL(Op);
19618   EVT InVT = Op.getOperand(0).getValueType();
19619   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
19620 
19621   assert(useSVEForFixedLengthVectorVT(InVT) &&
19622          "Only expected to lower fixed length vector operation!");
19623   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
19624          "Expected integer result of the same bit length as the inputs!");
19625 
19626   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
19627   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
19628   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
19629 
19630   EVT CmpVT = Pg.getValueType();
19631   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
19632                          {Pg, Op1, Op2, Op.getOperand(2)});
19633 
19634   EVT PromoteVT = ContainerVT.changeTypeToInteger();
19635   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
19636   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
19637 }
19638 
19639 SDValue
19640 AArch64TargetLowering::LowerFixedLengthBitcastToSVE(SDValue Op,
19641                                                     SelectionDAG &DAG) const {
19642   SDLoc DL(Op);
19643   auto SrcOp = Op.getOperand(0);
19644   EVT VT = Op.getValueType();
19645   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
19646   EVT ContainerSrcVT =
19647       getContainerForFixedLengthVector(DAG, SrcOp.getValueType());
19648 
19649   SrcOp = convertToScalableVector(DAG, ContainerSrcVT, SrcOp);
19650   Op = DAG.getNode(ISD::BITCAST, DL, ContainerDstVT, SrcOp);
19651   return convertFromScalableVector(DAG, VT, Op);
19652 }
19653 
19654 SDValue AArch64TargetLowering::LowerFixedLengthConcatVectorsToSVE(
19655     SDValue Op, SelectionDAG &DAG) const {
19656   SDLoc DL(Op);
19657   unsigned NumOperands = Op->getNumOperands();
19658 
19659   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
19660          "Unexpected number of operands in CONCAT_VECTORS");
19661 
19662   auto SrcOp1 = Op.getOperand(0);
19663   auto SrcOp2 = Op.getOperand(1);
19664   EVT VT = Op.getValueType();
19665   EVT SrcVT = SrcOp1.getValueType();
19666 
19667   if (NumOperands > 2) {
19668     SmallVector<SDValue, 4> Ops;
19669     EVT PairVT = SrcVT.getDoubleNumVectorElementsVT(*DAG.getContext());
19670     for (unsigned I = 0; I < NumOperands; I += 2)
19671       Ops.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, PairVT,
19672                                 Op->getOperand(I), Op->getOperand(I + 1)));
19673 
19674     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Ops);
19675   }
19676 
19677   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19678 
19679   SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
19680   SrcOp1 = convertToScalableVector(DAG, ContainerVT, SrcOp1);
19681   SrcOp2 = convertToScalableVector(DAG, ContainerVT, SrcOp2);
19682 
19683   Op = DAG.getNode(AArch64ISD::SPLICE, DL, ContainerVT, Pg, SrcOp1, SrcOp2);
19684 
19685   return convertFromScalableVector(DAG, VT, Op);
19686 }
19687 
19688 SDValue
19689 AArch64TargetLowering::LowerFixedLengthFPExtendToSVE(SDValue Op,
19690                                                      SelectionDAG &DAG) const {
19691   EVT VT = Op.getValueType();
19692   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19693 
19694   SDLoc DL(Op);
19695   SDValue Val = Op.getOperand(0);
19696   SDValue Pg = getPredicateForVector(DAG, DL, VT);
19697   EVT SrcVT = Val.getValueType();
19698   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19699   EVT ExtendVT = ContainerVT.changeVectorElementType(
19700       SrcVT.getVectorElementType());
19701 
19702   Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
19703   Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT.changeTypeToInteger(), Val);
19704 
19705   Val = convertToScalableVector(DAG, ContainerVT.changeTypeToInteger(), Val);
19706   Val = getSVESafeBitCast(ExtendVT, Val, DAG);
19707   Val = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
19708                     Pg, Val, DAG.getUNDEF(ContainerVT));
19709 
19710   return convertFromScalableVector(DAG, VT, Val);
19711 }
19712 
19713 SDValue
19714 AArch64TargetLowering::LowerFixedLengthFPRoundToSVE(SDValue Op,
19715                                                     SelectionDAG &DAG) const {
19716   EVT VT = Op.getValueType();
19717   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19718 
19719   SDLoc DL(Op);
19720   SDValue Val = Op.getOperand(0);
19721   EVT SrcVT = Val.getValueType();
19722   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
19723   EVT RoundVT = ContainerSrcVT.changeVectorElementType(
19724       VT.getVectorElementType());
19725   SDValue Pg = getPredicateForVector(DAG, DL, RoundVT);
19726 
19727   Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19728   Val = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, RoundVT, Pg, Val,
19729                     Op.getOperand(1), DAG.getUNDEF(RoundVT));
19730   Val = getSVESafeBitCast(ContainerSrcVT.changeTypeToInteger(), Val, DAG);
19731   Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
19732 
19733   Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
19734   return DAG.getNode(ISD::BITCAST, DL, VT, Val);
19735 }
19736 
19737 SDValue
19738 AArch64TargetLowering::LowerFixedLengthIntToFPToSVE(SDValue Op,
19739                                                     SelectionDAG &DAG) const {
19740   EVT VT = Op.getValueType();
19741   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19742 
19743   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
19744   unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
19745                              : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
19746 
19747   SDLoc DL(Op);
19748   SDValue Val = Op.getOperand(0);
19749   EVT SrcVT = Val.getValueType();
19750   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
19751   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
19752 
19753   if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
19754       ContainerDstVT.getVectorElementType().getSizeInBits()) {
19755     SDValue Pg = getPredicateForVector(DAG, DL, VT);
19756 
19757     Val = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
19758                       VT.changeTypeToInteger(), Val);
19759 
19760     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19761     Val = getSVESafeBitCast(ContainerDstVT.changeTypeToInteger(), Val, DAG);
19762     // Safe to use a larger than specified operand since we just unpacked the
19763     // data, hence the upper bits are zero.
19764     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
19765                       DAG.getUNDEF(ContainerDstVT));
19766     return convertFromScalableVector(DAG, VT, Val);
19767   } else {
19768     EVT CvtVT = ContainerSrcVT.changeVectorElementType(
19769         ContainerDstVT.getVectorElementType());
19770     SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
19771 
19772     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19773     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
19774     Val = getSVESafeBitCast(ContainerSrcVT, Val, DAG);
19775     Val = convertFromScalableVector(DAG, SrcVT, Val);
19776 
19777     Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
19778     return DAG.getNode(ISD::BITCAST, DL, VT, Val);
19779   }
19780 }
19781 
19782 SDValue
19783 AArch64TargetLowering::LowerFixedLengthFPToIntToSVE(SDValue Op,
19784                                                     SelectionDAG &DAG) const {
19785   EVT VT = Op.getValueType();
19786   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19787 
19788   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
19789   unsigned Opcode = IsSigned ? AArch64ISD::FCVTZS_MERGE_PASSTHRU
19790                              : AArch64ISD::FCVTZU_MERGE_PASSTHRU;
19791 
19792   SDLoc DL(Op);
19793   SDValue Val = Op.getOperand(0);
19794   EVT SrcVT = Val.getValueType();
19795   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
19796   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
19797 
19798   if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
19799       ContainerDstVT.getVectorElementType().getSizeInBits()) {
19800     EVT CvtVT = ContainerDstVT.changeVectorElementType(
19801       ContainerSrcVT.getVectorElementType());
19802     SDValue Pg = getPredicateForVector(DAG, DL, VT);
19803 
19804     Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
19805     Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Val);
19806 
19807     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19808     Val = getSVESafeBitCast(CvtVT, Val, DAG);
19809     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
19810                       DAG.getUNDEF(ContainerDstVT));
19811     return convertFromScalableVector(DAG, VT, Val);
19812   } else {
19813     EVT CvtVT = ContainerSrcVT.changeTypeToInteger();
19814     SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
19815 
19816     // Safe to use a larger than specified result since an fp_to_int where the
19817     // result doesn't fit into the destination is undefined.
19818     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19819     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
19820     Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
19821 
19822     return DAG.getNode(ISD::TRUNCATE, DL, VT, Val);
19823   }
19824 }
19825 
19826 SDValue AArch64TargetLowering::LowerFixedLengthVECTOR_SHUFFLEToSVE(
19827     SDValue Op, SelectionDAG &DAG) const {
19828   EVT VT = Op.getValueType();
19829   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19830 
19831   auto *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
19832   auto ShuffleMask = SVN->getMask();
19833 
19834   SDLoc DL(Op);
19835   SDValue Op1 = Op.getOperand(0);
19836   SDValue Op2 = Op.getOperand(1);
19837 
19838   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19839   Op1 = convertToScalableVector(DAG, ContainerVT, Op1);
19840   Op2 = convertToScalableVector(DAG, ContainerVT, Op2);
19841 
19842   bool ReverseEXT = false;
19843   unsigned Imm;
19844   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm) &&
19845       Imm == VT.getVectorNumElements() - 1) {
19846     if (ReverseEXT)
19847       std::swap(Op1, Op2);
19848 
19849     EVT ScalarTy = VT.getVectorElementType();
19850     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
19851       ScalarTy = MVT::i32;
19852     SDValue Scalar = DAG.getNode(
19853         ISD::EXTRACT_VECTOR_ELT, DL, ScalarTy, Op1,
19854         DAG.getConstant(VT.getVectorNumElements() - 1, DL, MVT::i64));
19855     Op = DAG.getNode(AArch64ISD::INSR, DL, ContainerVT, Op2, Scalar);
19856     return convertFromScalableVector(DAG, VT, Op);
19857   }
19858 
19859   for (unsigned LaneSize : {64U, 32U, 16U}) {
19860     if (isREVMask(ShuffleMask, VT, LaneSize)) {
19861       EVT NewVT =
19862           getPackedSVEVectorVT(EVT::getIntegerVT(*DAG.getContext(), LaneSize));
19863       unsigned RevOp;
19864       unsigned EltSz = VT.getScalarSizeInBits();
19865       if (EltSz == 8)
19866         RevOp = AArch64ISD::BSWAP_MERGE_PASSTHRU;
19867       else if (EltSz == 16)
19868         RevOp = AArch64ISD::REVH_MERGE_PASSTHRU;
19869       else
19870         RevOp = AArch64ISD::REVW_MERGE_PASSTHRU;
19871 
19872       Op = DAG.getNode(ISD::BITCAST, DL, NewVT, Op1);
19873       Op = LowerToPredicatedOp(Op, DAG, RevOp);
19874       Op = DAG.getNode(ISD::BITCAST, DL, ContainerVT, Op);
19875       return convertFromScalableVector(DAG, VT, Op);
19876     }
19877   }
19878 
19879   unsigned WhichResult;
19880   if (isZIPMask(ShuffleMask, VT, WhichResult) && WhichResult == 0)
19881     return convertFromScalableVector(
19882         DAG, VT, DAG.getNode(AArch64ISD::ZIP1, DL, ContainerVT, Op1, Op2));
19883 
19884   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
19885     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
19886     return convertFromScalableVector(
19887         DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op2));
19888   }
19889 
19890   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult) && WhichResult == 0)
19891     return convertFromScalableVector(
19892         DAG, VT, DAG.getNode(AArch64ISD::ZIP1, DL, ContainerVT, Op1, Op1));
19893 
19894   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
19895     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
19896     return convertFromScalableVector(
19897         DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op1));
19898   }
19899 
19900   // Functions like isZIPMask return true when a ISD::VECTOR_SHUFFLE's mask
19901   // represents the same logical operation as performed by a ZIP instruction. In
19902   // isolation these functions do not mean the ISD::VECTOR_SHUFFLE is exactly
19903   // equivalent to an AArch64 instruction. There's the extra component of
19904   // ISD::VECTOR_SHUFFLE's value type to consider. Prior to SVE these functions
19905   // only operated on 64/128bit vector types that have a direct mapping to a
19906   // target register and so an exact mapping is implied.
19907   // However, when using SVE for fixed length vectors, most legal vector types
19908   // are actually sub-vectors of a larger SVE register. When mapping
19909   // ISD::VECTOR_SHUFFLE to an SVE instruction care must be taken to consider
19910   // how the mask's indices translate. Specifically, when the mapping requires
19911   // an exact meaning for a specific vector index (e.g. Index X is the last
19912   // vector element in the register) then such mappings are often only safe when
19913   // the exact SVE register size is know. The main exception to this is when
19914   // indices are logically relative to the first element of either
19915   // ISD::VECTOR_SHUFFLE operand because these relative indices don't change
19916   // when converting from fixed-length to scalable vector types (i.e. the start
19917   // of a fixed length vector is always the start of a scalable vector).
19918   unsigned MinSVESize = Subtarget->getMinSVEVectorSizeInBits();
19919   unsigned MaxSVESize = Subtarget->getMaxSVEVectorSizeInBits();
19920   if (MinSVESize == MaxSVESize && MaxSVESize == VT.getSizeInBits()) {
19921     if (ShuffleVectorInst::isReverseMask(ShuffleMask) && Op2.isUndef()) {
19922       Op = DAG.getNode(ISD::VECTOR_REVERSE, DL, ContainerVT, Op1);
19923       return convertFromScalableVector(DAG, VT, Op);
19924     }
19925 
19926     if (isZIPMask(ShuffleMask, VT, WhichResult) && WhichResult != 0)
19927       return convertFromScalableVector(
19928           DAG, VT, DAG.getNode(AArch64ISD::ZIP2, DL, ContainerVT, Op1, Op2));
19929 
19930     if (isUZPMask(ShuffleMask, VT, WhichResult)) {
19931       unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
19932       return convertFromScalableVector(
19933           DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op2));
19934     }
19935 
19936     if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult) && WhichResult != 0)
19937       return convertFromScalableVector(
19938           DAG, VT, DAG.getNode(AArch64ISD::ZIP2, DL, ContainerVT, Op1, Op1));
19939 
19940     if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
19941       unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
19942       return convertFromScalableVector(
19943           DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op1));
19944     }
19945   }
19946 
19947   return SDValue();
19948 }
19949 
19950 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
19951                                                  SelectionDAG &DAG) const {
19952   SDLoc DL(Op);
19953   EVT InVT = Op.getValueType();
19954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19955   (void)TLI;
19956 
19957   assert(VT.isScalableVector() && TLI.isTypeLegal(VT) &&
19958          InVT.isScalableVector() && TLI.isTypeLegal(InVT) &&
19959          "Only expect to cast between legal scalable vector types!");
19960   assert((VT.getVectorElementType() == MVT::i1) ==
19961              (InVT.getVectorElementType() == MVT::i1) &&
19962          "Cannot cast between data and predicate scalable vector types!");
19963 
19964   if (InVT == VT)
19965     return Op;
19966 
19967   if (VT.getVectorElementType() == MVT::i1)
19968     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
19969 
19970   EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
19971   EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
19972 
19973   // Pack input if required.
19974   if (InVT != PackedInVT)
19975     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
19976 
19977   Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
19978 
19979   // Unpack result if required.
19980   if (VT != PackedVT)
19981     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
19982 
19983   return Op;
19984 }
19985 
19986 bool AArch64TargetLowering::isAllActivePredicate(SelectionDAG &DAG,
19987                                                  SDValue N) const {
19988   return ::isAllActivePredicate(DAG, N);
19989 }
19990 
19991 EVT AArch64TargetLowering::getPromotedVTForPredicate(EVT VT) const {
19992   return ::getPromotedVTForPredicate(VT);
19993 }
19994 
19995 bool AArch64TargetLowering::SimplifyDemandedBitsForTargetNode(
19996     SDValue Op, const APInt &OriginalDemandedBits,
19997     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
19998     unsigned Depth) const {
19999 
20000   unsigned Opc = Op.getOpcode();
20001   switch (Opc) {
20002   case AArch64ISD::VSHL: {
20003     // Match (VSHL (VLSHR Val X) X)
20004     SDValue ShiftL = Op;
20005     SDValue ShiftR = Op->getOperand(0);
20006     if (ShiftR->getOpcode() != AArch64ISD::VLSHR)
20007       return false;
20008 
20009     if (!ShiftL.hasOneUse() || !ShiftR.hasOneUse())
20010       return false;
20011 
20012     unsigned ShiftLBits = ShiftL->getConstantOperandVal(1);
20013     unsigned ShiftRBits = ShiftR->getConstantOperandVal(1);
20014 
20015     // Other cases can be handled as well, but this is not
20016     // implemented.
20017     if (ShiftRBits != ShiftLBits)
20018       return false;
20019 
20020     unsigned ScalarSize = Op.getScalarValueSizeInBits();
20021     assert(ScalarSize > ShiftLBits && "Invalid shift imm");
20022 
20023     APInt ZeroBits = APInt::getLowBitsSet(ScalarSize, ShiftLBits);
20024     APInt UnusedBits = ~OriginalDemandedBits;
20025 
20026     if ((ZeroBits & UnusedBits) != ZeroBits)
20027       return false;
20028 
20029     // All bits that are zeroed by (VSHL (VLSHR Val X) X) are not
20030     // used - simplify to just Val.
20031     return TLO.CombineTo(Op, ShiftR->getOperand(0));
20032   }
20033   }
20034 
20035   return TargetLowering::SimplifyDemandedBitsForTargetNode(
20036       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
20037 }
20038 
20039 bool AArch64TargetLowering::isConstantUnsignedBitfieldExtractLegal(
20040     unsigned Opc, LLT Ty1, LLT Ty2) const {
20041   return Ty1 == Ty2 && (Ty1 == LLT::scalar(32) || Ty1 == LLT::scalar(64));
20042 }
20043