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/Twine.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ObjCARCUtil.h"
34 #include "llvm/Analysis/TargetTransformInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineMemOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/MachineValueType.h"
48 #include "llvm/CodeGen/RuntimeLibcalls.h"
49 #include "llvm/CodeGen/SelectionDAG.h"
50 #include "llvm/CodeGen/SelectionDAGNodes.h"
51 #include "llvm/CodeGen/TargetCallingConv.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Attributes.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GetElementPtrTypeIterator.h"
61 #include "llvm/IR/GlobalValue.h"
62 #include "llvm/IR/IRBuilder.h"
63 #include "llvm/IR/Instruction.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/Intrinsics.h"
67 #include "llvm/IR/IntrinsicsAArch64.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/OperandTraits.h"
70 #include "llvm/IR/PatternMatch.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCRegisterInfo.h"
75 #include "llvm/Support/AtomicOrdering.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CodeGen.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/InstructionCost.h"
83 #include "llvm/Support/KnownBits.h"
84 #include "llvm/Support/MathExtras.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include "llvm/TargetParser/Triple.h"
89 #include <algorithm>
90 #include <bitset>
91 #include <cassert>
92 #include <cctype>
93 #include <cstdint>
94 #include <cstdlib>
95 #include <iterator>
96 #include <limits>
97 #include <optional>
98 #include <tuple>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 using namespace llvm::PatternMatch;
104 
105 #define DEBUG_TYPE "aarch64-lower"
106 
107 STATISTIC(NumTailCalls, "Number of tail calls");
108 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
109 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
110 
111 // FIXME: The necessary dtprel relocations don't seem to be supported
112 // well in the GNU bfd and gold linkers at the moment. Therefore, by
113 // default, for now, fall back to GeneralDynamic code generation.
114 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
115     "aarch64-elf-ldtls-generation", cl::Hidden,
116     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
117     cl::init(false));
118 
119 static cl::opt<bool>
120 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
121                          cl::desc("Enable AArch64 logical imm instruction "
122                                   "optimization"),
123                          cl::init(true));
124 
125 // Temporary option added for the purpose of testing functionality added
126 // to DAGCombiner.cpp in D92230. It is expected that this can be removed
127 // in future when both implementations will be based off MGATHER rather
128 // than the GLD1 nodes added for the SVE gather load intrinsics.
129 static cl::opt<bool>
130 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
131                                 cl::desc("Combine extends of AArch64 masked "
132                                          "gather intrinsics"),
133                                 cl::init(true));
134 
135 // All of the XOR, OR and CMP use ALU ports, and data dependency will become the
136 // bottleneck after this transform on high end CPU. So this max leaf node
137 // limitation is guard cmp+ccmp will be profitable.
138 static cl::opt<unsigned> MaxXors("aarch64-max-xors", cl::init(16), cl::Hidden,
139                                  cl::desc("Maximum of xors"));
140 
141 /// Value type used for condition codes.
142 static const MVT MVT_CC = MVT::i32;
143 
144 static const MCPhysReg GPRArgRegs[] = {AArch64::X0, AArch64::X1, AArch64::X2,
145                                        AArch64::X3, AArch64::X4, AArch64::X5,
146                                        AArch64::X6, AArch64::X7};
147 static const MCPhysReg FPRArgRegs[] = {AArch64::Q0, AArch64::Q1, AArch64::Q2,
148                                        AArch64::Q3, AArch64::Q4, AArch64::Q5,
149                                        AArch64::Q6, AArch64::Q7};
150 
151 const ArrayRef<MCPhysReg> llvm::AArch64::getGPRArgRegs() { return GPRArgRegs; }
152 
153 const ArrayRef<MCPhysReg> llvm::AArch64::getFPRArgRegs() { return FPRArgRegs; }
154 
155 static inline EVT getPackedSVEVectorVT(EVT VT) {
156   switch (VT.getSimpleVT().SimpleTy) {
157   default:
158     llvm_unreachable("unexpected element type for vector");
159   case MVT::i8:
160     return MVT::nxv16i8;
161   case MVT::i16:
162     return MVT::nxv8i16;
163   case MVT::i32:
164     return MVT::nxv4i32;
165   case MVT::i64:
166     return MVT::nxv2i64;
167   case MVT::f16:
168     return MVT::nxv8f16;
169   case MVT::f32:
170     return MVT::nxv4f32;
171   case MVT::f64:
172     return MVT::nxv2f64;
173   case MVT::bf16:
174     return MVT::nxv8bf16;
175   }
176 }
177 
178 // NOTE: Currently there's only a need to return integer vector types. If this
179 // changes then just add an extra "type" parameter.
180 static inline EVT getPackedSVEVectorVT(ElementCount EC) {
181   switch (EC.getKnownMinValue()) {
182   default:
183     llvm_unreachable("unexpected element count for vector");
184   case 16:
185     return MVT::nxv16i8;
186   case 8:
187     return MVT::nxv8i16;
188   case 4:
189     return MVT::nxv4i32;
190   case 2:
191     return MVT::nxv2i64;
192   }
193 }
194 
195 static inline EVT getPromotedVTForPredicate(EVT VT) {
196   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
197          "Expected scalable predicate vector type!");
198   switch (VT.getVectorMinNumElements()) {
199   default:
200     llvm_unreachable("unexpected element count for vector");
201   case 2:
202     return MVT::nxv2i64;
203   case 4:
204     return MVT::nxv4i32;
205   case 8:
206     return MVT::nxv8i16;
207   case 16:
208     return MVT::nxv16i8;
209   }
210 }
211 
212 /// Returns true if VT's elements occupy the lowest bit positions of its
213 /// associated register class without any intervening space.
214 ///
215 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
216 /// same register class, but only nxv8f16 can be treated as a packed vector.
217 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
218   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
219          "Expected legal vector type!");
220   return VT.isFixedLengthVector() ||
221          VT.getSizeInBits().getKnownMinValue() == AArch64::SVEBitsPerBlock;
222 }
223 
224 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
225 // predicate and end with a passthru value matching the result type.
226 static bool isMergePassthruOpcode(unsigned Opc) {
227   switch (Opc) {
228   default:
229     return false;
230   case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
231   case AArch64ISD::BSWAP_MERGE_PASSTHRU:
232   case AArch64ISD::REVH_MERGE_PASSTHRU:
233   case AArch64ISD::REVW_MERGE_PASSTHRU:
234   case AArch64ISD::REVD_MERGE_PASSTHRU:
235   case AArch64ISD::CTLZ_MERGE_PASSTHRU:
236   case AArch64ISD::CTPOP_MERGE_PASSTHRU:
237   case AArch64ISD::DUP_MERGE_PASSTHRU:
238   case AArch64ISD::ABS_MERGE_PASSTHRU:
239   case AArch64ISD::NEG_MERGE_PASSTHRU:
240   case AArch64ISD::FNEG_MERGE_PASSTHRU:
241   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
242   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
243   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
244   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
245   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
246   case AArch64ISD::FRINT_MERGE_PASSTHRU:
247   case AArch64ISD::FROUND_MERGE_PASSTHRU:
248   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
249   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
250   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
251   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
252   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
253   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
254   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
255   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
256   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
257   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
258   case AArch64ISD::FABS_MERGE_PASSTHRU:
259     return true;
260   }
261 }
262 
263 // Returns true if inactive lanes are known to be zeroed by construction.
264 static bool isZeroingInactiveLanes(SDValue Op) {
265   switch (Op.getOpcode()) {
266   default:
267     // We guarantee i1 splat_vectors to zero the other lanes by
268     // implementing it with ptrue and possibly a punpklo for nxv1i1.
269     if (ISD::isConstantSplatVectorAllOnes(Op.getNode()))
270       return true;
271     return false;
272   case AArch64ISD::PTRUE:
273   case AArch64ISD::SETCC_MERGE_ZERO:
274     return true;
275   case ISD::INTRINSIC_WO_CHAIN:
276     switch (Op.getConstantOperandVal(0)) {
277     default:
278       return false;
279     case Intrinsic::aarch64_sve_ptrue:
280     case Intrinsic::aarch64_sve_pnext:
281     case Intrinsic::aarch64_sve_cmpeq:
282     case Intrinsic::aarch64_sve_cmpne:
283     case Intrinsic::aarch64_sve_cmpge:
284     case Intrinsic::aarch64_sve_cmpgt:
285     case Intrinsic::aarch64_sve_cmphs:
286     case Intrinsic::aarch64_sve_cmphi:
287     case Intrinsic::aarch64_sve_cmpeq_wide:
288     case Intrinsic::aarch64_sve_cmpne_wide:
289     case Intrinsic::aarch64_sve_cmpge_wide:
290     case Intrinsic::aarch64_sve_cmpgt_wide:
291     case Intrinsic::aarch64_sve_cmplt_wide:
292     case Intrinsic::aarch64_sve_cmple_wide:
293     case Intrinsic::aarch64_sve_cmphs_wide:
294     case Intrinsic::aarch64_sve_cmphi_wide:
295     case Intrinsic::aarch64_sve_cmplo_wide:
296     case Intrinsic::aarch64_sve_cmpls_wide:
297     case Intrinsic::aarch64_sve_fcmpeq:
298     case Intrinsic::aarch64_sve_fcmpne:
299     case Intrinsic::aarch64_sve_fcmpge:
300     case Intrinsic::aarch64_sve_fcmpgt:
301     case Intrinsic::aarch64_sve_fcmpuo:
302     case Intrinsic::aarch64_sve_facgt:
303     case Intrinsic::aarch64_sve_facge:
304     case Intrinsic::aarch64_sve_whilege:
305     case Intrinsic::aarch64_sve_whilegt:
306     case Intrinsic::aarch64_sve_whilehi:
307     case Intrinsic::aarch64_sve_whilehs:
308     case Intrinsic::aarch64_sve_whilele:
309     case Intrinsic::aarch64_sve_whilelo:
310     case Intrinsic::aarch64_sve_whilels:
311     case Intrinsic::aarch64_sve_whilelt:
312     case Intrinsic::aarch64_sve_match:
313     case Intrinsic::aarch64_sve_nmatch:
314     case Intrinsic::aarch64_sve_whilege_x2:
315     case Intrinsic::aarch64_sve_whilegt_x2:
316     case Intrinsic::aarch64_sve_whilehi_x2:
317     case Intrinsic::aarch64_sve_whilehs_x2:
318     case Intrinsic::aarch64_sve_whilele_x2:
319     case Intrinsic::aarch64_sve_whilelo_x2:
320     case Intrinsic::aarch64_sve_whilels_x2:
321     case Intrinsic::aarch64_sve_whilelt_x2:
322       return true;
323     }
324   }
325 }
326 
327 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
328                                              const AArch64Subtarget &STI)
329     : TargetLowering(TM), Subtarget(&STI) {
330   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
331   // we have to make something up. Arbitrarily, choose ZeroOrOne.
332   setBooleanContents(ZeroOrOneBooleanContent);
333   // When comparing vectors the result sets the different elements in the
334   // vector to all-one or all-zero.
335   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
336 
337   // Set up the register classes.
338   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
339   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
340 
341   if (Subtarget->hasLS64()) {
342     addRegisterClass(MVT::i64x8, &AArch64::GPR64x8ClassRegClass);
343     setOperationAction(ISD::LOAD, MVT::i64x8, Custom);
344     setOperationAction(ISD::STORE, MVT::i64x8, Custom);
345   }
346 
347   if (Subtarget->hasFPARMv8()) {
348     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
349     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
350     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
351     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
352     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
353   }
354 
355   if (Subtarget->hasNEON()) {
356     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
357     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
358     // Someone set us up the NEON.
359     addDRTypeForNEON(MVT::v2f32);
360     addDRTypeForNEON(MVT::v8i8);
361     addDRTypeForNEON(MVT::v4i16);
362     addDRTypeForNEON(MVT::v2i32);
363     addDRTypeForNEON(MVT::v1i64);
364     addDRTypeForNEON(MVT::v1f64);
365     addDRTypeForNEON(MVT::v4f16);
366     if (Subtarget->hasBF16())
367       addDRTypeForNEON(MVT::v4bf16);
368 
369     addQRTypeForNEON(MVT::v4f32);
370     addQRTypeForNEON(MVT::v2f64);
371     addQRTypeForNEON(MVT::v16i8);
372     addQRTypeForNEON(MVT::v8i16);
373     addQRTypeForNEON(MVT::v4i32);
374     addQRTypeForNEON(MVT::v2i64);
375     addQRTypeForNEON(MVT::v8f16);
376     if (Subtarget->hasBF16())
377       addQRTypeForNEON(MVT::v8bf16);
378   }
379 
380   if (Subtarget->hasSVEorSME()) {
381     // Add legal sve predicate types
382     addRegisterClass(MVT::nxv1i1, &AArch64::PPRRegClass);
383     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
384     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
385     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
386     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
387 
388     // Add legal sve data types
389     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
390     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
391     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
392     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
393 
394     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
395     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
396     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
397     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
398     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
399     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
400 
401     if (Subtarget->hasBF16()) {
402       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
403       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
404       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
405     }
406 
407     if (Subtarget->useSVEForFixedLengthVectors()) {
408       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
409         if (useSVEForFixedLengthVectorVT(VT))
410           addRegisterClass(VT, &AArch64::ZPRRegClass);
411 
412       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
413         if (useSVEForFixedLengthVectorVT(VT))
414           addRegisterClass(VT, &AArch64::ZPRRegClass);
415     }
416   }
417 
418   if (Subtarget->hasSVE2p1() || Subtarget->hasSME2()) {
419     addRegisterClass(MVT::aarch64svcount, &AArch64::PPRRegClass);
420     setOperationPromotedToType(ISD::LOAD, MVT::aarch64svcount, MVT::nxv16i1);
421     setOperationPromotedToType(ISD::STORE, MVT::aarch64svcount, MVT::nxv16i1);
422 
423     setOperationAction(ISD::SELECT, MVT::aarch64svcount, Custom);
424     setOperationAction(ISD::SELECT_CC, MVT::aarch64svcount, Expand);
425   }
426 
427   // Compute derived properties from the register classes
428   computeRegisterProperties(Subtarget->getRegisterInfo());
429 
430   // Provide all sorts of operation actions
431   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
432   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
433   setOperationAction(ISD::SETCC, MVT::i32, Custom);
434   setOperationAction(ISD::SETCC, MVT::i64, Custom);
435   setOperationAction(ISD::SETCC, MVT::f16, Custom);
436   setOperationAction(ISD::SETCC, MVT::f32, Custom);
437   setOperationAction(ISD::SETCC, MVT::f64, Custom);
438   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
439   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
440   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
441   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
442   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
443   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
444   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
445   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
446   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
447   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
448   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
449   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
450   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
451   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
452   setOperationAction(ISD::SELECT, MVT::i32, Custom);
453   setOperationAction(ISD::SELECT, MVT::i64, Custom);
454   setOperationAction(ISD::SELECT, MVT::f16, Custom);
455   setOperationAction(ISD::SELECT, MVT::bf16, Custom);
456   setOperationAction(ISD::SELECT, MVT::f32, Custom);
457   setOperationAction(ISD::SELECT, MVT::f64, Custom);
458   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
459   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
460   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
461   setOperationAction(ISD::SELECT_CC, MVT::bf16, Expand);
462   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
463   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
464   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
465   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
466   setOperationAction(ISD::SETCCCARRY, MVT::i64, Custom);
467 
468   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
469   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
470   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
471 
472   setOperationAction(ISD::FREM, MVT::f32, Expand);
473   setOperationAction(ISD::FREM, MVT::f64, Expand);
474   setOperationAction(ISD::FREM, MVT::f80, Expand);
475 
476   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
477 
478   // Custom lowering hooks are needed for XOR
479   // to fold it into CSINC/CSINV.
480   setOperationAction(ISD::XOR, MVT::i32, Custom);
481   setOperationAction(ISD::XOR, MVT::i64, Custom);
482 
483   // Virtually no operation on f128 is legal, but LLVM can't expand them when
484   // there's a valid register class, so we need custom operations in most cases.
485   setOperationAction(ISD::FABS, MVT::f128, Expand);
486   setOperationAction(ISD::FADD, MVT::f128, LibCall);
487   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
488   setOperationAction(ISD::FCOS, MVT::f128, Expand);
489   setOperationAction(ISD::FDIV, MVT::f128, LibCall);
490   setOperationAction(ISD::FMA, MVT::f128, Expand);
491   setOperationAction(ISD::FMUL, MVT::f128, LibCall);
492   setOperationAction(ISD::FNEG, MVT::f128, Expand);
493   setOperationAction(ISD::FPOW, MVT::f128, Expand);
494   setOperationAction(ISD::FREM, MVT::f128, Expand);
495   setOperationAction(ISD::FRINT, MVT::f128, Expand);
496   setOperationAction(ISD::FSIN, MVT::f128, Expand);
497   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
498   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
499   setOperationAction(ISD::FSUB, MVT::f128, LibCall);
500   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
501   setOperationAction(ISD::SETCC, MVT::f128, Custom);
502   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
503   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
504   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
505   setOperationAction(ISD::SELECT, MVT::f128, Custom);
506   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
507   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
508   // FIXME: f128 FMINIMUM and FMAXIMUM (including STRICT versions) currently
509   // aren't handled.
510 
511   // Lowering for many of the conversions is actually specified by the non-f128
512   // type. The LowerXXX function will be trivial when f128 isn't involved.
513   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
514   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
515   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
516   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
517   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
518   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
519   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
520   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
521   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
522   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
523   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
524   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
525   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
526   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
527   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
528   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
529   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
530   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
531   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
532   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
533   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
534   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
535   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
536   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
537   setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
538   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
539   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
540   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
541   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
542   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
543 
544   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
545   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
546   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
547   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
548 
549   // Variable arguments.
550   setOperationAction(ISD::VASTART, MVT::Other, Custom);
551   setOperationAction(ISD::VAARG, MVT::Other, Custom);
552   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
553   setOperationAction(ISD::VAEND, MVT::Other, Expand);
554 
555   // Variable-sized objects.
556   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
557   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
558 
559   if (Subtarget->isTargetWindows())
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
561   else
562     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
563 
564   // Constant pool entries
565   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
566 
567   // BlockAddress
568   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
569 
570   // AArch64 lacks both left-rotate and popcount instructions.
571   setOperationAction(ISD::ROTL, MVT::i32, Expand);
572   setOperationAction(ISD::ROTL, MVT::i64, Expand);
573   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
574     setOperationAction(ISD::ROTL, VT, Expand);
575     setOperationAction(ISD::ROTR, VT, Expand);
576   }
577 
578   // AArch64 doesn't have i32 MULH{S|U}.
579   setOperationAction(ISD::MULHU, MVT::i32, Expand);
580   setOperationAction(ISD::MULHS, MVT::i32, Expand);
581 
582   // AArch64 doesn't have {U|S}MUL_LOHI.
583   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
584   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
585   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
586   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
587 
588   if (Subtarget->hasCSSC()) {
589     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
590     setOperationAction(ISD::CTPOP, MVT::i64, Legal);
591     setOperationAction(ISD::CTPOP, MVT::i128, Expand);
592 
593     setOperationAction(ISD::PARITY, MVT::i128, Expand);
594 
595     setOperationAction(ISD::CTTZ, MVT::i32, Legal);
596     setOperationAction(ISD::CTTZ, MVT::i64, Legal);
597     setOperationAction(ISD::CTTZ, MVT::i128, Expand);
598 
599     setOperationAction(ISD::ABS, MVT::i32, Legal);
600     setOperationAction(ISD::ABS, MVT::i64, Legal);
601 
602     setOperationAction(ISD::SMAX, MVT::i32, Legal);
603     setOperationAction(ISD::SMAX, MVT::i64, Legal);
604     setOperationAction(ISD::UMAX, MVT::i32, Legal);
605     setOperationAction(ISD::UMAX, MVT::i64, Legal);
606 
607     setOperationAction(ISD::SMIN, MVT::i32, Legal);
608     setOperationAction(ISD::SMIN, MVT::i64, Legal);
609     setOperationAction(ISD::UMIN, MVT::i32, Legal);
610     setOperationAction(ISD::UMIN, MVT::i64, Legal);
611   } else {
612     setOperationAction(ISD::CTPOP, MVT::i32, Custom);
613     setOperationAction(ISD::CTPOP, MVT::i64, Custom);
614     setOperationAction(ISD::CTPOP, MVT::i128, Custom);
615 
616     setOperationAction(ISD::PARITY, MVT::i64, Custom);
617     setOperationAction(ISD::PARITY, MVT::i128, Custom);
618 
619     setOperationAction(ISD::ABS, MVT::i32, Custom);
620     setOperationAction(ISD::ABS, MVT::i64, Custom);
621   }
622 
623   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
624   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
625   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
626     setOperationAction(ISD::SDIVREM, VT, Expand);
627     setOperationAction(ISD::UDIVREM, VT, Expand);
628   }
629   setOperationAction(ISD::SREM, MVT::i32, Expand);
630   setOperationAction(ISD::SREM, MVT::i64, Expand);
631   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
632   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
633   setOperationAction(ISD::UREM, MVT::i32, Expand);
634   setOperationAction(ISD::UREM, MVT::i64, Expand);
635 
636   // Custom lower Add/Sub/Mul with overflow.
637   setOperationAction(ISD::SADDO, MVT::i32, Custom);
638   setOperationAction(ISD::SADDO, MVT::i64, Custom);
639   setOperationAction(ISD::UADDO, MVT::i32, Custom);
640   setOperationAction(ISD::UADDO, MVT::i64, Custom);
641   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
642   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
643   setOperationAction(ISD::USUBO, MVT::i32, Custom);
644   setOperationAction(ISD::USUBO, MVT::i64, Custom);
645   setOperationAction(ISD::SMULO, MVT::i32, Custom);
646   setOperationAction(ISD::SMULO, MVT::i64, Custom);
647   setOperationAction(ISD::UMULO, MVT::i32, Custom);
648   setOperationAction(ISD::UMULO, MVT::i64, Custom);
649 
650   setOperationAction(ISD::UADDO_CARRY, MVT::i32, Custom);
651   setOperationAction(ISD::UADDO_CARRY, MVT::i64, Custom);
652   setOperationAction(ISD::USUBO_CARRY, MVT::i32, Custom);
653   setOperationAction(ISD::USUBO_CARRY, MVT::i64, Custom);
654   setOperationAction(ISD::SADDO_CARRY, MVT::i32, Custom);
655   setOperationAction(ISD::SADDO_CARRY, MVT::i64, Custom);
656   setOperationAction(ISD::SSUBO_CARRY, MVT::i32, Custom);
657   setOperationAction(ISD::SSUBO_CARRY, MVT::i64, Custom);
658 
659   setOperationAction(ISD::FSIN, MVT::f32, Expand);
660   setOperationAction(ISD::FSIN, MVT::f64, Expand);
661   setOperationAction(ISD::FCOS, MVT::f32, Expand);
662   setOperationAction(ISD::FCOS, MVT::f64, Expand);
663   setOperationAction(ISD::FPOW, MVT::f32, Expand);
664   setOperationAction(ISD::FPOW, MVT::f64, Expand);
665   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
666   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
667   if (Subtarget->hasFullFP16())
668     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
669   else
670     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
671 
672   for (auto Op : {ISD::FREM,        ISD::FPOW,         ISD::FPOWI,
673                   ISD::FCOS,        ISD::FSIN,         ISD::FSINCOS,
674                   ISD::FEXP,        ISD::FEXP2,        ISD::FLOG,
675                   ISD::FLOG2,       ISD::FLOG10,       ISD::STRICT_FREM,
676                   ISD::STRICT_FPOW, ISD::STRICT_FPOWI, ISD::STRICT_FCOS,
677                   ISD::STRICT_FSIN, ISD::STRICT_FEXP,  ISD::STRICT_FEXP2,
678                   ISD::STRICT_FLOG, ISD::STRICT_FLOG2, ISD::STRICT_FLOG10}) {
679     setOperationAction(Op, MVT::f16, Promote);
680     setOperationAction(Op, MVT::v4f16, Expand);
681     setOperationAction(Op, MVT::v8f16, Expand);
682   }
683 
684   if (!Subtarget->hasFullFP16()) {
685     for (auto Op :
686          {ISD::SETCC,          ISD::SELECT_CC,
687           ISD::BR_CC,          ISD::FADD,           ISD::FSUB,
688           ISD::FMUL,           ISD::FDIV,           ISD::FMA,
689           ISD::FNEG,           ISD::FABS,           ISD::FCEIL,
690           ISD::FSQRT,          ISD::FFLOOR,         ISD::FNEARBYINT,
691           ISD::FRINT,          ISD::FROUND,         ISD::FROUNDEVEN,
692           ISD::FTRUNC,         ISD::FMINNUM,        ISD::FMAXNUM,
693           ISD::FMINIMUM,       ISD::FMAXIMUM,       ISD::STRICT_FADD,
694           ISD::STRICT_FSUB,    ISD::STRICT_FMUL,    ISD::STRICT_FDIV,
695           ISD::STRICT_FMA,     ISD::STRICT_FCEIL,   ISD::STRICT_FFLOOR,
696           ISD::STRICT_FSQRT,   ISD::STRICT_FRINT,   ISD::STRICT_FNEARBYINT,
697           ISD::STRICT_FROUND,  ISD::STRICT_FTRUNC,  ISD::STRICT_FROUNDEVEN,
698           ISD::STRICT_FMINNUM, ISD::STRICT_FMAXNUM, ISD::STRICT_FMINIMUM,
699           ISD::STRICT_FMAXIMUM})
700       setOperationAction(Op, MVT::f16, Promote);
701 
702     // Round-to-integer need custom lowering for fp16, as Promote doesn't work
703     // because the result type is integer.
704     for (auto Op : {ISD::STRICT_LROUND, ISD::STRICT_LLROUND, ISD::STRICT_LRINT,
705                     ISD::STRICT_LLRINT})
706       setOperationAction(Op, MVT::f16, Custom);
707 
708     // promote v4f16 to v4f32 when that is known to be safe.
709     setOperationPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
710     setOperationPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
711     setOperationPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
712     setOperationPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
713 
714     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
715     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
716     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
717     setOperationAction(ISD::FROUNDEVEN,  MVT::v4f16, Expand);
718     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
719     setOperationAction(ISD::SETCC,       MVT::v4f16, Custom);
720     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
721     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
722     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
723     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
724     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
725     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
726     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
727     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
728     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
729     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
730 
731     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
732     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
733     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
734     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
735     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
736     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
737     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
738     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
739     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
740     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
741     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
742     setOperationAction(ISD::FROUNDEVEN,  MVT::v8f16, Expand);
743     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
744     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
745     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
746     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
747     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
748     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
749     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
750     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
751     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
752   }
753 
754   // AArch64 has implementations of a lot of rounding-like FP operations.
755   for (auto Op :
756        {ISD::FFLOOR,          ISD::FNEARBYINT,      ISD::FCEIL,
757         ISD::FRINT,           ISD::FTRUNC,          ISD::FROUND,
758         ISD::FROUNDEVEN,      ISD::FMINNUM,         ISD::FMAXNUM,
759         ISD::FMINIMUM,        ISD::FMAXIMUM,        ISD::LROUND,
760         ISD::LLROUND,         ISD::LRINT,           ISD::LLRINT,
761         ISD::STRICT_FFLOOR,   ISD::STRICT_FCEIL,    ISD::STRICT_FNEARBYINT,
762         ISD::STRICT_FRINT,    ISD::STRICT_FTRUNC,   ISD::STRICT_FROUNDEVEN,
763         ISD::STRICT_FROUND,   ISD::STRICT_FMINNUM,  ISD::STRICT_FMAXNUM,
764         ISD::STRICT_FMINIMUM, ISD::STRICT_FMAXIMUM, ISD::STRICT_LROUND,
765         ISD::STRICT_LLROUND,  ISD::STRICT_LRINT,    ISD::STRICT_LLRINT}) {
766     for (MVT Ty : {MVT::f32, MVT::f64})
767       setOperationAction(Op, Ty, Legal);
768     if (Subtarget->hasFullFP16())
769       setOperationAction(Op, MVT::f16, Legal);
770   }
771 
772   // Basic strict FP operations are legal
773   for (auto Op : {ISD::STRICT_FADD, ISD::STRICT_FSUB, ISD::STRICT_FMUL,
774                   ISD::STRICT_FDIV, ISD::STRICT_FMA, ISD::STRICT_FSQRT}) {
775     for (MVT Ty : {MVT::f32, MVT::f64})
776       setOperationAction(Op, Ty, Legal);
777     if (Subtarget->hasFullFP16())
778       setOperationAction(Op, MVT::f16, Legal);
779   }
780 
781   // Strict conversion to a larger type is legal
782   for (auto VT : {MVT::f32, MVT::f64})
783     setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal);
784 
785   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
786 
787   setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom);
788   setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
789 
790   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
791   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
792   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
793   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
794   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
795 
796   // Generate outline atomics library calls only if LSE was not specified for
797   // subtarget
798   if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
799     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
800     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
801     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
802     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
803     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
804     setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
805     setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
806     setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
807     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
808     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
809     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
810     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
811     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
812     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
813     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
814     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
815     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
816     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
817     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
818     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
819     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
820     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
821     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
822     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
823     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
824 #define LCALLNAMES(A, B, N)                                                    \
825   setLibcallName(A##N##_RELAX, #B #N "_relax");                                \
826   setLibcallName(A##N##_ACQ, #B #N "_acq");                                    \
827   setLibcallName(A##N##_REL, #B #N "_rel");                                    \
828   setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
829 #define LCALLNAME4(A, B)                                                       \
830   LCALLNAMES(A, B, 1)                                                          \
831   LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
832 #define LCALLNAME5(A, B)                                                       \
833   LCALLNAMES(A, B, 1)                                                          \
834   LCALLNAMES(A, B, 2)                                                          \
835   LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
836     LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
837     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
838     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
839     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
840     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
841     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
842 #undef LCALLNAMES
843 #undef LCALLNAME4
844 #undef LCALLNAME5
845   }
846 
847   if (Subtarget->hasLSE128()) {
848     // Custom lowering because i128 is not legal. Must be replaced by 2x64
849     // values. ATOMIC_LOAD_AND also needs op legalisation to emit LDCLRP.
850     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i128, Custom);
851     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i128, Custom);
852     setOperationAction(ISD::ATOMIC_SWAP, MVT::i128, Custom);
853   }
854 
855   // 128-bit loads and stores can be done without expanding
856   setOperationAction(ISD::LOAD, MVT::i128, Custom);
857   setOperationAction(ISD::STORE, MVT::i128, Custom);
858 
859   // Aligned 128-bit loads and stores are single-copy atomic according to the
860   // v8.4a spec. LRCPC3 introduces 128-bit STILP/LDIAPP but still requires LSE2.
861   if (Subtarget->hasLSE2()) {
862     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
863     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
864   }
865 
866   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
867   // custom lowering, as there are no un-paired non-temporal stores and
868   // legalization will break up 256 bit inputs.
869   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
870   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
871   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
872   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
873   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
874   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
875   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
876 
877   // 256 bit non-temporal loads can be lowered to LDNP. This is done using
878   // custom lowering, as there are no un-paired non-temporal loads legalization
879   // will break up 256 bit inputs.
880   setOperationAction(ISD::LOAD, MVT::v32i8, Custom);
881   setOperationAction(ISD::LOAD, MVT::v16i16, Custom);
882   setOperationAction(ISD::LOAD, MVT::v16f16, Custom);
883   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
884   setOperationAction(ISD::LOAD, MVT::v8f32, Custom);
885   setOperationAction(ISD::LOAD, MVT::v4f64, Custom);
886   setOperationAction(ISD::LOAD, MVT::v4i64, Custom);
887 
888   // Lower READCYCLECOUNTER using an mrs from CNTVCT_EL0.
889   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
890 
891   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
892       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
893     // Issue __sincos_stret if available.
894     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
895     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
896   } else {
897     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
898     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
899   }
900 
901   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
902     // MSVCRT doesn't have powi; fall back to pow
903     setLibcallName(RTLIB::POWI_F32, nullptr);
904     setLibcallName(RTLIB::POWI_F64, nullptr);
905   }
906 
907   // Make floating-point constants legal for the large code model, so they don't
908   // become loads from the constant pool.
909   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
910     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
911     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
912   }
913 
914   // AArch64 does not have floating-point extending loads, i1 sign-extending
915   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
916   for (MVT VT : MVT::fp_valuetypes()) {
917     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
918     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
919     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
920     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
921   }
922   for (MVT VT : MVT::integer_valuetypes())
923     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
924 
925   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
926   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
927   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
928   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
929   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
930   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
931   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
932 
933   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
934   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
935   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
936 
937   // Indexed loads and stores are supported.
938   for (unsigned im = (unsigned)ISD::PRE_INC;
939        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
940     setIndexedLoadAction(im, MVT::i8, Legal);
941     setIndexedLoadAction(im, MVT::i16, Legal);
942     setIndexedLoadAction(im, MVT::i32, Legal);
943     setIndexedLoadAction(im, MVT::i64, Legal);
944     setIndexedLoadAction(im, MVT::f64, Legal);
945     setIndexedLoadAction(im, MVT::f32, Legal);
946     setIndexedLoadAction(im, MVT::f16, Legal);
947     setIndexedLoadAction(im, MVT::bf16, Legal);
948     setIndexedStoreAction(im, MVT::i8, Legal);
949     setIndexedStoreAction(im, MVT::i16, Legal);
950     setIndexedStoreAction(im, MVT::i32, Legal);
951     setIndexedStoreAction(im, MVT::i64, Legal);
952     setIndexedStoreAction(im, MVT::f64, Legal);
953     setIndexedStoreAction(im, MVT::f32, Legal);
954     setIndexedStoreAction(im, MVT::f16, Legal);
955     setIndexedStoreAction(im, MVT::bf16, Legal);
956   }
957 
958   // Trap.
959   setOperationAction(ISD::TRAP, MVT::Other, Legal);
960   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
961   setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
962 
963   // We combine OR nodes for bitfield operations.
964   setTargetDAGCombine(ISD::OR);
965   // Try to create BICs for vector ANDs.
966   setTargetDAGCombine(ISD::AND);
967 
968   // Vector add and sub nodes may conceal a high-half opportunity.
969   // Also, try to fold ADD into CSINC/CSINV..
970   setTargetDAGCombine({ISD::ADD, ISD::ABS, ISD::SUB, ISD::XOR, ISD::SINT_TO_FP,
971                        ISD::UINT_TO_FP});
972 
973   setTargetDAGCombine({ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::FP_TO_SINT_SAT,
974                        ISD::FP_TO_UINT_SAT, ISD::FADD, ISD::FDIV});
975 
976   // Try and combine setcc with csel
977   setTargetDAGCombine(ISD::SETCC);
978 
979   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
980 
981   setTargetDAGCombine({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND,
982                        ISD::VECTOR_SPLICE, ISD::SIGN_EXTEND_INREG,
983                        ISD::CONCAT_VECTORS, ISD::EXTRACT_SUBVECTOR,
984                        ISD::INSERT_SUBVECTOR, ISD::STORE, ISD::BUILD_VECTOR});
985   setTargetDAGCombine(ISD::TRUNCATE);
986   setTargetDAGCombine(ISD::LOAD);
987 
988   setTargetDAGCombine(ISD::MSTORE);
989 
990   setTargetDAGCombine(ISD::MUL);
991 
992   setTargetDAGCombine({ISD::SELECT, ISD::VSELECT});
993 
994   setTargetDAGCombine({ISD::INTRINSIC_VOID, ISD::INTRINSIC_W_CHAIN,
995                        ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
996                        ISD::VECREDUCE_ADD, ISD::STEP_VECTOR});
997 
998   setTargetDAGCombine({ISD::MGATHER, ISD::MSCATTER});
999 
1000   setTargetDAGCombine(ISD::FP_EXTEND);
1001 
1002   setTargetDAGCombine(ISD::GlobalAddress);
1003 
1004   setTargetDAGCombine(ISD::CTLZ);
1005 
1006   setTargetDAGCombine(ISD::VECREDUCE_AND);
1007   setTargetDAGCombine(ISD::VECREDUCE_OR);
1008   setTargetDAGCombine(ISD::VECREDUCE_XOR);
1009 
1010   // In case of strict alignment, avoid an excessive number of byte wide stores.
1011   MaxStoresPerMemsetOptSize = 8;
1012   MaxStoresPerMemset =
1013       Subtarget->requiresStrictAlign() ? MaxStoresPerMemsetOptSize : 32;
1014 
1015   MaxGluedStoresPerMemcpy = 4;
1016   MaxStoresPerMemcpyOptSize = 4;
1017   MaxStoresPerMemcpy =
1018       Subtarget->requiresStrictAlign() ? MaxStoresPerMemcpyOptSize : 16;
1019 
1020   MaxStoresPerMemmoveOptSize = 4;
1021   MaxStoresPerMemmove = 4;
1022 
1023   MaxLoadsPerMemcmpOptSize = 4;
1024   MaxLoadsPerMemcmp =
1025       Subtarget->requiresStrictAlign() ? MaxLoadsPerMemcmpOptSize : 8;
1026 
1027   setStackPointerRegisterToSaveRestore(AArch64::SP);
1028 
1029   setSchedulingPreference(Sched::Hybrid);
1030 
1031   EnableExtLdPromotion = true;
1032 
1033   // Set required alignment.
1034   setMinFunctionAlignment(Align(4));
1035   // Set preferred alignments.
1036 
1037   // Don't align loops on Windows. The SEH unwind info generation needs to
1038   // know the exact length of functions before the alignments have been
1039   // expanded.
1040   if (!Subtarget->isTargetWindows())
1041     setPrefLoopAlignment(STI.getPrefLoopAlignment());
1042   setMaxBytesForAlignment(STI.getMaxBytesForLoopAlignment());
1043   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
1044 
1045   // Only change the limit for entries in a jump table if specified by
1046   // the sub target, but not at the command line.
1047   unsigned MaxJT = STI.getMaximumJumpTableSize();
1048   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
1049     setMaximumJumpTableSize(MaxJT);
1050 
1051   setHasExtractBitsInsn(true);
1052 
1053   setMaxDivRemBitWidthSupported(128);
1054 
1055   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1056 
1057   if (Subtarget->hasNEON()) {
1058     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
1059     // silliness like this:
1060     for (auto Op :
1061          {ISD::SELECT,         ISD::SELECT_CC,
1062           ISD::BR_CC,          ISD::FADD,           ISD::FSUB,
1063           ISD::FMUL,           ISD::FDIV,           ISD::FMA,
1064           ISD::FNEG,           ISD::FABS,           ISD::FCEIL,
1065           ISD::FSQRT,          ISD::FFLOOR,         ISD::FNEARBYINT,
1066           ISD::FRINT,          ISD::FROUND,         ISD::FROUNDEVEN,
1067           ISD::FTRUNC,         ISD::FMINNUM,        ISD::FMAXNUM,
1068           ISD::FMINIMUM,       ISD::FMAXIMUM,       ISD::STRICT_FADD,
1069           ISD::STRICT_FSUB,    ISD::STRICT_FMUL,    ISD::STRICT_FDIV,
1070           ISD::STRICT_FMA,     ISD::STRICT_FCEIL,   ISD::STRICT_FFLOOR,
1071           ISD::STRICT_FSQRT,   ISD::STRICT_FRINT,   ISD::STRICT_FNEARBYINT,
1072           ISD::STRICT_FROUND,  ISD::STRICT_FTRUNC,  ISD::STRICT_FROUNDEVEN,
1073           ISD::STRICT_FMINNUM, ISD::STRICT_FMAXNUM, ISD::STRICT_FMINIMUM,
1074           ISD::STRICT_FMAXIMUM})
1075       setOperationAction(Op, MVT::v1f64, Expand);
1076 
1077     for (auto Op :
1078          {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP,
1079           ISD::FP_ROUND, ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT, ISD::MUL,
1080           ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT,
1081           ISD::STRICT_SINT_TO_FP, ISD::STRICT_UINT_TO_FP, ISD::STRICT_FP_ROUND})
1082       setOperationAction(Op, MVT::v1i64, Expand);
1083 
1084     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
1085     // elements smaller than i32, so promote the input to i32 first.
1086     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
1087     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
1088 
1089     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
1090     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
1091     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
1092     for (auto Op : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
1093                     ISD::STRICT_UINT_TO_FP})
1094       for (auto VT : {MVT::v2i32, MVT::v2i64, MVT::v4i32})
1095         setOperationAction(Op, VT, Custom);
1096 
1097     if (Subtarget->hasFullFP16()) {
1098       setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
1099       setOperationAction(ISD::ConstantFP, MVT::bf16, Legal);
1100 
1101       setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Custom);
1102       setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1103       setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Custom);
1104       setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1105       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1106       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1107       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
1108       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1109     } else {
1110       // when AArch64 doesn't have fullfp16 support, promote the input
1111       // to i32 first.
1112       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
1113       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
1114       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v16i8, MVT::v16i32);
1115       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v16i8, MVT::v16i32);
1116       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
1117       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
1118       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
1119       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
1120     }
1121 
1122     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
1123     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
1124     setOperationAction(ISD::BITREVERSE, MVT::v8i8, Legal);
1125     setOperationAction(ISD::BITREVERSE, MVT::v16i8, Legal);
1126     setOperationAction(ISD::BITREVERSE, MVT::v2i32, Custom);
1127     setOperationAction(ISD::BITREVERSE, MVT::v4i32, Custom);
1128     setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1129     setOperationAction(ISD::BITREVERSE, MVT::v2i64, Custom);
1130     for (auto VT : {MVT::v1i64, MVT::v2i64}) {
1131       setOperationAction(ISD::UMAX, VT, Custom);
1132       setOperationAction(ISD::SMAX, VT, Custom);
1133       setOperationAction(ISD::UMIN, VT, Custom);
1134       setOperationAction(ISD::SMIN, VT, Custom);
1135     }
1136 
1137     // Custom handling for some quad-vector types to detect MULL.
1138     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
1139     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1140     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1141     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
1142     setOperationAction(ISD::MUL, MVT::v2i32, Custom);
1143     setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1144 
1145     // Saturates
1146     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1147                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1148       setOperationAction(ISD::SADDSAT, VT, Legal);
1149       setOperationAction(ISD::UADDSAT, VT, Legal);
1150       setOperationAction(ISD::SSUBSAT, VT, Legal);
1151       setOperationAction(ISD::USUBSAT, VT, Legal);
1152     }
1153 
1154     for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
1155                    MVT::v4i32}) {
1156       setOperationAction(ISD::AVGFLOORS, VT, Legal);
1157       setOperationAction(ISD::AVGFLOORU, VT, Legal);
1158       setOperationAction(ISD::AVGCEILS, VT, Legal);
1159       setOperationAction(ISD::AVGCEILU, VT, Legal);
1160       setOperationAction(ISD::ABDS, VT, Legal);
1161       setOperationAction(ISD::ABDU, VT, Legal);
1162     }
1163 
1164     // Vector reductions
1165     for (MVT VT : { MVT::v4f16, MVT::v2f32,
1166                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1167       if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) {
1168         setOperationAction(ISD::VECREDUCE_FMAX, VT, Legal);
1169         setOperationAction(ISD::VECREDUCE_FMIN, VT, Legal);
1170         setOperationAction(ISD::VECREDUCE_FMAXIMUM, VT, Legal);
1171         setOperationAction(ISD::VECREDUCE_FMINIMUM, VT, Legal);
1172 
1173         setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
1174       }
1175     }
1176     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1177                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1178       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1179       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1180       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1181       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1182       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1183       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1184       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1185       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1186     }
1187     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
1188     setOperationAction(ISD::VECREDUCE_AND, MVT::v2i64, Custom);
1189     setOperationAction(ISD::VECREDUCE_OR, MVT::v2i64, Custom);
1190     setOperationAction(ISD::VECREDUCE_XOR, MVT::v2i64, Custom);
1191 
1192     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
1193     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
1194     // Likewise, narrowing and extending vector loads/stores aren't handled
1195     // directly.
1196     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1197       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
1198 
1199       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
1200         setOperationAction(ISD::MULHS, VT, Legal);
1201         setOperationAction(ISD::MULHU, VT, Legal);
1202       } else {
1203         setOperationAction(ISD::MULHS, VT, Expand);
1204         setOperationAction(ISD::MULHU, VT, Expand);
1205       }
1206       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1207       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1208 
1209       setOperationAction(ISD::BSWAP, VT, Expand);
1210       setOperationAction(ISD::CTTZ, VT, Expand);
1211 
1212       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1213         setTruncStoreAction(VT, InnerVT, Expand);
1214         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1215         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1216         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1217       }
1218     }
1219 
1220     // AArch64 has implementations of a lot of rounding-like FP operations.
1221     for (auto Op :
1222          {ISD::FFLOOR, ISD::FNEARBYINT, ISD::FCEIL, ISD::FRINT, ISD::FTRUNC,
1223           ISD::FROUND, ISD::FROUNDEVEN, ISD::STRICT_FFLOOR,
1224           ISD::STRICT_FNEARBYINT, ISD::STRICT_FCEIL, ISD::STRICT_FRINT,
1225           ISD::STRICT_FTRUNC, ISD::STRICT_FROUND, ISD::STRICT_FROUNDEVEN}) {
1226       for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64})
1227         setOperationAction(Op, Ty, Legal);
1228       if (Subtarget->hasFullFP16())
1229         for (MVT Ty : {MVT::v4f16, MVT::v8f16})
1230           setOperationAction(Op, Ty, Legal);
1231     }
1232 
1233     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
1234 
1235     setOperationAction(ISD::BITCAST, MVT::i2, Custom);
1236     setOperationAction(ISD::BITCAST, MVT::i4, Custom);
1237     setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1238     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1239 
1240     setOperationAction(ISD::BITCAST, MVT::v2i8, Custom);
1241     setOperationAction(ISD::BITCAST, MVT::v2i16, Custom);
1242     setOperationAction(ISD::BITCAST, MVT::v4i8, Custom);
1243 
1244     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i16, MVT::v4i8, Custom);
1245     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1246     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1247     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i32, MVT::v4i8, Custom);
1248     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1249     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1250 
1251     // ADDP custom lowering
1252     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1253       setOperationAction(ISD::ADD, VT, Custom);
1254     // FADDP custom lowering
1255     for (MVT VT : { MVT::v16f16, MVT::v8f32, MVT::v4f64 })
1256       setOperationAction(ISD::FADD, VT, Custom);
1257   }
1258 
1259   if (Subtarget->hasSME()) {
1260     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1261   }
1262 
1263   // FIXME: Move lowering for more nodes here if those are common between
1264   // SVE and SME.
1265   if (Subtarget->hasSVEorSME()) {
1266     for (auto VT :
1267          {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1, MVT::nxv1i1}) {
1268       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1269       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1270       setOperationAction(ISD::VECTOR_DEINTERLEAVE, VT, Custom);
1271       setOperationAction(ISD::VECTOR_INTERLEAVE, VT, Custom);
1272     }
1273   }
1274 
1275   if (Subtarget->hasSVE()) {
1276     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
1277       setOperationAction(ISD::BITREVERSE, VT, Custom);
1278       setOperationAction(ISD::BSWAP, VT, Custom);
1279       setOperationAction(ISD::CTLZ, VT, Custom);
1280       setOperationAction(ISD::CTPOP, VT, Custom);
1281       setOperationAction(ISD::CTTZ, VT, Custom);
1282       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1283       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1284       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1285       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1286       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1287       setOperationAction(ISD::MGATHER, VT, Custom);
1288       setOperationAction(ISD::MSCATTER, VT, Custom);
1289       setOperationAction(ISD::MLOAD, VT, Custom);
1290       setOperationAction(ISD::MUL, VT, Custom);
1291       setOperationAction(ISD::MULHS, VT, Custom);
1292       setOperationAction(ISD::MULHU, VT, Custom);
1293       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
1294       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1295       setOperationAction(ISD::SELECT, VT, Custom);
1296       setOperationAction(ISD::SETCC, VT, Custom);
1297       setOperationAction(ISD::SDIV, VT, Custom);
1298       setOperationAction(ISD::UDIV, VT, Custom);
1299       setOperationAction(ISD::SMIN, VT, Custom);
1300       setOperationAction(ISD::UMIN, VT, Custom);
1301       setOperationAction(ISD::SMAX, VT, Custom);
1302       setOperationAction(ISD::UMAX, VT, Custom);
1303       setOperationAction(ISD::SHL, VT, Custom);
1304       setOperationAction(ISD::SRL, VT, Custom);
1305       setOperationAction(ISD::SRA, VT, Custom);
1306       setOperationAction(ISD::ABS, VT, Custom);
1307       setOperationAction(ISD::ABDS, VT, Custom);
1308       setOperationAction(ISD::ABDU, VT, Custom);
1309       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1310       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1311       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1312       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1313       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1314       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1315       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1316       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1317       setOperationAction(ISD::VECTOR_DEINTERLEAVE, VT, Custom);
1318       setOperationAction(ISD::VECTOR_INTERLEAVE, VT, Custom);
1319 
1320       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1321       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1322       setOperationAction(ISD::SELECT_CC, VT, Expand);
1323       setOperationAction(ISD::ROTL, VT, Expand);
1324       setOperationAction(ISD::ROTR, VT, Expand);
1325 
1326       setOperationAction(ISD::SADDSAT, VT, Legal);
1327       setOperationAction(ISD::UADDSAT, VT, Legal);
1328       setOperationAction(ISD::SSUBSAT, VT, Legal);
1329       setOperationAction(ISD::USUBSAT, VT, Legal);
1330       setOperationAction(ISD::UREM, VT, Expand);
1331       setOperationAction(ISD::SREM, VT, Expand);
1332       setOperationAction(ISD::SDIVREM, VT, Expand);
1333       setOperationAction(ISD::UDIVREM, VT, Expand);
1334 
1335       setOperationAction(ISD::AVGFLOORS, VT, Custom);
1336       setOperationAction(ISD::AVGFLOORU, VT, Custom);
1337       setOperationAction(ISD::AVGCEILS, VT, Custom);
1338       setOperationAction(ISD::AVGCEILU, VT, Custom);
1339     }
1340 
1341     // Illegal unpacked integer vector types.
1342     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1343       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1344       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1345     }
1346 
1347     // Legalize unpacked bitcasts to REINTERPRET_CAST.
1348     for (auto VT : {MVT::nxv2i16, MVT::nxv4i16, MVT::nxv2i32, MVT::nxv2bf16,
1349                     MVT::nxv4bf16, MVT::nxv2f16, MVT::nxv4f16, MVT::nxv2f32})
1350       setOperationAction(ISD::BITCAST, VT, Custom);
1351 
1352     for (auto VT :
1353          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
1354            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
1355       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
1356 
1357     for (auto VT :
1358          {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1, MVT::nxv1i1}) {
1359       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1360       setOperationAction(ISD::SELECT, VT, Custom);
1361       setOperationAction(ISD::SETCC, VT, Custom);
1362       setOperationAction(ISD::TRUNCATE, VT, Custom);
1363       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1364       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1365       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1366 
1367       setOperationAction(ISD::SELECT_CC, VT, Expand);
1368       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1369       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1370 
1371       // There are no legal MVT::nxv16f## based types.
1372       if (VT != MVT::nxv16i1) {
1373         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1374         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1375       }
1376     }
1377 
1378     // NEON doesn't support masked loads/stores/gathers/scatters, but SVE does
1379     for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v1f64,
1380                     MVT::v2f64, MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1381                     MVT::v2i32, MVT::v4i32, MVT::v1i64, MVT::v2i64}) {
1382       setOperationAction(ISD::MLOAD, VT, Custom);
1383       setOperationAction(ISD::MSTORE, VT, Custom);
1384       setOperationAction(ISD::MGATHER, VT, Custom);
1385       setOperationAction(ISD::MSCATTER, VT, Custom);
1386     }
1387 
1388     // Firstly, exclude all scalable vector extending loads/truncating stores,
1389     // include both integer and floating scalable vector.
1390     for (MVT VT : MVT::scalable_vector_valuetypes()) {
1391       for (MVT InnerVT : MVT::scalable_vector_valuetypes()) {
1392         setTruncStoreAction(VT, InnerVT, Expand);
1393         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1394         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1395         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1396       }
1397     }
1398 
1399     // Then, selectively enable those which we directly support.
1400     setTruncStoreAction(MVT::nxv2i64, MVT::nxv2i8, Legal);
1401     setTruncStoreAction(MVT::nxv2i64, MVT::nxv2i16, Legal);
1402     setTruncStoreAction(MVT::nxv2i64, MVT::nxv2i32, Legal);
1403     setTruncStoreAction(MVT::nxv4i32, MVT::nxv4i8, Legal);
1404     setTruncStoreAction(MVT::nxv4i32, MVT::nxv4i16, Legal);
1405     setTruncStoreAction(MVT::nxv8i16, MVT::nxv8i8, Legal);
1406     for (auto Op : {ISD::ZEXTLOAD, ISD::SEXTLOAD, ISD::EXTLOAD}) {
1407       setLoadExtAction(Op, MVT::nxv2i64, MVT::nxv2i8, Legal);
1408       setLoadExtAction(Op, MVT::nxv2i64, MVT::nxv2i16, Legal);
1409       setLoadExtAction(Op, MVT::nxv2i64, MVT::nxv2i32, Legal);
1410       setLoadExtAction(Op, MVT::nxv4i32, MVT::nxv4i8, Legal);
1411       setLoadExtAction(Op, MVT::nxv4i32, MVT::nxv4i16, Legal);
1412       setLoadExtAction(Op, MVT::nxv8i16, MVT::nxv8i8, Legal);
1413     }
1414 
1415     // SVE supports truncating stores of 64 and 128-bit vectors
1416     setTruncStoreAction(MVT::v2i64, MVT::v2i8, Custom);
1417     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Custom);
1418     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Custom);
1419     setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
1420     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
1421 
1422     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1423                     MVT::nxv4f32, MVT::nxv2f64}) {
1424       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1425       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1426       setOperationAction(ISD::MGATHER, VT, Custom);
1427       setOperationAction(ISD::MSCATTER, VT, Custom);
1428       setOperationAction(ISD::MLOAD, VT, Custom);
1429       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
1430       setOperationAction(ISD::SELECT, VT, Custom);
1431       setOperationAction(ISD::SETCC, VT, Custom);
1432       setOperationAction(ISD::FADD, VT, Custom);
1433       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1434       setOperationAction(ISD::FDIV, VT, Custom);
1435       setOperationAction(ISD::FMA, VT, Custom);
1436       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1437       setOperationAction(ISD::FMAXNUM, VT, Custom);
1438       setOperationAction(ISD::FMINIMUM, VT, Custom);
1439       setOperationAction(ISD::FMINNUM, VT, Custom);
1440       setOperationAction(ISD::FMUL, VT, Custom);
1441       setOperationAction(ISD::FNEG, VT, Custom);
1442       setOperationAction(ISD::FSUB, VT, Custom);
1443       setOperationAction(ISD::FCEIL, VT, Custom);
1444       setOperationAction(ISD::FFLOOR, VT, Custom);
1445       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1446       setOperationAction(ISD::FRINT, VT, Custom);
1447       setOperationAction(ISD::FROUND, VT, Custom);
1448       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1449       setOperationAction(ISD::FTRUNC, VT, Custom);
1450       setOperationAction(ISD::FSQRT, VT, Custom);
1451       setOperationAction(ISD::FABS, VT, Custom);
1452       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1453       setOperationAction(ISD::FP_ROUND, VT, Custom);
1454       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1455       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1456       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1457       setOperationAction(ISD::VECREDUCE_FMAXIMUM, VT, Custom);
1458       setOperationAction(ISD::VECREDUCE_FMINIMUM, VT, Custom);
1459       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1460       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1461       setOperationAction(ISD::VECTOR_DEINTERLEAVE, VT, Custom);
1462       setOperationAction(ISD::VECTOR_INTERLEAVE, VT, Custom);
1463 
1464       setOperationAction(ISD::SELECT_CC, VT, Expand);
1465       setOperationAction(ISD::FREM, VT, Expand);
1466       setOperationAction(ISD::FPOW, VT, Expand);
1467       setOperationAction(ISD::FPOWI, VT, Expand);
1468       setOperationAction(ISD::FCOS, VT, Expand);
1469       setOperationAction(ISD::FSIN, VT, Expand);
1470       setOperationAction(ISD::FSINCOS, VT, Expand);
1471       setOperationAction(ISD::FEXP, VT, Expand);
1472       setOperationAction(ISD::FEXP2, VT, Expand);
1473       setOperationAction(ISD::FLOG, VT, Expand);
1474       setOperationAction(ISD::FLOG2, VT, Expand);
1475       setOperationAction(ISD::FLOG10, VT, Expand);
1476 
1477       setCondCodeAction(ISD::SETO, VT, Expand);
1478       setCondCodeAction(ISD::SETOLT, VT, Expand);
1479       setCondCodeAction(ISD::SETLT, VT, Expand);
1480       setCondCodeAction(ISD::SETOLE, VT, Expand);
1481       setCondCodeAction(ISD::SETLE, VT, Expand);
1482       setCondCodeAction(ISD::SETULT, VT, Expand);
1483       setCondCodeAction(ISD::SETULE, VT, Expand);
1484       setCondCodeAction(ISD::SETUGE, VT, Expand);
1485       setCondCodeAction(ISD::SETUGT, VT, Expand);
1486       setCondCodeAction(ISD::SETUEQ, VT, Expand);
1487       setCondCodeAction(ISD::SETONE, VT, Expand);
1488     }
1489 
1490     for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
1491       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1492       setOperationAction(ISD::MGATHER, VT, Custom);
1493       setOperationAction(ISD::MSCATTER, VT, Custom);
1494       setOperationAction(ISD::MLOAD, VT, Custom);
1495       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1496       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
1497     }
1498 
1499     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1500     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1501 
1502     // NEON doesn't support integer divides, but SVE does
1503     for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, MVT::v2i32,
1504                     MVT::v4i32, MVT::v1i64, MVT::v2i64}) {
1505       setOperationAction(ISD::SDIV, VT, Custom);
1506       setOperationAction(ISD::UDIV, VT, Custom);
1507     }
1508 
1509     // NEON doesn't support 64-bit vector integer muls, but SVE does.
1510     setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1511     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1512 
1513     // NEON doesn't support across-vector reductions, but SVE does.
1514     for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v2f64})
1515       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1516 
1517     if (!Subtarget->isNeonAvailable()) {
1518       setTruncStoreAction(MVT::v2f32, MVT::v2f16, Custom);
1519       setTruncStoreAction(MVT::v4f32, MVT::v4f16, Custom);
1520       setTruncStoreAction(MVT::v8f32, MVT::v8f16, Custom);
1521       setTruncStoreAction(MVT::v1f64, MVT::v1f16, Custom);
1522       setTruncStoreAction(MVT::v2f64, MVT::v2f16, Custom);
1523       setTruncStoreAction(MVT::v4f64, MVT::v4f16, Custom);
1524       setTruncStoreAction(MVT::v1f64, MVT::v1f32, Custom);
1525       setTruncStoreAction(MVT::v2f64, MVT::v2f32, Custom);
1526       setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1527       for (MVT VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, MVT::v2i32,
1528                      MVT::v4i32, MVT::v1i64, MVT::v2i64})
1529         addTypeForFixedLengthSVE(VT, /*StreamingSVE=*/ true);
1530 
1531       for (MVT VT :
1532            {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v2f64})
1533         addTypeForFixedLengthSVE(VT, /*StreamingSVE=*/ true);
1534     }
1535 
1536     // NOTE: Currently this has to happen after computeRegisterProperties rather
1537     // than the preferred option of combining it with the addRegisterClass call.
1538     if (Subtarget->useSVEForFixedLengthVectors()) {
1539       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1540         if (useSVEForFixedLengthVectorVT(VT))
1541           addTypeForFixedLengthSVE(VT, /*StreamingSVE=*/ false);
1542       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1543         if (useSVEForFixedLengthVectorVT(VT))
1544           addTypeForFixedLengthSVE(VT, /*StreamingSVE=*/ false);
1545 
1546       // 64bit results can mean a bigger than NEON input.
1547       for (auto VT : {MVT::v8i8, MVT::v4i16})
1548         setOperationAction(ISD::TRUNCATE, VT, Custom);
1549       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1550 
1551       // 128bit results imply a bigger than NEON input.
1552       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1553         setOperationAction(ISD::TRUNCATE, VT, Custom);
1554       for (auto VT : {MVT::v8f16, MVT::v4f32})
1555         setOperationAction(ISD::FP_ROUND, VT, Custom);
1556 
1557       // These operations are not supported on NEON but SVE can do them.
1558       setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1559       setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
1560       setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1561       setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
1562       setOperationAction(ISD::MULHS, MVT::v1i64, Custom);
1563       setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
1564       setOperationAction(ISD::MULHU, MVT::v1i64, Custom);
1565       setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
1566       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1567       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1568       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1569       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1570       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1571       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1572       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1573       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1574       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1575       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1576       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1577       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1578 
1579       // Int operations with no NEON support.
1580       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1581                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1582         setOperationAction(ISD::BITREVERSE, VT, Custom);
1583         setOperationAction(ISD::CTTZ, VT, Custom);
1584         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1585         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1586         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1587         setOperationAction(ISD::MULHS, VT, Custom);
1588         setOperationAction(ISD::MULHU, VT, Custom);
1589       }
1590 
1591 
1592       // Use SVE for vectors with more than 2 elements.
1593       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1594         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1595     }
1596 
1597     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64);
1598     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32);
1599     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16);
1600     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8);
1601 
1602     setOperationAction(ISD::VSCALE, MVT::i32, Custom);
1603   }
1604 
1605   if (Subtarget->hasMOPS() && Subtarget->hasMTE()) {
1606     // Only required for llvm.aarch64.mops.memset.tag
1607     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
1608   }
1609 
1610   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1611 
1612   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1613 
1614   IsStrictFPEnabled = true;
1615 }
1616 
1617 void AArch64TargetLowering::addTypeForNEON(MVT VT) {
1618   assert(VT.isVector() && "VT should be a vector type");
1619 
1620   if (VT.isFloatingPoint()) {
1621     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1622     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1623     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1624   }
1625 
1626   // Mark vector float intrinsics as expand.
1627   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1628     setOperationAction(ISD::FSIN, VT, Expand);
1629     setOperationAction(ISD::FCOS, VT, Expand);
1630     setOperationAction(ISD::FPOW, VT, Expand);
1631     setOperationAction(ISD::FLOG, VT, Expand);
1632     setOperationAction(ISD::FLOG2, VT, Expand);
1633     setOperationAction(ISD::FLOG10, VT, Expand);
1634     setOperationAction(ISD::FEXP, VT, Expand);
1635     setOperationAction(ISD::FEXP2, VT, Expand);
1636   }
1637 
1638   // But we do support custom-lowering for FCOPYSIGN.
1639   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
1640       ((VT == MVT::v4f16 || VT == MVT::v8f16) && Subtarget->hasFullFP16()))
1641     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1642 
1643   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1644   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1645   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1646   setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1647   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1648   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1649   setOperationAction(ISD::SRA, VT, Custom);
1650   setOperationAction(ISD::SRL, VT, Custom);
1651   setOperationAction(ISD::SHL, VT, Custom);
1652   setOperationAction(ISD::OR, VT, Custom);
1653   setOperationAction(ISD::SETCC, VT, Custom);
1654   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1655 
1656   setOperationAction(ISD::SELECT, VT, Expand);
1657   setOperationAction(ISD::SELECT_CC, VT, Expand);
1658   setOperationAction(ISD::VSELECT, VT, Expand);
1659   for (MVT InnerVT : MVT::all_valuetypes())
1660     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1661 
1662   // CNT supports only B element sizes, then use UADDLP to widen.
1663   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1664     setOperationAction(ISD::CTPOP, VT, Custom);
1665 
1666   setOperationAction(ISD::UDIV, VT, Expand);
1667   setOperationAction(ISD::SDIV, VT, Expand);
1668   setOperationAction(ISD::UREM, VT, Expand);
1669   setOperationAction(ISD::SREM, VT, Expand);
1670   setOperationAction(ISD::FREM, VT, Expand);
1671 
1672   for (unsigned Opcode :
1673        {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::FP_TO_SINT_SAT,
1674         ISD::FP_TO_UINT_SAT, ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT})
1675     setOperationAction(Opcode, VT, Custom);
1676 
1677   if (!VT.isFloatingPoint())
1678     setOperationAction(ISD::ABS, VT, Legal);
1679 
1680   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1681   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1682     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1683       setOperationAction(Opcode, VT, Legal);
1684 
1685   // F[MIN|MAX][NUM|NAN] and simple strict operations are available for all FP
1686   // NEON types.
1687   if (VT.isFloatingPoint() &&
1688       VT.getVectorElementType() != MVT::bf16 &&
1689       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1690     for (unsigned Opcode :
1691          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM,
1692           ISD::STRICT_FMINIMUM, ISD::STRICT_FMAXIMUM, ISD::STRICT_FMINNUM,
1693           ISD::STRICT_FMAXNUM, ISD::STRICT_FADD, ISD::STRICT_FSUB,
1694           ISD::STRICT_FMUL, ISD::STRICT_FDIV, ISD::STRICT_FMA,
1695           ISD::STRICT_FSQRT})
1696       setOperationAction(Opcode, VT, Legal);
1697 
1698   // Strict fp extend and trunc are legal
1699   if (VT.isFloatingPoint() && VT.getScalarSizeInBits() != 16)
1700     setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal);
1701   if (VT.isFloatingPoint() && VT.getScalarSizeInBits() != 64)
1702     setOperationAction(ISD::STRICT_FP_ROUND, VT, Legal);
1703 
1704   // FIXME: We could potentially make use of the vector comparison instructions
1705   // for STRICT_FSETCC and STRICT_FSETCSS, but there's a number of
1706   // complications:
1707   //  * FCMPEQ/NE are quiet comparisons, the rest are signalling comparisons,
1708   //    so we would need to expand when the condition code doesn't match the
1709   //    kind of comparison.
1710   //  * Some kinds of comparison require more than one FCMXY instruction so
1711   //    would need to be expanded instead.
1712   //  * The lowering of the non-strict versions involves target-specific ISD
1713   //    nodes so we would likely need to add strict versions of all of them and
1714   //    handle them appropriately.
1715   setOperationAction(ISD::STRICT_FSETCC, VT, Expand);
1716   setOperationAction(ISD::STRICT_FSETCCS, VT, Expand);
1717 
1718   if (Subtarget->isLittleEndian()) {
1719     for (unsigned im = (unsigned)ISD::PRE_INC;
1720          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1721       setIndexedLoadAction(im, VT, Legal);
1722       setIndexedStoreAction(im, VT, Legal);
1723     }
1724   }
1725 
1726   if (Subtarget->hasD128()) {
1727     setOperationAction(ISD::READ_REGISTER, MVT::i128, Custom);
1728     setOperationAction(ISD::WRITE_REGISTER, MVT::i128, Custom);
1729   }
1730 }
1731 
1732 bool AArch64TargetLowering::shouldExpandGetActiveLaneMask(EVT ResVT,
1733                                                           EVT OpVT) const {
1734   // Only SVE has a 1:1 mapping from intrinsic -> instruction (whilelo).
1735   if (!Subtarget->hasSVE())
1736     return true;
1737 
1738   // We can only support legal predicate result types. We can use the SVE
1739   // whilelo instruction for generating fixed-width predicates too.
1740   if (ResVT != MVT::nxv2i1 && ResVT != MVT::nxv4i1 && ResVT != MVT::nxv8i1 &&
1741       ResVT != MVT::nxv16i1 && ResVT != MVT::v2i1 && ResVT != MVT::v4i1 &&
1742       ResVT != MVT::v8i1 && ResVT != MVT::v16i1)
1743     return true;
1744 
1745   // The whilelo instruction only works with i32 or i64 scalar inputs.
1746   if (OpVT != MVT::i32 && OpVT != MVT::i64)
1747     return true;
1748 
1749   return false;
1750 }
1751 
1752 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT,
1753                                                      bool StreamingSVE) {
1754   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1755 
1756   // By default everything must be expanded.
1757   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1758     setOperationAction(Op, VT, Expand);
1759 
1760   if (VT.isFloatingPoint()) {
1761     setCondCodeAction(ISD::SETO, VT, Expand);
1762     setCondCodeAction(ISD::SETOLT, VT, Expand);
1763     setCondCodeAction(ISD::SETOLE, VT, Expand);
1764     setCondCodeAction(ISD::SETULT, VT, Expand);
1765     setCondCodeAction(ISD::SETULE, VT, Expand);
1766     setCondCodeAction(ISD::SETUGE, VT, Expand);
1767     setCondCodeAction(ISD::SETUGT, VT, Expand);
1768     setCondCodeAction(ISD::SETUEQ, VT, Expand);
1769     setCondCodeAction(ISD::SETONE, VT, Expand);
1770   }
1771 
1772   // Mark integer truncating stores/extending loads as having custom lowering
1773   if (VT.isInteger()) {
1774     MVT InnerVT = VT.changeVectorElementType(MVT::i8);
1775     while (InnerVT != VT) {
1776       setTruncStoreAction(VT, InnerVT, Custom);
1777       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Custom);
1778       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Custom);
1779       InnerVT = InnerVT.changeVectorElementType(
1780           MVT::getIntegerVT(2 * InnerVT.getScalarSizeInBits()));
1781     }
1782   }
1783 
1784   // Mark floating-point truncating stores/extending loads as having custom
1785   // lowering
1786   if (VT.isFloatingPoint()) {
1787     MVT InnerVT = VT.changeVectorElementType(MVT::f16);
1788     while (InnerVT != VT) {
1789       setTruncStoreAction(VT, InnerVT, Custom);
1790       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Custom);
1791       InnerVT = InnerVT.changeVectorElementType(
1792           MVT::getFloatingPointVT(2 * InnerVT.getScalarSizeInBits()));
1793     }
1794   }
1795 
1796   // Lower fixed length vector operations to scalable equivalents.
1797   setOperationAction(ISD::ABS, VT, Custom);
1798   setOperationAction(ISD::ADD, VT, Custom);
1799   setOperationAction(ISD::AND, VT, Custom);
1800   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1801   setOperationAction(ISD::BITCAST, VT, StreamingSVE ? Legal : Custom);
1802   setOperationAction(ISD::BITREVERSE, VT, Custom);
1803   setOperationAction(ISD::BSWAP, VT, Custom);
1804   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1805   setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1806   setOperationAction(ISD::CTLZ, VT, Custom);
1807   setOperationAction(ISD::CTPOP, VT, Custom);
1808   setOperationAction(ISD::CTTZ, VT, Custom);
1809   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1810   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1811   setOperationAction(ISD::FABS, VT, Custom);
1812   setOperationAction(ISD::FADD, VT, Custom);
1813   setOperationAction(ISD::FCEIL, VT, Custom);
1814   setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1815   setOperationAction(ISD::FDIV, VT, Custom);
1816   setOperationAction(ISD::FFLOOR, VT, Custom);
1817   setOperationAction(ISD::FMA, VT, Custom);
1818   setOperationAction(ISD::FMAXIMUM, VT, Custom);
1819   setOperationAction(ISD::FMAXNUM, VT, Custom);
1820   setOperationAction(ISD::FMINIMUM, VT, Custom);
1821   setOperationAction(ISD::FMINNUM, VT, Custom);
1822   setOperationAction(ISD::FMUL, VT, Custom);
1823   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1824   setOperationAction(ISD::FNEG, VT, Custom);
1825   setOperationAction(ISD::FP_EXTEND, VT, Custom);
1826   setOperationAction(ISD::FP_ROUND, VT, Custom);
1827   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1828   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1829   setOperationAction(ISD::FRINT, VT, Custom);
1830   setOperationAction(ISD::FROUND, VT, Custom);
1831   setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1832   setOperationAction(ISD::FSQRT, VT, Custom);
1833   setOperationAction(ISD::FSUB, VT, Custom);
1834   setOperationAction(ISD::FTRUNC, VT, Custom);
1835   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1836   setOperationAction(ISD::LOAD, VT, StreamingSVE ? Legal : Custom);
1837   setOperationAction(ISD::MGATHER, VT, StreamingSVE ? Expand : Custom);
1838   setOperationAction(ISD::MLOAD, VT, Custom);
1839   setOperationAction(ISD::MSCATTER, VT, StreamingSVE ? Expand : Custom);
1840   setOperationAction(ISD::MSTORE, VT, Custom);
1841   setOperationAction(ISD::MUL, VT, Custom);
1842   setOperationAction(ISD::MULHS, VT, Custom);
1843   setOperationAction(ISD::MULHU, VT, Custom);
1844   setOperationAction(ISD::OR, VT, Custom);
1845   setOperationAction(ISD::SCALAR_TO_VECTOR, VT, StreamingSVE ? Legal : Expand);
1846   setOperationAction(ISD::SDIV, VT, Custom);
1847   setOperationAction(ISD::SELECT, VT, Custom);
1848   setOperationAction(ISD::SETCC, VT, Custom);
1849   setOperationAction(ISD::SHL, VT, Custom);
1850   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1851   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1852   setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1853   setOperationAction(ISD::SMAX, VT, Custom);
1854   setOperationAction(ISD::SMIN, VT, Custom);
1855   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1856   setOperationAction(ISD::SRA, VT, Custom);
1857   setOperationAction(ISD::SRL, VT, Custom);
1858   setOperationAction(ISD::STORE, VT, StreamingSVE ? Legal : Custom);
1859   setOperationAction(ISD::SUB, VT, Custom);
1860   setOperationAction(ISD::TRUNCATE, VT, Custom);
1861   setOperationAction(ISD::UDIV, VT, Custom);
1862   setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1863   setOperationAction(ISD::UMAX, VT, Custom);
1864   setOperationAction(ISD::UMIN, VT, Custom);
1865   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1866   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1867   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1868   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1869   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1870   setOperationAction(ISD::VECREDUCE_FMAXIMUM, VT, Custom);
1871   setOperationAction(ISD::VECREDUCE_FMINIMUM, VT, Custom);
1872   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1873   setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1874   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1875   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1876   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1877   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1878   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1879   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1880   setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1881   setOperationAction(ISD::VSELECT, VT, Custom);
1882   setOperationAction(ISD::XOR, VT, Custom);
1883   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1884 }
1885 
1886 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1887   addRegisterClass(VT, &AArch64::FPR64RegClass);
1888   addTypeForNEON(VT);
1889 }
1890 
1891 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1892   addRegisterClass(VT, &AArch64::FPR128RegClass);
1893   addTypeForNEON(VT);
1894 }
1895 
1896 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1897                                               LLVMContext &C, EVT VT) const {
1898   if (!VT.isVector())
1899     return MVT::i32;
1900   if (VT.isScalableVector())
1901     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1902   return VT.changeVectorElementTypeToInteger();
1903 }
1904 
1905 // isIntImmediate - This method tests to see if the node is a constant
1906 // operand. If so Imm will receive the value.
1907 static bool isIntImmediate(const SDNode *N, uint64_t &Imm) {
1908   if (const ConstantSDNode *C = dyn_cast<const ConstantSDNode>(N)) {
1909     Imm = C->getZExtValue();
1910     return true;
1911   }
1912   return false;
1913 }
1914 
1915 // isOpcWithIntImmediate - This method tests to see if the node is a specific
1916 // opcode and that it has a immediate integer right operand.
1917 // If so Imm will receive the value.
1918 static bool isOpcWithIntImmediate(const SDNode *N, unsigned Opc,
1919                                   uint64_t &Imm) {
1920   return N->getOpcode() == Opc &&
1921          isIntImmediate(N->getOperand(1).getNode(), Imm);
1922 }
1923 
1924 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1925                                const APInt &Demanded,
1926                                TargetLowering::TargetLoweringOpt &TLO,
1927                                unsigned NewOpc) {
1928   uint64_t OldImm = Imm, NewImm, Enc;
1929   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1930 
1931   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1932   // bimm64.
1933   if (Imm == 0 || Imm == Mask ||
1934       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1935     return false;
1936 
1937   unsigned EltSize = Size;
1938   uint64_t DemandedBits = Demanded.getZExtValue();
1939 
1940   // Clear bits that are not demanded.
1941   Imm &= DemandedBits;
1942 
1943   while (true) {
1944     // The goal here is to set the non-demanded bits in a way that minimizes
1945     // the number of switching between 0 and 1. In order to achieve this goal,
1946     // we set the non-demanded bits to the value of the preceding demanded bits.
1947     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1948     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1949     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1950     // The final result is 0b11000011.
1951     uint64_t NonDemandedBits = ~DemandedBits;
1952     uint64_t InvertedImm = ~Imm & DemandedBits;
1953     uint64_t RotatedImm =
1954         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1955         NonDemandedBits;
1956     uint64_t Sum = RotatedImm + NonDemandedBits;
1957     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1958     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1959     NewImm = (Imm | Ones) & Mask;
1960 
1961     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1962     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1963     // we halve the element size and continue the search.
1964     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1965       break;
1966 
1967     // We cannot shrink the element size any further if it is 2-bits.
1968     if (EltSize == 2)
1969       return false;
1970 
1971     EltSize /= 2;
1972     Mask >>= EltSize;
1973     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1974 
1975     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1976     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1977       return false;
1978 
1979     // Merge the upper and lower halves of Imm and DemandedBits.
1980     Imm |= Hi;
1981     DemandedBits |= DemandedBitsHi;
1982   }
1983 
1984   ++NumOptimizedImms;
1985 
1986   // Replicate the element across the register width.
1987   while (EltSize < Size) {
1988     NewImm |= NewImm << EltSize;
1989     EltSize *= 2;
1990   }
1991 
1992   (void)OldImm;
1993   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1994          "demanded bits should never be altered");
1995   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1996 
1997   // Create the new constant immediate node.
1998   EVT VT = Op.getValueType();
1999   SDLoc DL(Op);
2000   SDValue New;
2001 
2002   // If the new constant immediate is all-zeros or all-ones, let the target
2003   // independent DAG combine optimize this node.
2004   if (NewImm == 0 || NewImm == OrigMask) {
2005     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
2006                           TLO.DAG.getConstant(NewImm, DL, VT));
2007   // Otherwise, create a machine node so that target independent DAG combine
2008   // doesn't undo this optimization.
2009   } else {
2010     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
2011     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
2012     New = SDValue(
2013         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
2014   }
2015 
2016   return TLO.CombineTo(Op, New);
2017 }
2018 
2019 bool AArch64TargetLowering::targetShrinkDemandedConstant(
2020     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2021     TargetLoweringOpt &TLO) const {
2022   // Delay this optimization to as late as possible.
2023   if (!TLO.LegalOps)
2024     return false;
2025 
2026   if (!EnableOptimizeLogicalImm)
2027     return false;
2028 
2029   EVT VT = Op.getValueType();
2030   if (VT.isVector())
2031     return false;
2032 
2033   unsigned Size = VT.getSizeInBits();
2034   assert((Size == 32 || Size == 64) &&
2035          "i32 or i64 is expected after legalization.");
2036 
2037   // Exit early if we demand all bits.
2038   if (DemandedBits.popcount() == Size)
2039     return false;
2040 
2041   unsigned NewOpc;
2042   switch (Op.getOpcode()) {
2043   default:
2044     return false;
2045   case ISD::AND:
2046     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
2047     break;
2048   case ISD::OR:
2049     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
2050     break;
2051   case ISD::XOR:
2052     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
2053     break;
2054   }
2055   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2056   if (!C)
2057     return false;
2058   uint64_t Imm = C->getZExtValue();
2059   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
2060 }
2061 
2062 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
2063 /// Mask are known to be either zero or one and return them Known.
2064 void AArch64TargetLowering::computeKnownBitsForTargetNode(
2065     const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
2066     const SelectionDAG &DAG, unsigned Depth) const {
2067   switch (Op.getOpcode()) {
2068   default:
2069     break;
2070   case AArch64ISD::DUP: {
2071     SDValue SrcOp = Op.getOperand(0);
2072     Known = DAG.computeKnownBits(SrcOp, Depth + 1);
2073     if (SrcOp.getValueSizeInBits() != Op.getScalarValueSizeInBits()) {
2074       assert(SrcOp.getValueSizeInBits() > Op.getScalarValueSizeInBits() &&
2075              "Expected DUP implicit truncation");
2076       Known = Known.trunc(Op.getScalarValueSizeInBits());
2077     }
2078     break;
2079   }
2080   case AArch64ISD::CSEL: {
2081     KnownBits Known2;
2082     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
2083     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
2084     Known = Known.intersectWith(Known2);
2085     break;
2086   }
2087   case AArch64ISD::BICi: {
2088     // Compute the bit cleared value.
2089     uint64_t Mask =
2090         ~(Op->getConstantOperandVal(1) << Op->getConstantOperandVal(2));
2091     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
2092     Known &= KnownBits::makeConstant(APInt(Known.getBitWidth(), Mask));
2093     break;
2094   }
2095   case AArch64ISD::VLSHR: {
2096     KnownBits Known2;
2097     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
2098     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
2099     Known = KnownBits::lshr(Known, Known2);
2100     break;
2101   }
2102   case AArch64ISD::VASHR: {
2103     KnownBits Known2;
2104     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
2105     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
2106     Known = KnownBits::ashr(Known, Known2);
2107     break;
2108   }
2109   case AArch64ISD::MOVI: {
2110     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(0));
2111     Known =
2112         KnownBits::makeConstant(APInt(Known.getBitWidth(), CN->getZExtValue()));
2113     break;
2114   }
2115   case AArch64ISD::LOADgot:
2116   case AArch64ISD::ADDlow: {
2117     if (!Subtarget->isTargetILP32())
2118       break;
2119     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
2120     Known.Zero = APInt::getHighBitsSet(64, 32);
2121     break;
2122   }
2123   case AArch64ISD::ASSERT_ZEXT_BOOL: {
2124     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
2125     Known.Zero |= APInt(Known.getBitWidth(), 0xFE);
2126     break;
2127   }
2128   case ISD::INTRINSIC_W_CHAIN: {
2129     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
2130     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
2131     switch (IntID) {
2132     default: return;
2133     case Intrinsic::aarch64_ldaxr:
2134     case Intrinsic::aarch64_ldxr: {
2135       unsigned BitWidth = Known.getBitWidth();
2136       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
2137       unsigned MemBits = VT.getScalarSizeInBits();
2138       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
2139       return;
2140     }
2141     }
2142     break;
2143   }
2144   case ISD::INTRINSIC_WO_CHAIN:
2145   case ISD::INTRINSIC_VOID: {
2146     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2147     switch (IntNo) {
2148     default:
2149       break;
2150     case Intrinsic::aarch64_neon_umaxv:
2151     case Intrinsic::aarch64_neon_uminv: {
2152       // Figure out the datatype of the vector operand. The UMINV instruction
2153       // will zero extend the result, so we can mark as known zero all the
2154       // bits larger than the element datatype. 32-bit or larget doesn't need
2155       // this as those are legal types and will be handled by isel directly.
2156       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
2157       unsigned BitWidth = Known.getBitWidth();
2158       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
2159         assert(BitWidth >= 8 && "Unexpected width!");
2160         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
2161         Known.Zero |= Mask;
2162       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
2163         assert(BitWidth >= 16 && "Unexpected width!");
2164         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
2165         Known.Zero |= Mask;
2166       }
2167       break;
2168     } break;
2169     }
2170   }
2171   }
2172 }
2173 
2174 unsigned AArch64TargetLowering::ComputeNumSignBitsForTargetNode(
2175     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
2176     unsigned Depth) const {
2177   EVT VT = Op.getValueType();
2178   unsigned VTBits = VT.getScalarSizeInBits();
2179   unsigned Opcode = Op.getOpcode();
2180   switch (Opcode) {
2181     case AArch64ISD::CMEQ:
2182     case AArch64ISD::CMGE:
2183     case AArch64ISD::CMGT:
2184     case AArch64ISD::CMHI:
2185     case AArch64ISD::CMHS:
2186     case AArch64ISD::FCMEQ:
2187     case AArch64ISD::FCMGE:
2188     case AArch64ISD::FCMGT:
2189     case AArch64ISD::CMEQz:
2190     case AArch64ISD::CMGEz:
2191     case AArch64ISD::CMGTz:
2192     case AArch64ISD::CMLEz:
2193     case AArch64ISD::CMLTz:
2194     case AArch64ISD::FCMEQz:
2195     case AArch64ISD::FCMGEz:
2196     case AArch64ISD::FCMGTz:
2197     case AArch64ISD::FCMLEz:
2198     case AArch64ISD::FCMLTz:
2199       // Compares return either 0 or all-ones
2200       return VTBits;
2201   }
2202 
2203   return 1;
2204 }
2205 
2206 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
2207                                                   EVT) const {
2208   return MVT::i64;
2209 }
2210 
2211 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
2212     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
2213     unsigned *Fast) const {
2214   if (Subtarget->requiresStrictAlign())
2215     return false;
2216 
2217   if (Fast) {
2218     // Some CPUs are fine with unaligned stores except for 128-bit ones.
2219     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
2220             // See comments in performSTORECombine() for more details about
2221             // these conditions.
2222 
2223             // Code that uses clang vector extensions can mark that it
2224             // wants unaligned accesses to be treated as fast by
2225             // underspecifying alignment to be 1 or 2.
2226             Alignment <= 2 ||
2227 
2228             // Disregard v2i64. Memcpy lowering produces those and splitting
2229             // them regresses performance on micro-benchmarks and olden/bh.
2230             VT == MVT::v2i64;
2231   }
2232   return true;
2233 }
2234 
2235 // Same as above but handling LLTs instead.
2236 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
2237     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
2238     unsigned *Fast) const {
2239   if (Subtarget->requiresStrictAlign())
2240     return false;
2241 
2242   if (Fast) {
2243     // Some CPUs are fine with unaligned stores except for 128-bit ones.
2244     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
2245             Ty.getSizeInBytes() != 16 ||
2246             // See comments in performSTORECombine() for more details about
2247             // these conditions.
2248 
2249             // Code that uses clang vector extensions can mark that it
2250             // wants unaligned accesses to be treated as fast by
2251             // underspecifying alignment to be 1 or 2.
2252             Alignment <= 2 ||
2253 
2254             // Disregard v2i64. Memcpy lowering produces those and splitting
2255             // them regresses performance on micro-benchmarks and olden/bh.
2256             Ty == LLT::fixed_vector(2, 64);
2257   }
2258   return true;
2259 }
2260 
2261 FastISel *
2262 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2263                                       const TargetLibraryInfo *libInfo) const {
2264   return AArch64::createFastISel(funcInfo, libInfo);
2265 }
2266 
2267 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
2268 #define MAKE_CASE(V)                                                           \
2269   case V:                                                                      \
2270     return #V;
2271   switch ((AArch64ISD::NodeType)Opcode) {
2272   case AArch64ISD::FIRST_NUMBER:
2273     break;
2274     MAKE_CASE(AArch64ISD::OBSCURE_COPY)
2275     MAKE_CASE(AArch64ISD::SMSTART)
2276     MAKE_CASE(AArch64ISD::SMSTOP)
2277     MAKE_CASE(AArch64ISD::RESTORE_ZA)
2278     MAKE_CASE(AArch64ISD::CALL)
2279     MAKE_CASE(AArch64ISD::ADRP)
2280     MAKE_CASE(AArch64ISD::ADR)
2281     MAKE_CASE(AArch64ISD::ADDlow)
2282     MAKE_CASE(AArch64ISD::LOADgot)
2283     MAKE_CASE(AArch64ISD::RET_GLUE)
2284     MAKE_CASE(AArch64ISD::BRCOND)
2285     MAKE_CASE(AArch64ISD::CSEL)
2286     MAKE_CASE(AArch64ISD::CSINV)
2287     MAKE_CASE(AArch64ISD::CSNEG)
2288     MAKE_CASE(AArch64ISD::CSINC)
2289     MAKE_CASE(AArch64ISD::THREAD_POINTER)
2290     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
2291     MAKE_CASE(AArch64ISD::ABDS_PRED)
2292     MAKE_CASE(AArch64ISD::ABDU_PRED)
2293     MAKE_CASE(AArch64ISD::HADDS_PRED)
2294     MAKE_CASE(AArch64ISD::HADDU_PRED)
2295     MAKE_CASE(AArch64ISD::MUL_PRED)
2296     MAKE_CASE(AArch64ISD::MULHS_PRED)
2297     MAKE_CASE(AArch64ISD::MULHU_PRED)
2298     MAKE_CASE(AArch64ISD::RHADDS_PRED)
2299     MAKE_CASE(AArch64ISD::RHADDU_PRED)
2300     MAKE_CASE(AArch64ISD::SDIV_PRED)
2301     MAKE_CASE(AArch64ISD::SHL_PRED)
2302     MAKE_CASE(AArch64ISD::SMAX_PRED)
2303     MAKE_CASE(AArch64ISD::SMIN_PRED)
2304     MAKE_CASE(AArch64ISD::SRA_PRED)
2305     MAKE_CASE(AArch64ISD::SRL_PRED)
2306     MAKE_CASE(AArch64ISD::UDIV_PRED)
2307     MAKE_CASE(AArch64ISD::UMAX_PRED)
2308     MAKE_CASE(AArch64ISD::UMIN_PRED)
2309     MAKE_CASE(AArch64ISD::SRAD_MERGE_OP1)
2310     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
2311     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
2312     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
2313     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
2314     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
2315     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
2316     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
2317     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
2318     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
2319     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
2320     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
2321     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
2322     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
2323     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
2324     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
2325     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
2326     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
2327     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
2328     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
2329     MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
2330     MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
2331     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
2332     MAKE_CASE(AArch64ISD::ADC)
2333     MAKE_CASE(AArch64ISD::SBC)
2334     MAKE_CASE(AArch64ISD::ADDS)
2335     MAKE_CASE(AArch64ISD::SUBS)
2336     MAKE_CASE(AArch64ISD::ADCS)
2337     MAKE_CASE(AArch64ISD::SBCS)
2338     MAKE_CASE(AArch64ISD::ANDS)
2339     MAKE_CASE(AArch64ISD::CCMP)
2340     MAKE_CASE(AArch64ISD::CCMN)
2341     MAKE_CASE(AArch64ISD::FCCMP)
2342     MAKE_CASE(AArch64ISD::FCMP)
2343     MAKE_CASE(AArch64ISD::STRICT_FCMP)
2344     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
2345     MAKE_CASE(AArch64ISD::DUP)
2346     MAKE_CASE(AArch64ISD::DUPLANE8)
2347     MAKE_CASE(AArch64ISD::DUPLANE16)
2348     MAKE_CASE(AArch64ISD::DUPLANE32)
2349     MAKE_CASE(AArch64ISD::DUPLANE64)
2350     MAKE_CASE(AArch64ISD::DUPLANE128)
2351     MAKE_CASE(AArch64ISD::MOVI)
2352     MAKE_CASE(AArch64ISD::MOVIshift)
2353     MAKE_CASE(AArch64ISD::MOVIedit)
2354     MAKE_CASE(AArch64ISD::MOVImsl)
2355     MAKE_CASE(AArch64ISD::FMOV)
2356     MAKE_CASE(AArch64ISD::MVNIshift)
2357     MAKE_CASE(AArch64ISD::MVNImsl)
2358     MAKE_CASE(AArch64ISD::BICi)
2359     MAKE_CASE(AArch64ISD::ORRi)
2360     MAKE_CASE(AArch64ISD::BSP)
2361     MAKE_CASE(AArch64ISD::EXTR)
2362     MAKE_CASE(AArch64ISD::ZIP1)
2363     MAKE_CASE(AArch64ISD::ZIP2)
2364     MAKE_CASE(AArch64ISD::UZP1)
2365     MAKE_CASE(AArch64ISD::UZP2)
2366     MAKE_CASE(AArch64ISD::TRN1)
2367     MAKE_CASE(AArch64ISD::TRN2)
2368     MAKE_CASE(AArch64ISD::REV16)
2369     MAKE_CASE(AArch64ISD::REV32)
2370     MAKE_CASE(AArch64ISD::REV64)
2371     MAKE_CASE(AArch64ISD::EXT)
2372     MAKE_CASE(AArch64ISD::SPLICE)
2373     MAKE_CASE(AArch64ISD::VSHL)
2374     MAKE_CASE(AArch64ISD::VLSHR)
2375     MAKE_CASE(AArch64ISD::VASHR)
2376     MAKE_CASE(AArch64ISD::VSLI)
2377     MAKE_CASE(AArch64ISD::VSRI)
2378     MAKE_CASE(AArch64ISD::CMEQ)
2379     MAKE_CASE(AArch64ISD::CMGE)
2380     MAKE_CASE(AArch64ISD::CMGT)
2381     MAKE_CASE(AArch64ISD::CMHI)
2382     MAKE_CASE(AArch64ISD::CMHS)
2383     MAKE_CASE(AArch64ISD::FCMEQ)
2384     MAKE_CASE(AArch64ISD::FCMGE)
2385     MAKE_CASE(AArch64ISD::FCMGT)
2386     MAKE_CASE(AArch64ISD::CMEQz)
2387     MAKE_CASE(AArch64ISD::CMGEz)
2388     MAKE_CASE(AArch64ISD::CMGTz)
2389     MAKE_CASE(AArch64ISD::CMLEz)
2390     MAKE_CASE(AArch64ISD::CMLTz)
2391     MAKE_CASE(AArch64ISD::FCMEQz)
2392     MAKE_CASE(AArch64ISD::FCMGEz)
2393     MAKE_CASE(AArch64ISD::FCMGTz)
2394     MAKE_CASE(AArch64ISD::FCMLEz)
2395     MAKE_CASE(AArch64ISD::FCMLTz)
2396     MAKE_CASE(AArch64ISD::SADDV)
2397     MAKE_CASE(AArch64ISD::UADDV)
2398     MAKE_CASE(AArch64ISD::SDOT)
2399     MAKE_CASE(AArch64ISD::UDOT)
2400     MAKE_CASE(AArch64ISD::SMINV)
2401     MAKE_CASE(AArch64ISD::UMINV)
2402     MAKE_CASE(AArch64ISD::SMAXV)
2403     MAKE_CASE(AArch64ISD::UMAXV)
2404     MAKE_CASE(AArch64ISD::SADDV_PRED)
2405     MAKE_CASE(AArch64ISD::UADDV_PRED)
2406     MAKE_CASE(AArch64ISD::SMAXV_PRED)
2407     MAKE_CASE(AArch64ISD::UMAXV_PRED)
2408     MAKE_CASE(AArch64ISD::SMINV_PRED)
2409     MAKE_CASE(AArch64ISD::UMINV_PRED)
2410     MAKE_CASE(AArch64ISD::ORV_PRED)
2411     MAKE_CASE(AArch64ISD::EORV_PRED)
2412     MAKE_CASE(AArch64ISD::ANDV_PRED)
2413     MAKE_CASE(AArch64ISD::CLASTA_N)
2414     MAKE_CASE(AArch64ISD::CLASTB_N)
2415     MAKE_CASE(AArch64ISD::LASTA)
2416     MAKE_CASE(AArch64ISD::LASTB)
2417     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
2418     MAKE_CASE(AArch64ISD::LS64_BUILD)
2419     MAKE_CASE(AArch64ISD::LS64_EXTRACT)
2420     MAKE_CASE(AArch64ISD::TBL)
2421     MAKE_CASE(AArch64ISD::FADD_PRED)
2422     MAKE_CASE(AArch64ISD::FADDA_PRED)
2423     MAKE_CASE(AArch64ISD::FADDV_PRED)
2424     MAKE_CASE(AArch64ISD::FDIV_PRED)
2425     MAKE_CASE(AArch64ISD::FMA_PRED)
2426     MAKE_CASE(AArch64ISD::FMAX_PRED)
2427     MAKE_CASE(AArch64ISD::FMAXV_PRED)
2428     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
2429     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
2430     MAKE_CASE(AArch64ISD::FMIN_PRED)
2431     MAKE_CASE(AArch64ISD::FMINV_PRED)
2432     MAKE_CASE(AArch64ISD::FMINNM_PRED)
2433     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
2434     MAKE_CASE(AArch64ISD::FMUL_PRED)
2435     MAKE_CASE(AArch64ISD::FSUB_PRED)
2436     MAKE_CASE(AArch64ISD::RDSVL)
2437     MAKE_CASE(AArch64ISD::BIC)
2438     MAKE_CASE(AArch64ISD::BIT)
2439     MAKE_CASE(AArch64ISD::CBZ)
2440     MAKE_CASE(AArch64ISD::CBNZ)
2441     MAKE_CASE(AArch64ISD::TBZ)
2442     MAKE_CASE(AArch64ISD::TBNZ)
2443     MAKE_CASE(AArch64ISD::TC_RETURN)
2444     MAKE_CASE(AArch64ISD::PREFETCH)
2445     MAKE_CASE(AArch64ISD::SITOF)
2446     MAKE_CASE(AArch64ISD::UITOF)
2447     MAKE_CASE(AArch64ISD::NVCAST)
2448     MAKE_CASE(AArch64ISD::MRS)
2449     MAKE_CASE(AArch64ISD::SQSHL_I)
2450     MAKE_CASE(AArch64ISD::UQSHL_I)
2451     MAKE_CASE(AArch64ISD::SRSHR_I)
2452     MAKE_CASE(AArch64ISD::URSHR_I)
2453     MAKE_CASE(AArch64ISD::SQSHLU_I)
2454     MAKE_CASE(AArch64ISD::WrapperLarge)
2455     MAKE_CASE(AArch64ISD::LD2post)
2456     MAKE_CASE(AArch64ISD::LD3post)
2457     MAKE_CASE(AArch64ISD::LD4post)
2458     MAKE_CASE(AArch64ISD::ST2post)
2459     MAKE_CASE(AArch64ISD::ST3post)
2460     MAKE_CASE(AArch64ISD::ST4post)
2461     MAKE_CASE(AArch64ISD::LD1x2post)
2462     MAKE_CASE(AArch64ISD::LD1x3post)
2463     MAKE_CASE(AArch64ISD::LD1x4post)
2464     MAKE_CASE(AArch64ISD::ST1x2post)
2465     MAKE_CASE(AArch64ISD::ST1x3post)
2466     MAKE_CASE(AArch64ISD::ST1x4post)
2467     MAKE_CASE(AArch64ISD::LD1DUPpost)
2468     MAKE_CASE(AArch64ISD::LD2DUPpost)
2469     MAKE_CASE(AArch64ISD::LD3DUPpost)
2470     MAKE_CASE(AArch64ISD::LD4DUPpost)
2471     MAKE_CASE(AArch64ISD::LD1LANEpost)
2472     MAKE_CASE(AArch64ISD::LD2LANEpost)
2473     MAKE_CASE(AArch64ISD::LD3LANEpost)
2474     MAKE_CASE(AArch64ISD::LD4LANEpost)
2475     MAKE_CASE(AArch64ISD::ST2LANEpost)
2476     MAKE_CASE(AArch64ISD::ST3LANEpost)
2477     MAKE_CASE(AArch64ISD::ST4LANEpost)
2478     MAKE_CASE(AArch64ISD::SMULL)
2479     MAKE_CASE(AArch64ISD::UMULL)
2480     MAKE_CASE(AArch64ISD::PMULL)
2481     MAKE_CASE(AArch64ISD::FRECPE)
2482     MAKE_CASE(AArch64ISD::FRECPS)
2483     MAKE_CASE(AArch64ISD::FRSQRTE)
2484     MAKE_CASE(AArch64ISD::FRSQRTS)
2485     MAKE_CASE(AArch64ISD::STG)
2486     MAKE_CASE(AArch64ISD::STZG)
2487     MAKE_CASE(AArch64ISD::ST2G)
2488     MAKE_CASE(AArch64ISD::STZ2G)
2489     MAKE_CASE(AArch64ISD::SUNPKHI)
2490     MAKE_CASE(AArch64ISD::SUNPKLO)
2491     MAKE_CASE(AArch64ISD::UUNPKHI)
2492     MAKE_CASE(AArch64ISD::UUNPKLO)
2493     MAKE_CASE(AArch64ISD::INSR)
2494     MAKE_CASE(AArch64ISD::PTEST)
2495     MAKE_CASE(AArch64ISD::PTEST_ANY)
2496     MAKE_CASE(AArch64ISD::PTRUE)
2497     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
2498     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
2499     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
2500     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
2501     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
2502     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
2503     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
2504     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
2505     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
2506     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
2507     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
2508     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
2509     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
2510     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
2511     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
2512     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
2513     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
2514     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
2515     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
2516     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
2517     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
2518     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
2519     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
2520     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
2521     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
2522     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
2523     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
2524     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
2525     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
2526     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
2527     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
2528     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
2529     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
2530     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
2531     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
2532     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
2533     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
2534     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
2535     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
2536     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
2537     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
2538     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
2539     MAKE_CASE(AArch64ISD::ST1_PRED)
2540     MAKE_CASE(AArch64ISD::SST1_PRED)
2541     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
2542     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
2543     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
2544     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
2545     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
2546     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
2547     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
2548     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
2549     MAKE_CASE(AArch64ISD::LDP)
2550     MAKE_CASE(AArch64ISD::LDIAPP)
2551     MAKE_CASE(AArch64ISD::LDNP)
2552     MAKE_CASE(AArch64ISD::STP)
2553     MAKE_CASE(AArch64ISD::STILP)
2554     MAKE_CASE(AArch64ISD::STNP)
2555     MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
2556     MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
2557     MAKE_CASE(AArch64ISD::REVH_MERGE_PASSTHRU)
2558     MAKE_CASE(AArch64ISD::REVW_MERGE_PASSTHRU)
2559     MAKE_CASE(AArch64ISD::REVD_MERGE_PASSTHRU)
2560     MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
2561     MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
2562     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
2563     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
2564     MAKE_CASE(AArch64ISD::ADDP)
2565     MAKE_CASE(AArch64ISD::SADDLP)
2566     MAKE_CASE(AArch64ISD::UADDLP)
2567     MAKE_CASE(AArch64ISD::CALL_RVMARKER)
2568     MAKE_CASE(AArch64ISD::ASSERT_ZEXT_BOOL)
2569     MAKE_CASE(AArch64ISD::MOPS_MEMSET)
2570     MAKE_CASE(AArch64ISD::MOPS_MEMSET_TAGGING)
2571     MAKE_CASE(AArch64ISD::MOPS_MEMCOPY)
2572     MAKE_CASE(AArch64ISD::MOPS_MEMMOVE)
2573     MAKE_CASE(AArch64ISD::CALL_BTI)
2574     MAKE_CASE(AArch64ISD::MRRS)
2575     MAKE_CASE(AArch64ISD::MSRR)
2576   }
2577 #undef MAKE_CASE
2578   return nullptr;
2579 }
2580 
2581 MachineBasicBlock *
2582 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
2583                                     MachineBasicBlock *MBB) const {
2584   // We materialise the F128CSEL pseudo-instruction as some control flow and a
2585   // phi node:
2586 
2587   // OrigBB:
2588   //     [... previous instrs leading to comparison ...]
2589   //     b.ne TrueBB
2590   //     b EndBB
2591   // TrueBB:
2592   //     ; Fallthrough
2593   // EndBB:
2594   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
2595 
2596   MachineFunction *MF = MBB->getParent();
2597   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2598   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2599   DebugLoc DL = MI.getDebugLoc();
2600   MachineFunction::iterator It = ++MBB->getIterator();
2601 
2602   Register DestReg = MI.getOperand(0).getReg();
2603   Register IfTrueReg = MI.getOperand(1).getReg();
2604   Register IfFalseReg = MI.getOperand(2).getReg();
2605   unsigned CondCode = MI.getOperand(3).getImm();
2606   bool NZCVKilled = MI.getOperand(4).isKill();
2607 
2608   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
2609   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
2610   MF->insert(It, TrueBB);
2611   MF->insert(It, EndBB);
2612 
2613   // Transfer rest of current basic-block to EndBB
2614   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
2615                 MBB->end());
2616   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
2617 
2618   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
2619   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
2620   MBB->addSuccessor(TrueBB);
2621   MBB->addSuccessor(EndBB);
2622 
2623   // TrueBB falls through to the end.
2624   TrueBB->addSuccessor(EndBB);
2625 
2626   if (!NZCVKilled) {
2627     TrueBB->addLiveIn(AArch64::NZCV);
2628     EndBB->addLiveIn(AArch64::NZCV);
2629   }
2630 
2631   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
2632       .addReg(IfTrueReg)
2633       .addMBB(TrueBB)
2634       .addReg(IfFalseReg)
2635       .addMBB(MBB);
2636 
2637   MI.eraseFromParent();
2638   return EndBB;
2639 }
2640 
2641 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
2642        MachineInstr &MI, MachineBasicBlock *BB) const {
2643   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2644              BB->getParent()->getFunction().getPersonalityFn())) &&
2645          "SEH does not use catchret!");
2646   return BB;
2647 }
2648 
2649 MachineBasicBlock *
2650 AArch64TargetLowering::EmitTileLoad(unsigned Opc, unsigned BaseReg,
2651                                     MachineInstr &MI,
2652                                     MachineBasicBlock *BB) const {
2653   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2654   MachineInstrBuilder MIB = BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(Opc));
2655 
2656   MIB.addReg(BaseReg + MI.getOperand(0).getImm(), RegState::Define);
2657   MIB.add(MI.getOperand(1)); // slice index register
2658   MIB.add(MI.getOperand(2)); // slice index offset
2659   MIB.add(MI.getOperand(3)); // pg
2660   MIB.add(MI.getOperand(4)); // base
2661   MIB.add(MI.getOperand(5)); // offset
2662 
2663   MI.eraseFromParent(); // The pseudo is gone now.
2664   return BB;
2665 }
2666 
2667 MachineBasicBlock *
2668 AArch64TargetLowering::EmitFill(MachineInstr &MI, MachineBasicBlock *BB) const {
2669   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2670   MachineInstrBuilder MIB =
2671       BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(AArch64::LDR_ZA));
2672 
2673   MIB.addReg(AArch64::ZA, RegState::Define);
2674   MIB.add(MI.getOperand(0)); // Vector select register
2675   MIB.add(MI.getOperand(1)); // Vector select offset
2676   MIB.add(MI.getOperand(2)); // Base
2677   MIB.add(MI.getOperand(1)); // Offset, same as vector select offset
2678 
2679   MI.eraseFromParent(); // The pseudo is gone now.
2680   return BB;
2681 }
2682 
2683 MachineBasicBlock *
2684 AArch64TargetLowering::EmitZAInstr(unsigned Opc, unsigned BaseReg,
2685                                    MachineInstr &MI,
2686                                    MachineBasicBlock *BB, bool HasTile) const {
2687   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2688   MachineInstrBuilder MIB = BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(Opc));
2689   unsigned StartIdx = 0;
2690 
2691   if (HasTile) {
2692     MIB.addReg(BaseReg + MI.getOperand(0).getImm(), RegState::Define);
2693     MIB.addReg(BaseReg + MI.getOperand(0).getImm());
2694     StartIdx = 1;
2695   } else
2696     MIB.addReg(BaseReg, RegState::Define).addReg(BaseReg);
2697 
2698   for (unsigned I = StartIdx; I < MI.getNumOperands(); ++I)
2699     MIB.add(MI.getOperand(I));
2700 
2701   MI.eraseFromParent(); // The pseudo is gone now.
2702   return BB;
2703 }
2704 
2705 MachineBasicBlock *
2706 AArch64TargetLowering::EmitZero(MachineInstr &MI, MachineBasicBlock *BB) const {
2707   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2708   MachineInstrBuilder MIB =
2709       BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(AArch64::ZERO_M));
2710   MIB.add(MI.getOperand(0)); // Mask
2711 
2712   unsigned Mask = MI.getOperand(0).getImm();
2713   for (unsigned I = 0; I < 8; I++) {
2714     if (Mask & (1 << I))
2715       MIB.addDef(AArch64::ZAD0 + I, RegState::ImplicitDefine);
2716   }
2717 
2718   MI.eraseFromParent(); // The pseudo is gone now.
2719   return BB;
2720 }
2721 
2722 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
2723     MachineInstr &MI, MachineBasicBlock *BB) const {
2724 
2725   int SMEOrigInstr = AArch64::getSMEPseudoMap(MI.getOpcode());
2726   if (SMEOrigInstr != -1) {
2727     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2728     uint64_t SMEMatrixType =
2729         TII->get(MI.getOpcode()).TSFlags & AArch64::SMEMatrixTypeMask;
2730     switch (SMEMatrixType) {
2731     case (AArch64::SMEMatrixArray):
2732       return EmitZAInstr(SMEOrigInstr, AArch64::ZA, MI, BB, /*HasTile*/ false);
2733     case (AArch64::SMEMatrixTileB):
2734       return EmitZAInstr(SMEOrigInstr, AArch64::ZAB0, MI, BB, /*HasTile*/ true);
2735     case (AArch64::SMEMatrixTileH):
2736       return EmitZAInstr(SMEOrigInstr, AArch64::ZAH0, MI, BB, /*HasTile*/ true);
2737     case (AArch64::SMEMatrixTileS):
2738       return EmitZAInstr(SMEOrigInstr, AArch64::ZAS0, MI, BB, /*HasTile*/ true);
2739     case (AArch64::SMEMatrixTileD):
2740       return EmitZAInstr(SMEOrigInstr, AArch64::ZAD0, MI, BB, /*HasTile*/ true);
2741     case (AArch64::SMEMatrixTileQ):
2742       return EmitZAInstr(SMEOrigInstr, AArch64::ZAQ0, MI, BB, /*HasTile*/ true);
2743     }
2744   }
2745 
2746   switch (MI.getOpcode()) {
2747   default:
2748 #ifndef NDEBUG
2749     MI.dump();
2750 #endif
2751     llvm_unreachable("Unexpected instruction for custom inserter!");
2752 
2753   case AArch64::F128CSEL:
2754     return EmitF128CSEL(MI, BB);
2755   case TargetOpcode::STATEPOINT:
2756     // STATEPOINT is a pseudo instruction which has no implicit defs/uses
2757     // while bl call instruction (where statepoint will be lowered at the end)
2758     // has implicit def. This def is early-clobber as it will be set at
2759     // the moment of the call and earlier than any use is read.
2760     // Add this implicit dead def here as a workaround.
2761     MI.addOperand(*MI.getMF(),
2762                   MachineOperand::CreateReg(
2763                       AArch64::LR, /*isDef*/ true,
2764                       /*isImp*/ true, /*isKill*/ false, /*isDead*/ true,
2765                       /*isUndef*/ false, /*isEarlyClobber*/ true));
2766     [[fallthrough]];
2767   case TargetOpcode::STACKMAP:
2768   case TargetOpcode::PATCHPOINT:
2769     return emitPatchPoint(MI, BB);
2770 
2771   case TargetOpcode::PATCHABLE_EVENT_CALL:
2772   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
2773     return BB;
2774 
2775   case AArch64::CATCHRET:
2776     return EmitLoweredCatchRet(MI, BB);
2777   case AArch64::LD1_MXIPXX_H_PSEUDO_B:
2778     return EmitTileLoad(AArch64::LD1_MXIPXX_H_B, AArch64::ZAB0, MI, BB);
2779   case AArch64::LD1_MXIPXX_H_PSEUDO_H:
2780     return EmitTileLoad(AArch64::LD1_MXIPXX_H_H, AArch64::ZAH0, MI, BB);
2781   case AArch64::LD1_MXIPXX_H_PSEUDO_S:
2782     return EmitTileLoad(AArch64::LD1_MXIPXX_H_S, AArch64::ZAS0, MI, BB);
2783   case AArch64::LD1_MXIPXX_H_PSEUDO_D:
2784     return EmitTileLoad(AArch64::LD1_MXIPXX_H_D, AArch64::ZAD0, MI, BB);
2785   case AArch64::LD1_MXIPXX_H_PSEUDO_Q:
2786     return EmitTileLoad(AArch64::LD1_MXIPXX_H_Q, AArch64::ZAQ0, MI, BB);
2787   case AArch64::LD1_MXIPXX_V_PSEUDO_B:
2788     return EmitTileLoad(AArch64::LD1_MXIPXX_V_B, AArch64::ZAB0, MI, BB);
2789   case AArch64::LD1_MXIPXX_V_PSEUDO_H:
2790     return EmitTileLoad(AArch64::LD1_MXIPXX_V_H, AArch64::ZAH0, MI, BB);
2791   case AArch64::LD1_MXIPXX_V_PSEUDO_S:
2792     return EmitTileLoad(AArch64::LD1_MXIPXX_V_S, AArch64::ZAS0, MI, BB);
2793   case AArch64::LD1_MXIPXX_V_PSEUDO_D:
2794     return EmitTileLoad(AArch64::LD1_MXIPXX_V_D, AArch64::ZAD0, MI, BB);
2795   case AArch64::LD1_MXIPXX_V_PSEUDO_Q:
2796     return EmitTileLoad(AArch64::LD1_MXIPXX_V_Q, AArch64::ZAQ0, MI, BB);
2797   case AArch64::LDR_ZA_PSEUDO:
2798     return EmitFill(MI, BB);
2799   case AArch64::ZERO_M_PSEUDO:
2800     return EmitZero(MI, BB);
2801   }
2802 }
2803 
2804 //===----------------------------------------------------------------------===//
2805 // AArch64 Lowering private implementation.
2806 //===----------------------------------------------------------------------===//
2807 
2808 //===----------------------------------------------------------------------===//
2809 // Lowering Code
2810 //===----------------------------------------------------------------------===//
2811 
2812 // Forward declarations of SVE fixed length lowering helpers
2813 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT);
2814 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2815 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2816 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
2817                                                 SelectionDAG &DAG);
2818 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
2819                                              EVT VT);
2820 
2821 /// isZerosVector - Check whether SDNode N is a zero-filled vector.
2822 static bool isZerosVector(const SDNode *N) {
2823   // Look through a bit convert.
2824   while (N->getOpcode() == ISD::BITCAST)
2825     N = N->getOperand(0).getNode();
2826 
2827   if (ISD::isConstantSplatVectorAllZeros(N))
2828     return true;
2829 
2830   if (N->getOpcode() != AArch64ISD::DUP)
2831     return false;
2832 
2833   auto Opnd0 = N->getOperand(0);
2834   return isNullConstant(Opnd0) || isNullFPConstant(Opnd0);
2835 }
2836 
2837 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
2838 /// CC
2839 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
2840   switch (CC) {
2841   default:
2842     llvm_unreachable("Unknown condition code!");
2843   case ISD::SETNE:
2844     return AArch64CC::NE;
2845   case ISD::SETEQ:
2846     return AArch64CC::EQ;
2847   case ISD::SETGT:
2848     return AArch64CC::GT;
2849   case ISD::SETGE:
2850     return AArch64CC::GE;
2851   case ISD::SETLT:
2852     return AArch64CC::LT;
2853   case ISD::SETLE:
2854     return AArch64CC::LE;
2855   case ISD::SETUGT:
2856     return AArch64CC::HI;
2857   case ISD::SETUGE:
2858     return AArch64CC::HS;
2859   case ISD::SETULT:
2860     return AArch64CC::LO;
2861   case ISD::SETULE:
2862     return AArch64CC::LS;
2863   }
2864 }
2865 
2866 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
2867 static void changeFPCCToAArch64CC(ISD::CondCode CC,
2868                                   AArch64CC::CondCode &CondCode,
2869                                   AArch64CC::CondCode &CondCode2) {
2870   CondCode2 = AArch64CC::AL;
2871   switch (CC) {
2872   default:
2873     llvm_unreachable("Unknown FP condition!");
2874   case ISD::SETEQ:
2875   case ISD::SETOEQ:
2876     CondCode = AArch64CC::EQ;
2877     break;
2878   case ISD::SETGT:
2879   case ISD::SETOGT:
2880     CondCode = AArch64CC::GT;
2881     break;
2882   case ISD::SETGE:
2883   case ISD::SETOGE:
2884     CondCode = AArch64CC::GE;
2885     break;
2886   case ISD::SETOLT:
2887     CondCode = AArch64CC::MI;
2888     break;
2889   case ISD::SETOLE:
2890     CondCode = AArch64CC::LS;
2891     break;
2892   case ISD::SETONE:
2893     CondCode = AArch64CC::MI;
2894     CondCode2 = AArch64CC::GT;
2895     break;
2896   case ISD::SETO:
2897     CondCode = AArch64CC::VC;
2898     break;
2899   case ISD::SETUO:
2900     CondCode = AArch64CC::VS;
2901     break;
2902   case ISD::SETUEQ:
2903     CondCode = AArch64CC::EQ;
2904     CondCode2 = AArch64CC::VS;
2905     break;
2906   case ISD::SETUGT:
2907     CondCode = AArch64CC::HI;
2908     break;
2909   case ISD::SETUGE:
2910     CondCode = AArch64CC::PL;
2911     break;
2912   case ISD::SETLT:
2913   case ISD::SETULT:
2914     CondCode = AArch64CC::LT;
2915     break;
2916   case ISD::SETLE:
2917   case ISD::SETULE:
2918     CondCode = AArch64CC::LE;
2919     break;
2920   case ISD::SETNE:
2921   case ISD::SETUNE:
2922     CondCode = AArch64CC::NE;
2923     break;
2924   }
2925 }
2926 
2927 /// Convert a DAG fp condition code to an AArch64 CC.
2928 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2929 /// should be AND'ed instead of OR'ed.
2930 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2931                                      AArch64CC::CondCode &CondCode,
2932                                      AArch64CC::CondCode &CondCode2) {
2933   CondCode2 = AArch64CC::AL;
2934   switch (CC) {
2935   default:
2936     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2937     assert(CondCode2 == AArch64CC::AL);
2938     break;
2939   case ISD::SETONE:
2940     // (a one b)
2941     // == ((a olt b) || (a ogt b))
2942     // == ((a ord b) && (a une b))
2943     CondCode = AArch64CC::VC;
2944     CondCode2 = AArch64CC::NE;
2945     break;
2946   case ISD::SETUEQ:
2947     // (a ueq b)
2948     // == ((a uno b) || (a oeq b))
2949     // == ((a ule b) && (a uge b))
2950     CondCode = AArch64CC::PL;
2951     CondCode2 = AArch64CC::LE;
2952     break;
2953   }
2954 }
2955 
2956 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2957 /// CC usable with the vector instructions. Fewer operations are available
2958 /// without a real NZCV register, so we have to use less efficient combinations
2959 /// to get the same effect.
2960 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2961                                         AArch64CC::CondCode &CondCode,
2962                                         AArch64CC::CondCode &CondCode2,
2963                                         bool &Invert) {
2964   Invert = false;
2965   switch (CC) {
2966   default:
2967     // Mostly the scalar mappings work fine.
2968     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2969     break;
2970   case ISD::SETUO:
2971     Invert = true;
2972     [[fallthrough]];
2973   case ISD::SETO:
2974     CondCode = AArch64CC::MI;
2975     CondCode2 = AArch64CC::GE;
2976     break;
2977   case ISD::SETUEQ:
2978   case ISD::SETULT:
2979   case ISD::SETULE:
2980   case ISD::SETUGT:
2981   case ISD::SETUGE:
2982     // All of the compare-mask comparisons are ordered, but we can switch
2983     // between the two by a double inversion. E.g. ULE == !OGT.
2984     Invert = true;
2985     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2986                           CondCode, CondCode2);
2987     break;
2988   }
2989 }
2990 
2991 static bool isLegalArithImmed(uint64_t C) {
2992   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2993   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2994   LLVM_DEBUG(dbgs() << "Is imm " << C
2995                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2996   return IsLegal;
2997 }
2998 
2999 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
3000 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
3001 // can be set differently by this operation. It comes down to whether
3002 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
3003 // everything is fine. If not then the optimization is wrong. Thus general
3004 // comparisons are only valid if op2 != 0.
3005 //
3006 // So, finally, the only LLVM-native comparisons that don't mention C and V
3007 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
3008 // the absence of information about op2.
3009 static bool isCMN(SDValue Op, ISD::CondCode CC) {
3010   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
3011          (CC == ISD::SETEQ || CC == ISD::SETNE);
3012 }
3013 
3014 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
3015                                       SelectionDAG &DAG, SDValue Chain,
3016                                       bool IsSignaling) {
3017   EVT VT = LHS.getValueType();
3018   assert(VT != MVT::f128);
3019 
3020   const bool FullFP16 = DAG.getSubtarget<AArch64Subtarget>().hasFullFP16();
3021 
3022   if (VT == MVT::f16 && !FullFP16) {
3023     LHS = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f32, MVT::Other},
3024                       {Chain, LHS});
3025     RHS = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f32, MVT::Other},
3026                       {LHS.getValue(1), RHS});
3027     Chain = RHS.getValue(1);
3028     VT = MVT::f32;
3029   }
3030   unsigned Opcode =
3031       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
3032   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
3033 }
3034 
3035 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3036                               const SDLoc &dl, SelectionDAG &DAG) {
3037   EVT VT = LHS.getValueType();
3038   const bool FullFP16 = DAG.getSubtarget<AArch64Subtarget>().hasFullFP16();
3039 
3040   if (VT.isFloatingPoint()) {
3041     assert(VT != MVT::f128);
3042     if (VT == MVT::f16 && !FullFP16) {
3043       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3044       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3045       VT = MVT::f32;
3046     }
3047     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
3048   }
3049 
3050   // The CMP instruction is just an alias for SUBS, and representing it as
3051   // SUBS means that it's possible to get CSE with subtract operations.
3052   // A later phase can perform the optimization of setting the destination
3053   // register to WZR/XZR if it ends up being unused.
3054   unsigned Opcode = AArch64ISD::SUBS;
3055 
3056   if (isCMN(RHS, CC)) {
3057     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
3058     Opcode = AArch64ISD::ADDS;
3059     RHS = RHS.getOperand(1);
3060   } else if (isCMN(LHS, CC)) {
3061     // As we are looking for EQ/NE compares, the operands can be commuted ; can
3062     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
3063     Opcode = AArch64ISD::ADDS;
3064     LHS = LHS.getOperand(1);
3065   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
3066     if (LHS.getOpcode() == ISD::AND) {
3067       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
3068       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
3069       // of the signed comparisons.
3070       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
3071                                            DAG.getVTList(VT, MVT_CC),
3072                                            LHS.getOperand(0),
3073                                            LHS.getOperand(1));
3074       // Replace all users of (and X, Y) with newly generated (ands X, Y)
3075       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
3076       return ANDSNode.getValue(1);
3077     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
3078       // Use result of ANDS
3079       return LHS.getValue(1);
3080     }
3081   }
3082 
3083   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
3084       .getValue(1);
3085 }
3086 
3087 /// \defgroup AArch64CCMP CMP;CCMP matching
3088 ///
3089 /// These functions deal with the formation of CMP;CCMP;... sequences.
3090 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
3091 /// a comparison. They set the NZCV flags to a predefined value if their
3092 /// predicate is false. This allows to express arbitrary conjunctions, for
3093 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
3094 /// expressed as:
3095 ///   cmp A
3096 ///   ccmp B, inv(CB), CA
3097 ///   check for CB flags
3098 ///
3099 /// This naturally lets us implement chains of AND operations with SETCC
3100 /// operands. And we can even implement some other situations by transforming
3101 /// them:
3102 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
3103 ///     negating the flags used in a CCMP/FCCMP operations.
3104 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
3105 ///     by negating the flags we test for afterwards. i.e.
3106 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
3107 ///   - Note that we can only ever negate all previously processed results.
3108 ///     What we can not implement by flipping the flags to test is a negation
3109 ///     of two sub-trees (because the negation affects all sub-trees emitted so
3110 ///     far, so the 2nd sub-tree we emit would also affect the first).
3111 /// With those tools we can implement some OR operations:
3112 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
3113 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
3114 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
3115 ///     elimination rules from earlier to implement the whole thing as a
3116 ///     CCMP/FCCMP chain.
3117 ///
3118 /// As complete example:
3119 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
3120 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
3121 /// can be reassociated to:
3122 ///     or (and (setCC (cmp C)) setCD (cmp D))
3123 //         (or (setCA (cmp A)) (setCB (cmp B)))
3124 /// can be transformed to:
3125 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
3126 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
3127 /// which can be implemented as:
3128 ///   cmp C
3129 ///   ccmp D, inv(CD), CC
3130 ///   ccmp A, CA, inv(CD)
3131 ///   ccmp B, CB, inv(CA)
3132 ///   check for CB flags
3133 ///
3134 /// A counterexample is "or (and A B) (and C D)" which translates to
3135 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
3136 /// can only implement 1 of the inner (not) operations, but not both!
3137 /// @{
3138 
3139 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
3140 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
3141                                          ISD::CondCode CC, SDValue CCOp,
3142                                          AArch64CC::CondCode Predicate,
3143                                          AArch64CC::CondCode OutCC,
3144                                          const SDLoc &DL, SelectionDAG &DAG) {
3145   unsigned Opcode = 0;
3146   const bool FullFP16 = DAG.getSubtarget<AArch64Subtarget>().hasFullFP16();
3147 
3148   if (LHS.getValueType().isFloatingPoint()) {
3149     assert(LHS.getValueType() != MVT::f128);
3150     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
3151       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
3152       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
3153     }
3154     Opcode = AArch64ISD::FCCMP;
3155   } else if (RHS.getOpcode() == ISD::SUB) {
3156     SDValue SubOp0 = RHS.getOperand(0);
3157     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3158       // See emitComparison() on why we can only do this for SETEQ and SETNE.
3159       Opcode = AArch64ISD::CCMN;
3160       RHS = RHS.getOperand(1);
3161     }
3162   }
3163   if (Opcode == 0)
3164     Opcode = AArch64ISD::CCMP;
3165 
3166   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
3167   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
3168   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
3169   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
3170   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
3171 }
3172 
3173 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
3174 /// expressed as a conjunction. See \ref AArch64CCMP.
3175 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
3176 ///                     changing the conditions on the SETCC tests.
3177 ///                     (this means we can call emitConjunctionRec() with
3178 ///                      Negate==true on this sub-tree)
3179 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
3180 ///                     cannot do the negation naturally. We are required to
3181 ///                     emit the subtree first in this case.
3182 /// \param WillNegate   Is true if are called when the result of this
3183 ///                     subexpression must be negated. This happens when the
3184 ///                     outer expression is an OR. We can use this fact to know
3185 ///                     that we have a double negation (or (or ...) ...) that
3186 ///                     can be implemented for free.
3187 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
3188                                bool &MustBeFirst, bool WillNegate,
3189                                unsigned Depth = 0) {
3190   if (!Val.hasOneUse())
3191     return false;
3192   unsigned Opcode = Val->getOpcode();
3193   if (Opcode == ISD::SETCC) {
3194     if (Val->getOperand(0).getValueType() == MVT::f128)
3195       return false;
3196     CanNegate = true;
3197     MustBeFirst = false;
3198     return true;
3199   }
3200   // Protect against exponential runtime and stack overflow.
3201   if (Depth > 6)
3202     return false;
3203   if (Opcode == ISD::AND || Opcode == ISD::OR) {
3204     bool IsOR = Opcode == ISD::OR;
3205     SDValue O0 = Val->getOperand(0);
3206     SDValue O1 = Val->getOperand(1);
3207     bool CanNegateL;
3208     bool MustBeFirstL;
3209     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
3210       return false;
3211     bool CanNegateR;
3212     bool MustBeFirstR;
3213     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
3214       return false;
3215 
3216     if (MustBeFirstL && MustBeFirstR)
3217       return false;
3218 
3219     if (IsOR) {
3220       // For an OR expression we need to be able to naturally negate at least
3221       // one side or we cannot do the transformation at all.
3222       if (!CanNegateL && !CanNegateR)
3223         return false;
3224       // If we the result of the OR will be negated and we can naturally negate
3225       // the leafs, then this sub-tree as a whole negates naturally.
3226       CanNegate = WillNegate && CanNegateL && CanNegateR;
3227       // If we cannot naturally negate the whole sub-tree, then this must be
3228       // emitted first.
3229       MustBeFirst = !CanNegate;
3230     } else {
3231       assert(Opcode == ISD::AND && "Must be OR or AND");
3232       // We cannot naturally negate an AND operation.
3233       CanNegate = false;
3234       MustBeFirst = MustBeFirstL || MustBeFirstR;
3235     }
3236     return true;
3237   }
3238   return false;
3239 }
3240 
3241 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
3242 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
3243 /// Tries to transform the given i1 producing node @p Val to a series compare
3244 /// and conditional compare operations. @returns an NZCV flags producing node
3245 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
3246 /// transformation was not possible.
3247 /// \p Negate is true if we want this sub-tree being negated just by changing
3248 /// SETCC conditions.
3249 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
3250     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
3251     AArch64CC::CondCode Predicate) {
3252   // We're at a tree leaf, produce a conditional comparison operation.
3253   unsigned Opcode = Val->getOpcode();
3254   if (Opcode == ISD::SETCC) {
3255     SDValue LHS = Val->getOperand(0);
3256     SDValue RHS = Val->getOperand(1);
3257     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
3258     bool isInteger = LHS.getValueType().isInteger();
3259     if (Negate)
3260       CC = getSetCCInverse(CC, LHS.getValueType());
3261     SDLoc DL(Val);
3262     // Determine OutCC and handle FP special case.
3263     if (isInteger) {
3264       OutCC = changeIntCCToAArch64CC(CC);
3265     } else {
3266       assert(LHS.getValueType().isFloatingPoint());
3267       AArch64CC::CondCode ExtraCC;
3268       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
3269       // Some floating point conditions can't be tested with a single condition
3270       // code. Construct an additional comparison in this case.
3271       if (ExtraCC != AArch64CC::AL) {
3272         SDValue ExtraCmp;
3273         if (!CCOp.getNode())
3274           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
3275         else
3276           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
3277                                                ExtraCC, DL, DAG);
3278         CCOp = ExtraCmp;
3279         Predicate = ExtraCC;
3280       }
3281     }
3282 
3283     // Produce a normal comparison if we are first in the chain
3284     if (!CCOp)
3285       return emitComparison(LHS, RHS, CC, DL, DAG);
3286     // Otherwise produce a ccmp.
3287     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
3288                                      DAG);
3289   }
3290   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
3291 
3292   bool IsOR = Opcode == ISD::OR;
3293 
3294   SDValue LHS = Val->getOperand(0);
3295   bool CanNegateL;
3296   bool MustBeFirstL;
3297   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
3298   assert(ValidL && "Valid conjunction/disjunction tree");
3299   (void)ValidL;
3300 
3301   SDValue RHS = Val->getOperand(1);
3302   bool CanNegateR;
3303   bool MustBeFirstR;
3304   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
3305   assert(ValidR && "Valid conjunction/disjunction tree");
3306   (void)ValidR;
3307 
3308   // Swap sub-tree that must come first to the right side.
3309   if (MustBeFirstL) {
3310     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
3311     std::swap(LHS, RHS);
3312     std::swap(CanNegateL, CanNegateR);
3313     std::swap(MustBeFirstL, MustBeFirstR);
3314   }
3315 
3316   bool NegateR;
3317   bool NegateAfterR;
3318   bool NegateL;
3319   bool NegateAfterAll;
3320   if (Opcode == ISD::OR) {
3321     // Swap the sub-tree that we can negate naturally to the left.
3322     if (!CanNegateL) {
3323       assert(CanNegateR && "at least one side must be negatable");
3324       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
3325       assert(!Negate);
3326       std::swap(LHS, RHS);
3327       NegateR = false;
3328       NegateAfterR = true;
3329     } else {
3330       // Negate the left sub-tree if possible, otherwise negate the result.
3331       NegateR = CanNegateR;
3332       NegateAfterR = !CanNegateR;
3333     }
3334     NegateL = true;
3335     NegateAfterAll = !Negate;
3336   } else {
3337     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
3338     assert(!Negate && "Valid conjunction/disjunction tree");
3339 
3340     NegateL = false;
3341     NegateR = false;
3342     NegateAfterR = false;
3343     NegateAfterAll = false;
3344   }
3345 
3346   // Emit sub-trees.
3347   AArch64CC::CondCode RHSCC;
3348   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
3349   if (NegateAfterR)
3350     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
3351   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
3352   if (NegateAfterAll)
3353     OutCC = AArch64CC::getInvertedCondCode(OutCC);
3354   return CmpL;
3355 }
3356 
3357 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
3358 /// In some cases this is even possible with OR operations in the expression.
3359 /// See \ref AArch64CCMP.
3360 /// \see emitConjunctionRec().
3361 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
3362                                AArch64CC::CondCode &OutCC) {
3363   bool DummyCanNegate;
3364   bool DummyMustBeFirst;
3365   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
3366     return SDValue();
3367 
3368   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
3369 }
3370 
3371 /// @}
3372 
3373 /// Returns how profitable it is to fold a comparison's operand's shift and/or
3374 /// extension operations.
3375 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
3376   auto isSupportedExtend = [&](SDValue V) {
3377     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
3378       return true;
3379 
3380     if (V.getOpcode() == ISD::AND)
3381       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3382         uint64_t Mask = MaskCst->getZExtValue();
3383         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
3384       }
3385 
3386     return false;
3387   };
3388 
3389   if (!Op.hasOneUse())
3390     return 0;
3391 
3392   if (isSupportedExtend(Op))
3393     return 1;
3394 
3395   unsigned Opc = Op.getOpcode();
3396   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
3397     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3398       uint64_t Shift = ShiftCst->getZExtValue();
3399       if (isSupportedExtend(Op.getOperand(0)))
3400         return (Shift <= 4) ? 2 : 1;
3401       EVT VT = Op.getValueType();
3402       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
3403         return 1;
3404     }
3405 
3406   return 0;
3407 }
3408 
3409 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3410                              SDValue &AArch64cc, SelectionDAG &DAG,
3411                              const SDLoc &dl) {
3412   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3413     EVT VT = RHS.getValueType();
3414     uint64_t C = RHSC->getZExtValue();
3415     if (!isLegalArithImmed(C)) {
3416       // Constant does not fit, try adjusting it by one?
3417       switch (CC) {
3418       default:
3419         break;
3420       case ISD::SETLT:
3421       case ISD::SETGE:
3422         if ((VT == MVT::i32 && C != 0x80000000 &&
3423              isLegalArithImmed((uint32_t)(C - 1))) ||
3424             (VT == MVT::i64 && C != 0x80000000ULL &&
3425              isLegalArithImmed(C - 1ULL))) {
3426           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3427           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
3428           RHS = DAG.getConstant(C, dl, VT);
3429         }
3430         break;
3431       case ISD::SETULT:
3432       case ISD::SETUGE:
3433         if ((VT == MVT::i32 && C != 0 &&
3434              isLegalArithImmed((uint32_t)(C - 1))) ||
3435             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
3436           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3437           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
3438           RHS = DAG.getConstant(C, dl, VT);
3439         }
3440         break;
3441       case ISD::SETLE:
3442       case ISD::SETGT:
3443         if ((VT == MVT::i32 && C != INT32_MAX &&
3444              isLegalArithImmed((uint32_t)(C + 1))) ||
3445             (VT == MVT::i64 && C != INT64_MAX &&
3446              isLegalArithImmed(C + 1ULL))) {
3447           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3448           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
3449           RHS = DAG.getConstant(C, dl, VT);
3450         }
3451         break;
3452       case ISD::SETULE:
3453       case ISD::SETUGT:
3454         if ((VT == MVT::i32 && C != UINT32_MAX &&
3455              isLegalArithImmed((uint32_t)(C + 1))) ||
3456             (VT == MVT::i64 && C != UINT64_MAX &&
3457              isLegalArithImmed(C + 1ULL))) {
3458           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3459           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
3460           RHS = DAG.getConstant(C, dl, VT);
3461         }
3462         break;
3463       }
3464     }
3465   }
3466 
3467   // Comparisons are canonicalized so that the RHS operand is simpler than the
3468   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
3469   // can fold some shift+extend operations on the RHS operand, so swap the
3470   // operands if that can be done.
3471   //
3472   // For example:
3473   //    lsl     w13, w11, #1
3474   //    cmp     w13, w12
3475   // can be turned into:
3476   //    cmp     w12, w11, lsl #1
3477   if (!isa<ConstantSDNode>(RHS) ||
3478       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
3479     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
3480 
3481     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
3482       std::swap(LHS, RHS);
3483       CC = ISD::getSetCCSwappedOperands(CC);
3484     }
3485   }
3486 
3487   SDValue Cmp;
3488   AArch64CC::CondCode AArch64CC;
3489   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
3490     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
3491 
3492     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
3493     // For the i8 operand, the largest immediate is 255, so this can be easily
3494     // encoded in the compare instruction. For the i16 operand, however, the
3495     // largest immediate cannot be encoded in the compare.
3496     // Therefore, use a sign extending load and cmn to avoid materializing the
3497     // -1 constant. For example,
3498     // movz w1, #65535
3499     // ldrh w0, [x0, #0]
3500     // cmp w0, w1
3501     // >
3502     // ldrsh w0, [x0, #0]
3503     // cmn w0, #1
3504     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
3505     // if and only if (sext LHS) == (sext RHS). The checks are in place to
3506     // ensure both the LHS and RHS are truly zero extended and to make sure the
3507     // transformation is profitable.
3508     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
3509         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
3510         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
3511         LHS.getNode()->hasNUsesOfValue(1, 0)) {
3512       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
3513       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
3514         SDValue SExt =
3515             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
3516                         DAG.getValueType(MVT::i16));
3517         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
3518                                                    RHS.getValueType()),
3519                              CC, dl, DAG);
3520         AArch64CC = changeIntCCToAArch64CC(CC);
3521       }
3522     }
3523 
3524     if (!Cmp && (RHSC->isZero() || RHSC->isOne())) {
3525       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
3526         if ((CC == ISD::SETNE) ^ RHSC->isZero())
3527           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
3528       }
3529     }
3530   }
3531 
3532   if (!Cmp) {
3533     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3534     AArch64CC = changeIntCCToAArch64CC(CC);
3535   }
3536   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
3537   return Cmp;
3538 }
3539 
3540 static std::pair<SDValue, SDValue>
3541 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
3542   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
3543          "Unsupported value type");
3544   SDValue Value, Overflow;
3545   SDLoc DL(Op);
3546   SDValue LHS = Op.getOperand(0);
3547   SDValue RHS = Op.getOperand(1);
3548   unsigned Opc = 0;
3549   switch (Op.getOpcode()) {
3550   default:
3551     llvm_unreachable("Unknown overflow instruction!");
3552   case ISD::SADDO:
3553     Opc = AArch64ISD::ADDS;
3554     CC = AArch64CC::VS;
3555     break;
3556   case ISD::UADDO:
3557     Opc = AArch64ISD::ADDS;
3558     CC = AArch64CC::HS;
3559     break;
3560   case ISD::SSUBO:
3561     Opc = AArch64ISD::SUBS;
3562     CC = AArch64CC::VS;
3563     break;
3564   case ISD::USUBO:
3565     Opc = AArch64ISD::SUBS;
3566     CC = AArch64CC::LO;
3567     break;
3568   // Multiply needs a little bit extra work.
3569   case ISD::SMULO:
3570   case ISD::UMULO: {
3571     CC = AArch64CC::NE;
3572     bool IsSigned = Op.getOpcode() == ISD::SMULO;
3573     if (Op.getValueType() == MVT::i32) {
3574       // Extend to 64-bits, then perform a 64-bit multiply.
3575       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3576       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
3577       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
3578       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3579       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3580 
3581       // Check that the result fits into a 32-bit integer.
3582       SDVTList VTs = DAG.getVTList(MVT::i64, MVT_CC);
3583       if (IsSigned) {
3584         // cmp xreg, wreg, sxtw
3585         SDValue SExtMul = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Value);
3586         Overflow =
3587             DAG.getNode(AArch64ISD::SUBS, DL, VTs, Mul, SExtMul).getValue(1);
3588       } else {
3589         // tst xreg, #0xffffffff00000000
3590         SDValue UpperBits = DAG.getConstant(0xFFFFFFFF00000000, DL, MVT::i64);
3591         Overflow =
3592             DAG.getNode(AArch64ISD::ANDS, DL, VTs, Mul, UpperBits).getValue(1);
3593       }
3594       break;
3595     }
3596     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
3597     // For the 64 bit multiply
3598     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3599     if (IsSigned) {
3600       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
3601       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
3602                                       DAG.getConstant(63, DL, MVT::i64));
3603       // It is important that LowerBits is last, otherwise the arithmetic
3604       // shift will not be folded into the compare (SUBS).
3605       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3606       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
3607                      .getValue(1);
3608     } else {
3609       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
3610       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3611       Overflow =
3612           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
3613                       DAG.getConstant(0, DL, MVT::i64),
3614                       UpperBits).getValue(1);
3615     }
3616     break;
3617   }
3618   } // switch (...)
3619 
3620   if (Opc) {
3621     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
3622 
3623     // Emit the AArch64 operation with overflow check.
3624     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
3625     Overflow = Value.getValue(1);
3626   }
3627   return std::make_pair(Value, Overflow);
3628 }
3629 
3630 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
3631   if (useSVEForFixedLengthVectorVT(Op.getValueType(),
3632                                    !Subtarget->isNeonAvailable()))
3633     return LowerToScalableOp(Op, DAG);
3634 
3635   SDValue Sel = Op.getOperand(0);
3636   SDValue Other = Op.getOperand(1);
3637   SDLoc dl(Sel);
3638 
3639   // If the operand is an overflow checking operation, invert the condition
3640   // code and kill the Not operation. I.e., transform:
3641   // (xor (overflow_op_bool, 1))
3642   //   -->
3643   // (csel 1, 0, invert(cc), overflow_op_bool)
3644   // ... which later gets transformed to just a cset instruction with an
3645   // inverted condition code, rather than a cset + eor sequence.
3646   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
3647     // Only lower legal XALUO ops.
3648     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
3649       return SDValue();
3650 
3651     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3652     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3653     AArch64CC::CondCode CC;
3654     SDValue Value, Overflow;
3655     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
3656     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3657     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
3658                        CCVal, Overflow);
3659   }
3660   // If neither operand is a SELECT_CC, give up.
3661   if (Sel.getOpcode() != ISD::SELECT_CC)
3662     std::swap(Sel, Other);
3663   if (Sel.getOpcode() != ISD::SELECT_CC)
3664     return Op;
3665 
3666   // The folding we want to perform is:
3667   // (xor x, (select_cc a, b, cc, 0, -1) )
3668   //   -->
3669   // (csel x, (xor x, -1), cc ...)
3670   //
3671   // The latter will get matched to a CSINV instruction.
3672 
3673   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
3674   SDValue LHS = Sel.getOperand(0);
3675   SDValue RHS = Sel.getOperand(1);
3676   SDValue TVal = Sel.getOperand(2);
3677   SDValue FVal = Sel.getOperand(3);
3678 
3679   // FIXME: This could be generalized to non-integer comparisons.
3680   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
3681     return Op;
3682 
3683   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3684   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3685 
3686   // The values aren't constants, this isn't the pattern we're looking for.
3687   if (!CFVal || !CTVal)
3688     return Op;
3689 
3690   // We can commute the SELECT_CC by inverting the condition.  This
3691   // might be needed to make this fit into a CSINV pattern.
3692   if (CTVal->isAllOnes() && CFVal->isZero()) {
3693     std::swap(TVal, FVal);
3694     std::swap(CTVal, CFVal);
3695     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
3696   }
3697 
3698   // If the constants line up, perform the transform!
3699   if (CTVal->isZero() && CFVal->isAllOnes()) {
3700     SDValue CCVal;
3701     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3702 
3703     FVal = Other;
3704     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
3705                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
3706 
3707     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
3708                        CCVal, Cmp);
3709   }
3710 
3711   return Op;
3712 }
3713 
3714 // If Invert is false, sets 'C' bit of NZCV to 0 if value is 0, else sets 'C'
3715 // bit to 1. If Invert is true, sets 'C' bit of NZCV to 1 if value is 0, else
3716 // sets 'C' bit to 0.
3717 static SDValue valueToCarryFlag(SDValue Value, SelectionDAG &DAG, bool Invert) {
3718   SDLoc DL(Value);
3719   EVT VT = Value.getValueType();
3720   SDValue Op0 = Invert ? DAG.getConstant(0, DL, VT) : Value;
3721   SDValue Op1 = Invert ? Value : DAG.getConstant(1, DL, VT);
3722   SDValue Cmp =
3723       DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::Glue), Op0, Op1);
3724   return Cmp.getValue(1);
3725 }
3726 
3727 // If Invert is false, value is 1 if 'C' bit of NZCV is 1, else 0.
3728 // If Invert is true, value is 0 if 'C' bit of NZCV is 1, else 1.
3729 static SDValue carryFlagToValue(SDValue Glue, EVT VT, SelectionDAG &DAG,
3730                                 bool Invert) {
3731   assert(Glue.getResNo() == 1);
3732   SDLoc DL(Glue);
3733   SDValue Zero = DAG.getConstant(0, DL, VT);
3734   SDValue One = DAG.getConstant(1, DL, VT);
3735   unsigned Cond = Invert ? AArch64CC::LO : AArch64CC::HS;
3736   SDValue CC = DAG.getConstant(Cond, DL, MVT::i32);
3737   return DAG.getNode(AArch64ISD::CSEL, DL, VT, One, Zero, CC, Glue);
3738 }
3739 
3740 // Value is 1 if 'V' bit of NZCV is 1, else 0
3741 static SDValue overflowFlagToValue(SDValue Glue, EVT VT, SelectionDAG &DAG) {
3742   assert(Glue.getResNo() == 1);
3743   SDLoc DL(Glue);
3744   SDValue Zero = DAG.getConstant(0, DL, VT);
3745   SDValue One = DAG.getConstant(1, DL, VT);
3746   SDValue CC = DAG.getConstant(AArch64CC::VS, DL, MVT::i32);
3747   return DAG.getNode(AArch64ISD::CSEL, DL, VT, One, Zero, CC, Glue);
3748 }
3749 
3750 // This lowering is inefficient, but it will get cleaned up by
3751 // `foldOverflowCheck`
3752 static SDValue lowerADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG,
3753                                   unsigned Opcode, bool IsSigned) {
3754   EVT VT0 = Op.getValue(0).getValueType();
3755   EVT VT1 = Op.getValue(1).getValueType();
3756 
3757   if (VT0 != MVT::i32 && VT0 != MVT::i64)
3758     return SDValue();
3759 
3760   bool InvertCarry = Opcode == AArch64ISD::SBCS;
3761   SDValue OpLHS = Op.getOperand(0);
3762   SDValue OpRHS = Op.getOperand(1);
3763   SDValue OpCarryIn = valueToCarryFlag(Op.getOperand(2), DAG, InvertCarry);
3764 
3765   SDLoc DL(Op);
3766   SDVTList VTs = DAG.getVTList(VT0, VT1);
3767 
3768   SDValue Sum = DAG.getNode(Opcode, DL, DAG.getVTList(VT0, MVT::Glue), OpLHS,
3769                             OpRHS, OpCarryIn);
3770 
3771   SDValue OutFlag =
3772       IsSigned ? overflowFlagToValue(Sum.getValue(1), VT1, DAG)
3773                : carryFlagToValue(Sum.getValue(1), VT1, DAG, InvertCarry);
3774 
3775   return DAG.getNode(ISD::MERGE_VALUES, DL, VTs, Sum, OutFlag);
3776 }
3777 
3778 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
3779   // Let legalize expand this if it isn't a legal type yet.
3780   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3781     return SDValue();
3782 
3783   SDLoc dl(Op);
3784   AArch64CC::CondCode CC;
3785   // The actual operation that sets the overflow or carry flag.
3786   SDValue Value, Overflow;
3787   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
3788 
3789   // We use 0 and 1 as false and true values.
3790   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3791   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3792 
3793   // We use an inverted condition, because the conditional select is inverted
3794   // too. This will allow it to be selected to a single instruction:
3795   // CSINC Wd, WZR, WZR, invert(cond).
3796   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3797   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
3798                          CCVal, Overflow);
3799 
3800   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3801   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3802 }
3803 
3804 // Prefetch operands are:
3805 // 1: Address to prefetch
3806 // 2: bool isWrite
3807 // 3: int locality (0 = no locality ... 3 = extreme locality)
3808 // 4: bool isDataCache
3809 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
3810   SDLoc DL(Op);
3811   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3812   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
3813   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3814 
3815   bool IsStream = !Locality;
3816   // When the locality number is set
3817   if (Locality) {
3818     // The front-end should have filtered out the out-of-range values
3819     assert(Locality <= 3 && "Prefetch locality out-of-range");
3820     // The locality degree is the opposite of the cache speed.
3821     // Put the number the other way around.
3822     // The encoding starts at 0 for level 1
3823     Locality = 3 - Locality;
3824   }
3825 
3826   // built the mask value encoding the expected behavior.
3827   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
3828                    (!IsData << 3) |     // IsDataCache bit
3829                    (Locality << 1) |    // Cache level bits
3830                    (unsigned)IsStream;  // Stream bit
3831   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
3832                      DAG.getTargetConstant(PrfOp, DL, MVT::i32),
3833                      Op.getOperand(1));
3834 }
3835 
3836 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
3837                                               SelectionDAG &DAG) const {
3838   EVT VT = Op.getValueType();
3839   if (VT.isScalableVector())
3840     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
3841 
3842   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
3843     return LowerFixedLengthFPExtendToSVE(Op, DAG);
3844 
3845   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
3846   return SDValue();
3847 }
3848 
3849 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
3850                                              SelectionDAG &DAG) const {
3851   if (Op.getValueType().isScalableVector())
3852     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
3853 
3854   bool IsStrict = Op->isStrictFPOpcode();
3855   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3856   EVT SrcVT = SrcVal.getValueType();
3857 
3858   if (useSVEForFixedLengthVectorVT(SrcVT, !Subtarget->isNeonAvailable()))
3859     return LowerFixedLengthFPRoundToSVE(Op, DAG);
3860 
3861   if (SrcVT != MVT::f128) {
3862     // Expand cases where the input is a vector bigger than NEON.
3863     if (useSVEForFixedLengthVectorVT(SrcVT))
3864       return SDValue();
3865 
3866     // It's legal except when f128 is involved
3867     return Op;
3868   }
3869 
3870   return SDValue();
3871 }
3872 
3873 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
3874                                                     SelectionDAG &DAG) const {
3875   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3876   // Any additional optimization in this function should be recorded
3877   // in the cost tables.
3878   bool IsStrict = Op->isStrictFPOpcode();
3879   EVT InVT = Op.getOperand(IsStrict ? 1 : 0).getValueType();
3880   EVT VT = Op.getValueType();
3881 
3882   if (VT.isScalableVector()) {
3883     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3884                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3885                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3886     return LowerToPredicatedOp(Op, DAG, Opcode);
3887   }
3888 
3889   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()) ||
3890       useSVEForFixedLengthVectorVT(InVT, !Subtarget->isNeonAvailable()))
3891     return LowerFixedLengthFPToIntToSVE(Op, DAG);
3892 
3893   unsigned NumElts = InVT.getVectorNumElements();
3894 
3895   // f16 conversions are promoted to f32 when full fp16 is not supported.
3896   if (InVT.getVectorElementType() == MVT::f16 &&
3897       !Subtarget->hasFullFP16()) {
3898     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3899     SDLoc dl(Op);
3900     if (IsStrict) {
3901       SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NewVT, MVT::Other},
3902                                 {Op.getOperand(0), Op.getOperand(1)});
3903       return DAG.getNode(Op.getOpcode(), dl, {VT, MVT::Other},
3904                          {Ext.getValue(1), Ext.getValue(0)});
3905     }
3906     return DAG.getNode(
3907         Op.getOpcode(), dl, Op.getValueType(),
3908         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3909   }
3910 
3911   uint64_t VTSize = VT.getFixedSizeInBits();
3912   uint64_t InVTSize = InVT.getFixedSizeInBits();
3913   if (VTSize < InVTSize) {
3914     SDLoc dl(Op);
3915     if (IsStrict) {
3916       InVT = InVT.changeVectorElementTypeToInteger();
3917       SDValue Cv = DAG.getNode(Op.getOpcode(), dl, {InVT, MVT::Other},
3918                                {Op.getOperand(0), Op.getOperand(1)});
3919       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3920       return DAG.getMergeValues({Trunc, Cv.getValue(1)}, dl);
3921     }
3922     SDValue Cv =
3923         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3924                     Op.getOperand(0));
3925     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3926   }
3927 
3928   if (VTSize > InVTSize) {
3929     SDLoc dl(Op);
3930     MVT ExtVT =
3931         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3932                          VT.getVectorNumElements());
3933     if (IsStrict) {
3934       SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {ExtVT, MVT::Other},
3935                                 {Op.getOperand(0), Op.getOperand(1)});
3936       return DAG.getNode(Op.getOpcode(), dl, {VT, MVT::Other},
3937                          {Ext.getValue(1), Ext.getValue(0)});
3938     }
3939     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3940     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3941   }
3942 
3943   // Use a scalar operation for conversions between single-element vectors of
3944   // the same size.
3945   if (NumElts == 1) {
3946     SDLoc dl(Op);
3947     SDValue Extract = DAG.getNode(
3948         ISD::EXTRACT_VECTOR_ELT, dl, InVT.getScalarType(),
3949         Op.getOperand(IsStrict ? 1 : 0), DAG.getConstant(0, dl, MVT::i64));
3950     EVT ScalarVT = VT.getScalarType();
3951     if (IsStrict)
3952       return DAG.getNode(Op.getOpcode(), dl, {ScalarVT, MVT::Other},
3953                          {Op.getOperand(0), Extract});
3954     return DAG.getNode(Op.getOpcode(), dl, ScalarVT, Extract);
3955   }
3956 
3957   // Type changing conversions are illegal.
3958   return Op;
3959 }
3960 
3961 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3962                                               SelectionDAG &DAG) const {
3963   bool IsStrict = Op->isStrictFPOpcode();
3964   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3965 
3966   if (SrcVal.getValueType().isVector())
3967     return LowerVectorFP_TO_INT(Op, DAG);
3968 
3969   // f16 conversions are promoted to f32 when full fp16 is not supported.
3970   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3971     SDLoc dl(Op);
3972     if (IsStrict) {
3973       SDValue Ext =
3974           DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f32, MVT::Other},
3975                       {Op.getOperand(0), SrcVal});
3976       return DAG.getNode(Op.getOpcode(), dl, {Op.getValueType(), MVT::Other},
3977                          {Ext.getValue(1), Ext.getValue(0)});
3978     }
3979     return DAG.getNode(
3980         Op.getOpcode(), dl, Op.getValueType(),
3981         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3982   }
3983 
3984   if (SrcVal.getValueType() != MVT::f128) {
3985     // It's legal except when f128 is involved
3986     return Op;
3987   }
3988 
3989   return SDValue();
3990 }
3991 
3992 SDValue
3993 AArch64TargetLowering::LowerVectorFP_TO_INT_SAT(SDValue Op,
3994                                                 SelectionDAG &DAG) const {
3995   // AArch64 FP-to-int conversions saturate to the destination element size, so
3996   // we can lower common saturating conversions to simple instructions.
3997   SDValue SrcVal = Op.getOperand(0);
3998   EVT SrcVT = SrcVal.getValueType();
3999   EVT DstVT = Op.getValueType();
4000   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4001 
4002   uint64_t SrcElementWidth = SrcVT.getScalarSizeInBits();
4003   uint64_t DstElementWidth = DstVT.getScalarSizeInBits();
4004   uint64_t SatWidth = SatVT.getScalarSizeInBits();
4005   assert(SatWidth <= DstElementWidth &&
4006          "Saturation width cannot exceed result width");
4007 
4008   // TODO: Consider lowering to SVE operations, as in LowerVectorFP_TO_INT.
4009   // Currently, the `llvm.fpto[su]i.sat.*` intrinsics don't accept scalable
4010   // types, so this is hard to reach.
4011   if (DstVT.isScalableVector())
4012     return SDValue();
4013 
4014   EVT SrcElementVT = SrcVT.getVectorElementType();
4015 
4016   // In the absence of FP16 support, promote f16 to f32 and saturate the result.
4017   if (SrcElementVT == MVT::f16 &&
4018       (!Subtarget->hasFullFP16() || DstElementWidth > 16)) {
4019     MVT F32VT = MVT::getVectorVT(MVT::f32, SrcVT.getVectorNumElements());
4020     SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), F32VT, SrcVal);
4021     SrcVT = F32VT;
4022     SrcElementVT = MVT::f32;
4023     SrcElementWidth = 32;
4024   } else if (SrcElementVT != MVT::f64 && SrcElementVT != MVT::f32 &&
4025              SrcElementVT != MVT::f16)
4026     return SDValue();
4027 
4028   SDLoc DL(Op);
4029   // Cases that we can emit directly.
4030   if (SrcElementWidth == DstElementWidth && SrcElementWidth == SatWidth)
4031     return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
4032                        DAG.getValueType(DstVT.getScalarType()));
4033 
4034   // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
4035   // result. This is only valid if the legal cvt is larger than the saturate
4036   // width. For double, as we don't have MIN/MAX, it can be simpler to scalarize
4037   // (at least until sqxtn is selected).
4038   if (SrcElementWidth < SatWidth || SrcElementVT == MVT::f64)
4039     return SDValue();
4040 
4041   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
4042   SDValue NativeCvt = DAG.getNode(Op.getOpcode(), DL, IntVT, SrcVal,
4043                                   DAG.getValueType(IntVT.getScalarType()));
4044   SDValue Sat;
4045   if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
4046     SDValue MinC = DAG.getConstant(
4047         APInt::getSignedMaxValue(SatWidth).sext(SrcElementWidth), DL, IntVT);
4048     SDValue Min = DAG.getNode(ISD::SMIN, DL, IntVT, NativeCvt, MinC);
4049     SDValue MaxC = DAG.getConstant(
4050         APInt::getSignedMinValue(SatWidth).sext(SrcElementWidth), DL, IntVT);
4051     Sat = DAG.getNode(ISD::SMAX, DL, IntVT, Min, MaxC);
4052   } else {
4053     SDValue MinC = DAG.getConstant(
4054         APInt::getAllOnes(SatWidth).zext(SrcElementWidth), DL, IntVT);
4055     Sat = DAG.getNode(ISD::UMIN, DL, IntVT, NativeCvt, MinC);
4056   }
4057 
4058   return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
4059 }
4060 
4061 SDValue AArch64TargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
4062                                                   SelectionDAG &DAG) const {
4063   // AArch64 FP-to-int conversions saturate to the destination register size, so
4064   // we can lower common saturating conversions to simple instructions.
4065   SDValue SrcVal = Op.getOperand(0);
4066   EVT SrcVT = SrcVal.getValueType();
4067 
4068   if (SrcVT.isVector())
4069     return LowerVectorFP_TO_INT_SAT(Op, DAG);
4070 
4071   EVT DstVT = Op.getValueType();
4072   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4073   uint64_t SatWidth = SatVT.getScalarSizeInBits();
4074   uint64_t DstWidth = DstVT.getScalarSizeInBits();
4075   assert(SatWidth <= DstWidth && "Saturation width cannot exceed result width");
4076 
4077   // In the absence of FP16 support, promote f16 to f32 and saturate the result.
4078   if (SrcVT == MVT::f16 && !Subtarget->hasFullFP16()) {
4079     SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, SrcVal);
4080     SrcVT = MVT::f32;
4081   } else if (SrcVT != MVT::f64 && SrcVT != MVT::f32 && SrcVT != MVT::f16)
4082     return SDValue();
4083 
4084   SDLoc DL(Op);
4085   // Cases that we can emit directly.
4086   if ((SrcVT == MVT::f64 || SrcVT == MVT::f32 ||
4087        (SrcVT == MVT::f16 && Subtarget->hasFullFP16())) &&
4088       DstVT == SatVT && (DstVT == MVT::i64 || DstVT == MVT::i32))
4089     return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
4090                        DAG.getValueType(DstVT));
4091 
4092   // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
4093   // result. This is only valid if the legal cvt is larger than the saturate
4094   // width.
4095   if (DstWidth < SatWidth)
4096     return SDValue();
4097 
4098   SDValue NativeCvt =
4099       DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal, DAG.getValueType(DstVT));
4100   SDValue Sat;
4101   if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
4102     SDValue MinC = DAG.getConstant(
4103         APInt::getSignedMaxValue(SatWidth).sext(DstWidth), DL, DstVT);
4104     SDValue Min = DAG.getNode(ISD::SMIN, DL, DstVT, NativeCvt, MinC);
4105     SDValue MaxC = DAG.getConstant(
4106         APInt::getSignedMinValue(SatWidth).sext(DstWidth), DL, DstVT);
4107     Sat = DAG.getNode(ISD::SMAX, DL, DstVT, Min, MaxC);
4108   } else {
4109     SDValue MinC = DAG.getConstant(
4110         APInt::getAllOnes(SatWidth).zext(DstWidth), DL, DstVT);
4111     Sat = DAG.getNode(ISD::UMIN, DL, DstVT, NativeCvt, MinC);
4112   }
4113 
4114   return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
4115 }
4116 
4117 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
4118                                                     SelectionDAG &DAG) const {
4119   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
4120   // Any additional optimization in this function should be recorded
4121   // in the cost tables.
4122   bool IsStrict = Op->isStrictFPOpcode();
4123   EVT VT = Op.getValueType();
4124   SDLoc dl(Op);
4125   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
4126   EVT InVT = In.getValueType();
4127   unsigned Opc = Op.getOpcode();
4128   bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
4129 
4130   if (VT.isScalableVector()) {
4131     if (InVT.getVectorElementType() == MVT::i1) {
4132       // We can't directly extend an SVE predicate; extend it first.
4133       unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4134       EVT CastVT = getPromotedVTForPredicate(InVT);
4135       In = DAG.getNode(CastOpc, dl, CastVT, In);
4136       return DAG.getNode(Opc, dl, VT, In);
4137     }
4138 
4139     unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
4140                                : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
4141     return LowerToPredicatedOp(Op, DAG, Opcode);
4142   }
4143 
4144   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()) ||
4145       useSVEForFixedLengthVectorVT(InVT, !Subtarget->isNeonAvailable()))
4146     return LowerFixedLengthIntToFPToSVE(Op, DAG);
4147 
4148   uint64_t VTSize = VT.getFixedSizeInBits();
4149   uint64_t InVTSize = InVT.getFixedSizeInBits();
4150   if (VTSize < InVTSize) {
4151     MVT CastVT =
4152         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
4153                          InVT.getVectorNumElements());
4154     if (IsStrict) {
4155       In = DAG.getNode(Opc, dl, {CastVT, MVT::Other},
4156                        {Op.getOperand(0), In});
4157       return DAG.getNode(
4158           ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
4159           {In.getValue(1), In.getValue(0), DAG.getIntPtrConstant(0, dl)});
4160     }
4161     In = DAG.getNode(Opc, dl, CastVT, In);
4162     return DAG.getNode(ISD::FP_ROUND, dl, VT, In,
4163                        DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
4164   }
4165 
4166   if (VTSize > InVTSize) {
4167     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4168     EVT CastVT = VT.changeVectorElementTypeToInteger();
4169     In = DAG.getNode(CastOpc, dl, CastVT, In);
4170     if (IsStrict)
4171       return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op.getOperand(0), In});
4172     return DAG.getNode(Opc, dl, VT, In);
4173   }
4174 
4175   // Use a scalar operation for conversions between single-element vectors of
4176   // the same size.
4177   if (VT.getVectorNumElements() == 1) {
4178     SDValue Extract = DAG.getNode(
4179         ISD::EXTRACT_VECTOR_ELT, dl, InVT.getScalarType(),
4180         In, DAG.getConstant(0, dl, MVT::i64));
4181     EVT ScalarVT = VT.getScalarType();
4182     if (IsStrict)
4183       return DAG.getNode(Op.getOpcode(), dl, {ScalarVT, MVT::Other},
4184                          {Op.getOperand(0), Extract});
4185     return DAG.getNode(Op.getOpcode(), dl, ScalarVT, Extract);
4186   }
4187 
4188   return Op;
4189 }
4190 
4191 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
4192                                             SelectionDAG &DAG) const {
4193   if (Op.getValueType().isVector())
4194     return LowerVectorINT_TO_FP(Op, DAG);
4195 
4196   bool IsStrict = Op->isStrictFPOpcode();
4197   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
4198 
4199   // f16 conversions are promoted to f32 when full fp16 is not supported.
4200   if (Op.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4201     SDLoc dl(Op);
4202     if (IsStrict) {
4203       SDValue Val = DAG.getNode(Op.getOpcode(), dl, {MVT::f32, MVT::Other},
4204                                 {Op.getOperand(0), SrcVal});
4205       return DAG.getNode(
4206           ISD::STRICT_FP_ROUND, dl, {MVT::f16, MVT::Other},
4207           {Val.getValue(1), Val.getValue(0), DAG.getIntPtrConstant(0, dl)});
4208     }
4209     return DAG.getNode(
4210         ISD::FP_ROUND, dl, MVT::f16,
4211         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
4212         DAG.getIntPtrConstant(0, dl));
4213   }
4214 
4215   // i128 conversions are libcalls.
4216   if (SrcVal.getValueType() == MVT::i128)
4217     return SDValue();
4218 
4219   // Other conversions are legal, unless it's to the completely software-based
4220   // fp128.
4221   if (Op.getValueType() != MVT::f128)
4222     return Op;
4223   return SDValue();
4224 }
4225 
4226 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
4227                                             SelectionDAG &DAG) const {
4228   // For iOS, we want to call an alternative entry point: __sincos_stret,
4229   // which returns the values in two S / D registers.
4230   SDLoc dl(Op);
4231   SDValue Arg = Op.getOperand(0);
4232   EVT ArgVT = Arg.getValueType();
4233   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
4234 
4235   ArgListTy Args;
4236   ArgListEntry Entry;
4237 
4238   Entry.Node = Arg;
4239   Entry.Ty = ArgTy;
4240   Entry.IsSExt = false;
4241   Entry.IsZExt = false;
4242   Args.push_back(Entry);
4243 
4244   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
4245                                         : RTLIB::SINCOS_STRET_F32;
4246   const char *LibcallName = getLibcallName(LC);
4247   SDValue Callee =
4248       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
4249 
4250   StructType *RetTy = StructType::get(ArgTy, ArgTy);
4251   TargetLowering::CallLoweringInfo CLI(DAG);
4252   CLI.setDebugLoc(dl)
4253       .setChain(DAG.getEntryNode())
4254       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
4255 
4256   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
4257   return CallResult.first;
4258 }
4259 
4260 static MVT getSVEContainerType(EVT ContentTy);
4261 
4262 SDValue AArch64TargetLowering::LowerBITCAST(SDValue Op,
4263                                             SelectionDAG &DAG) const {
4264   EVT OpVT = Op.getValueType();
4265   EVT ArgVT = Op.getOperand(0).getValueType();
4266 
4267   if (useSVEForFixedLengthVectorVT(OpVT))
4268     return LowerFixedLengthBitcastToSVE(Op, DAG);
4269 
4270   if (OpVT.isScalableVector()) {
4271     // Bitcasting between unpacked vector types of different element counts is
4272     // not a NOP because the live elements are laid out differently.
4273     //                01234567
4274     // e.g. nxv2i32 = XX??XX??
4275     //      nxv4f16 = X?X?X?X?
4276     if (OpVT.getVectorElementCount() != ArgVT.getVectorElementCount())
4277       return SDValue();
4278 
4279     if (isTypeLegal(OpVT) && !isTypeLegal(ArgVT)) {
4280       assert(OpVT.isFloatingPoint() && !ArgVT.isFloatingPoint() &&
4281              "Expected int->fp bitcast!");
4282       SDValue ExtResult =
4283           DAG.getNode(ISD::ANY_EXTEND, SDLoc(Op), getSVEContainerType(ArgVT),
4284                       Op.getOperand(0));
4285       return getSVESafeBitCast(OpVT, ExtResult, DAG);
4286     }
4287     return getSVESafeBitCast(OpVT, Op.getOperand(0), DAG);
4288   }
4289 
4290   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
4291     return SDValue();
4292 
4293   // Bitcasts between f16 and bf16 are legal.
4294   if (ArgVT == MVT::f16 || ArgVT == MVT::bf16)
4295     return Op;
4296 
4297   assert(ArgVT == MVT::i16);
4298   SDLoc DL(Op);
4299 
4300   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
4301   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
4302   return DAG.getTargetExtractSubreg(AArch64::hsub, DL, OpVT, Op);
4303 }
4304 
4305 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
4306   if (OrigVT.getSizeInBits() >= 64)
4307     return OrigVT;
4308 
4309   assert(OrigVT.isSimple() && "Expecting a simple value type");
4310 
4311   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
4312   switch (OrigSimpleTy) {
4313   default: llvm_unreachable("Unexpected Vector Type");
4314   case MVT::v2i8:
4315   case MVT::v2i16:
4316      return MVT::v2i32;
4317   case MVT::v4i8:
4318     return  MVT::v4i16;
4319   }
4320 }
4321 
4322 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
4323                                                  const EVT &OrigTy,
4324                                                  const EVT &ExtTy,
4325                                                  unsigned ExtOpcode) {
4326   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
4327   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
4328   // 64-bits we need to insert a new extension so that it will be 64-bits.
4329   assert(ExtTy.is128BitVector() && "Unexpected extension size");
4330   if (OrigTy.getSizeInBits() >= 64)
4331     return N;
4332 
4333   // Must extend size to at least 64 bits to be used as an operand for VMULL.
4334   EVT NewVT = getExtensionTo64Bits(OrigTy);
4335 
4336   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
4337 }
4338 
4339 // Returns lane if Op extracts from a two-element vector and lane is constant
4340 // (i.e., extractelt(<2 x Ty> %v, ConstantLane)), and std::nullopt otherwise.
4341 static std::optional<uint64_t>
4342 getConstantLaneNumOfExtractHalfOperand(SDValue &Op) {
4343   SDNode *OpNode = Op.getNode();
4344   if (OpNode->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
4345     return std::nullopt;
4346 
4347   EVT VT = OpNode->getOperand(0).getValueType();
4348   ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpNode->getOperand(1));
4349   if (!VT.isFixedLengthVector() || VT.getVectorNumElements() != 2 || !C)
4350     return std::nullopt;
4351 
4352   return C->getZExtValue();
4353 }
4354 
4355 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4356                                    bool isSigned) {
4357   EVT VT = N->getValueType(0);
4358 
4359   if (N->getOpcode() != ISD::BUILD_VECTOR)
4360     return false;
4361 
4362   for (const SDValue &Elt : N->op_values()) {
4363     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4364       unsigned EltSize = VT.getScalarSizeInBits();
4365       unsigned HalfSize = EltSize / 2;
4366       if (isSigned) {
4367         if (!isIntN(HalfSize, C->getSExtValue()))
4368           return false;
4369       } else {
4370         if (!isUIntN(HalfSize, C->getZExtValue()))
4371           return false;
4372       }
4373       continue;
4374     }
4375     return false;
4376   }
4377 
4378   return true;
4379 }
4380 
4381 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
4382   if (ISD::isExtOpcode(N->getOpcode()))
4383     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
4384                                              N->getOperand(0)->getValueType(0),
4385                                              N->getValueType(0),
4386                                              N->getOpcode());
4387 
4388   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4389   EVT VT = N->getValueType(0);
4390   SDLoc dl(N);
4391   unsigned EltSize = VT.getScalarSizeInBits() / 2;
4392   unsigned NumElts = VT.getVectorNumElements();
4393   MVT TruncVT = MVT::getIntegerVT(EltSize);
4394   SmallVector<SDValue, 8> Ops;
4395   for (unsigned i = 0; i != NumElts; ++i) {
4396     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4397     const APInt &CInt = C->getAPIntValue();
4398     // Element types smaller than 32 bits are not legal, so use i32 elements.
4399     // The values are implicitly truncated so sext vs. zext doesn't matter.
4400     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
4401   }
4402   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
4403 }
4404 
4405 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4406   return N->getOpcode() == ISD::SIGN_EXTEND ||
4407          N->getOpcode() == ISD::ANY_EXTEND ||
4408          isExtendedBUILD_VECTOR(N, DAG, true);
4409 }
4410 
4411 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4412   return N->getOpcode() == ISD::ZERO_EXTEND ||
4413          N->getOpcode() == ISD::ANY_EXTEND ||
4414          isExtendedBUILD_VECTOR(N, DAG, false);
4415 }
4416 
4417 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4418   unsigned Opcode = N->getOpcode();
4419   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4420     SDNode *N0 = N->getOperand(0).getNode();
4421     SDNode *N1 = N->getOperand(1).getNode();
4422     return N0->hasOneUse() && N1->hasOneUse() &&
4423       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4424   }
4425   return false;
4426 }
4427 
4428 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4429   unsigned Opcode = N->getOpcode();
4430   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4431     SDNode *N0 = N->getOperand(0).getNode();
4432     SDNode *N1 = N->getOperand(1).getNode();
4433     return N0->hasOneUse() && N1->hasOneUse() &&
4434       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4435   }
4436   return false;
4437 }
4438 
4439 SDValue AArch64TargetLowering::LowerGET_ROUNDING(SDValue Op,
4440                                                  SelectionDAG &DAG) const {
4441   // The rounding mode is in bits 23:22 of the FPSCR.
4442   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4443   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4444   // so that the shift + and get folded into a bitfield extract.
4445   SDLoc dl(Op);
4446 
4447   SDValue Chain = Op.getOperand(0);
4448   SDValue FPCR_64 = DAG.getNode(
4449       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
4450       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
4451   Chain = FPCR_64.getValue(1);
4452   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
4453   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
4454                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4455   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4456                               DAG.getConstant(22, dl, MVT::i32));
4457   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4458                             DAG.getConstant(3, dl, MVT::i32));
4459   return DAG.getMergeValues({AND, Chain}, dl);
4460 }
4461 
4462 SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op,
4463                                                  SelectionDAG &DAG) const {
4464   SDLoc DL(Op);
4465   SDValue Chain = Op->getOperand(0);
4466   SDValue RMValue = Op->getOperand(1);
4467 
4468   // The rounding mode is in bits 23:22 of the FPCR.
4469   // The llvm.set.rounding argument value to the rounding mode in FPCR mapping
4470   // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
4471   // ((arg - 1) & 3) << 22).
4472   //
4473   // The argument of llvm.set.rounding must be within the segment [0, 3], so
4474   // NearestTiesToAway (4) is not handled here. It is responsibility of the code
4475   // generated llvm.set.rounding to ensure this condition.
4476 
4477   // Calculate new value of FPCR[23:22].
4478   RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
4479                         DAG.getConstant(1, DL, MVT::i32));
4480   RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
4481                         DAG.getConstant(0x3, DL, MVT::i32));
4482   RMValue =
4483       DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
4484                   DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32));
4485   RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue);
4486 
4487   // Get current value of FPCR.
4488   SDValue Ops[] = {
4489       Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)};
4490   SDValue FPCR =
4491       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops);
4492   Chain = FPCR.getValue(1);
4493   FPCR = FPCR.getValue(0);
4494 
4495   // Put new rounding mode into FPSCR[23:22].
4496   const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos);
4497   FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR,
4498                      DAG.getConstant(RMMask, DL, MVT::i64));
4499   FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue);
4500   SDValue Ops2[] = {
4501       Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64),
4502       FPCR};
4503   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
4504 }
4505 
4506 static unsigned selectUmullSmull(SDNode *&N0, SDNode *&N1, SelectionDAG &DAG,
4507                                  SDLoc DL, bool &IsMLA) {
4508   bool IsN0SExt = isSignExtended(N0, DAG);
4509   bool IsN1SExt = isSignExtended(N1, DAG);
4510   if (IsN0SExt && IsN1SExt)
4511     return AArch64ISD::SMULL;
4512 
4513   bool IsN0ZExt = isZeroExtended(N0, DAG);
4514   bool IsN1ZExt = isZeroExtended(N1, DAG);
4515 
4516   if (IsN0ZExt && IsN1ZExt)
4517     return AArch64ISD::UMULL;
4518 
4519   // Select SMULL if we can replace zext with sext.
4520   if (((IsN0SExt && IsN1ZExt) || (IsN0ZExt && IsN1SExt)) &&
4521       !isExtendedBUILD_VECTOR(N0, DAG, false) &&
4522       !isExtendedBUILD_VECTOR(N1, DAG, false)) {
4523     SDValue ZextOperand;
4524     if (IsN0ZExt)
4525       ZextOperand = N0->getOperand(0);
4526     else
4527       ZextOperand = N1->getOperand(0);
4528     if (DAG.SignBitIsZero(ZextOperand)) {
4529       SDNode *NewSext =
4530           DAG.getSExtOrTrunc(ZextOperand, DL, N0->getValueType(0)).getNode();
4531       if (IsN0ZExt)
4532         N0 = NewSext;
4533       else
4534         N1 = NewSext;
4535       return AArch64ISD::SMULL;
4536     }
4537   }
4538 
4539   // Select UMULL if we can replace the other operand with an extend.
4540   if (IsN0ZExt || IsN1ZExt) {
4541     EVT VT = N0->getValueType(0);
4542     APInt Mask = APInt::getHighBitsSet(VT.getScalarSizeInBits(),
4543                                        VT.getScalarSizeInBits() / 2);
4544     if (DAG.MaskedValueIsZero(SDValue(IsN0ZExt ? N1 : N0, 0), Mask)) {
4545       EVT HalfVT;
4546       switch (VT.getSimpleVT().SimpleTy) {
4547       case MVT::v2i64:
4548         HalfVT = MVT::v2i32;
4549         break;
4550       case MVT::v4i32:
4551         HalfVT = MVT::v4i16;
4552         break;
4553       case MVT::v8i16:
4554         HalfVT = MVT::v8i8;
4555         break;
4556       default:
4557         return 0;
4558       }
4559       // Truncate and then extend the result.
4560       SDValue NewExt = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
4561                                    SDValue(IsN0ZExt ? N1 : N0, 0));
4562       NewExt = DAG.getZExtOrTrunc(NewExt, DL, VT);
4563       if (IsN0ZExt)
4564         N1 = NewExt.getNode();
4565       else
4566         N0 = NewExt.getNode();
4567       return AArch64ISD::UMULL;
4568     }
4569   }
4570 
4571   if (!IsN1SExt && !IsN1ZExt)
4572     return 0;
4573 
4574   // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4575   // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4576   if (IsN1SExt && isAddSubSExt(N0, DAG)) {
4577     IsMLA = true;
4578     return AArch64ISD::SMULL;
4579   }
4580   if (IsN1ZExt && isAddSubZExt(N0, DAG)) {
4581     IsMLA = true;
4582     return AArch64ISD::UMULL;
4583   }
4584   if (IsN0ZExt && isAddSubZExt(N1, DAG)) {
4585     std::swap(N0, N1);
4586     IsMLA = true;
4587     return AArch64ISD::UMULL;
4588   }
4589   return 0;
4590 }
4591 
4592 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
4593   EVT VT = Op.getValueType();
4594 
4595   bool OverrideNEON = !Subtarget->isNeonAvailable();
4596   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
4597     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED);
4598 
4599   // Multiplications are only custom-lowered for 128-bit and 64-bit vectors so
4600   // that VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4601   assert((VT.is128BitVector() || VT.is64BitVector()) && VT.isInteger() &&
4602          "unexpected type for custom-lowering ISD::MUL");
4603   SDNode *N0 = Op.getOperand(0).getNode();
4604   SDNode *N1 = Op.getOperand(1).getNode();
4605   bool isMLA = false;
4606   EVT OVT = VT;
4607   if (VT.is64BitVector()) {
4608     if (N0->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4609         isNullConstant(N0->getOperand(1)) &&
4610         N1->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4611         isNullConstant(N1->getOperand(1))) {
4612       N0 = N0->getOperand(0).getNode();
4613       N1 = N1->getOperand(0).getNode();
4614       VT = N0->getValueType(0);
4615     } else {
4616       if (VT == MVT::v1i64) {
4617         if (Subtarget->hasSVE())
4618           return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED);
4619         // Fall through to expand this.  It is not legal.
4620         return SDValue();
4621       } else
4622         // Other vector multiplications are legal.
4623         return Op;
4624     }
4625   }
4626 
4627   SDLoc DL(Op);
4628   unsigned NewOpc = selectUmullSmull(N0, N1, DAG, DL, isMLA);
4629 
4630   if (!NewOpc) {
4631     if (VT.getVectorElementType() == MVT::i64) {
4632       // If SVE is available then i64 vector multiplications can also be made
4633       // legal.
4634       if (Subtarget->hasSVE())
4635         return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED);
4636       // Fall through to expand this.  It is not legal.
4637       return SDValue();
4638     } else
4639       // Other vector multiplications are legal.
4640       return Op;
4641   }
4642 
4643   // Legalize to a S/UMULL instruction
4644   SDValue Op0;
4645   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
4646   if (!isMLA) {
4647     Op0 = skipExtensionForVectorMULL(N0, DAG);
4648     assert(Op0.getValueType().is64BitVector() &&
4649            Op1.getValueType().is64BitVector() &&
4650            "unexpected types for extended operands to VMULL");
4651     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OVT,
4652                        DAG.getNode(NewOpc, DL, VT, Op0, Op1),
4653                        DAG.getConstant(0, DL, MVT::i64));
4654   }
4655   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
4656   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
4657   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
4658   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
4659   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
4660   EVT Op1VT = Op1.getValueType();
4661   return DAG.getNode(
4662       ISD::EXTRACT_SUBVECTOR, DL, OVT,
4663       DAG.getNode(N0->getOpcode(), DL, VT,
4664                   DAG.getNode(NewOpc, DL, VT,
4665                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4666                   DAG.getNode(NewOpc, DL, VT,
4667                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)),
4668       DAG.getConstant(0, DL, MVT::i64));
4669 }
4670 
4671 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
4672                                int Pattern) {
4673   if (VT == MVT::nxv1i1 && Pattern == AArch64SVEPredPattern::all)
4674     return DAG.getConstant(1, DL, MVT::nxv1i1);
4675   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
4676                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
4677 }
4678 
4679 static SDValue optimizeWhile(SDValue Op, SelectionDAG &DAG, bool IsSigned,
4680                              bool IsLess, bool IsEqual) {
4681   if (!isa<ConstantSDNode>(Op.getOperand(1)) ||
4682       !isa<ConstantSDNode>(Op.getOperand(2)))
4683     return SDValue();
4684 
4685   SDLoc dl(Op);
4686   APInt X = Op.getConstantOperandAPInt(1);
4687   APInt Y = Op.getConstantOperandAPInt(2);
4688   APInt NumActiveElems;
4689   bool Overflow;
4690   if (IsLess)
4691     NumActiveElems = IsSigned ? Y.ssub_ov(X, Overflow) : Y.usub_ov(X, Overflow);
4692   else
4693     NumActiveElems = IsSigned ? X.ssub_ov(Y, Overflow) : X.usub_ov(Y, Overflow);
4694 
4695   if (Overflow)
4696     return SDValue();
4697 
4698   if (IsEqual) {
4699     APInt One(NumActiveElems.getBitWidth(), 1, IsSigned);
4700     NumActiveElems = IsSigned ? NumActiveElems.sadd_ov(One, Overflow)
4701                               : NumActiveElems.uadd_ov(One, Overflow);
4702     if (Overflow)
4703       return SDValue();
4704   }
4705 
4706   std::optional<unsigned> PredPattern =
4707       getSVEPredPatternFromNumElements(NumActiveElems.getZExtValue());
4708   unsigned MinSVEVectorSize = std::max(
4709       DAG.getSubtarget<AArch64Subtarget>().getMinSVEVectorSizeInBits(), 128u);
4710   unsigned ElementSize = 128 / Op.getValueType().getVectorMinNumElements();
4711   if (PredPattern != std::nullopt &&
4712       NumActiveElems.getZExtValue() <= (MinSVEVectorSize / ElementSize))
4713     return getPTrue(DAG, dl, Op.getValueType(), *PredPattern);
4714 
4715   return SDValue();
4716 }
4717 
4718 // Returns a safe bitcast between two scalable vector predicates, where
4719 // any newly created lanes from a widening bitcast are defined as zero.
4720 static SDValue getSVEPredicateBitCast(EVT VT, SDValue Op, SelectionDAG &DAG) {
4721   SDLoc DL(Op);
4722   EVT InVT = Op.getValueType();
4723 
4724   assert(InVT.getVectorElementType() == MVT::i1 &&
4725          VT.getVectorElementType() == MVT::i1 &&
4726          "Expected a predicate-to-predicate bitcast");
4727   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
4728          InVT.isScalableVector() &&
4729          DAG.getTargetLoweringInfo().isTypeLegal(InVT) &&
4730          "Only expect to cast between legal scalable predicate types!");
4731 
4732   // Return the operand if the cast isn't changing type,
4733   // e.g. <n x 16 x i1> -> <n x 16 x i1>
4734   if (InVT == VT)
4735     return Op;
4736 
4737   SDValue Reinterpret = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
4738 
4739   // We only have to zero the lanes if new lanes are being defined, e.g. when
4740   // casting from <vscale x 2 x i1> to <vscale x 16 x i1>. If this is not the
4741   // case (e.g. when casting from <vscale x 16 x i1> -> <vscale x 2 x i1>) then
4742   // we can return here.
4743   if (InVT.bitsGT(VT))
4744     return Reinterpret;
4745 
4746   // Check if the other lanes are already known to be zeroed by
4747   // construction.
4748   if (isZeroingInactiveLanes(Op))
4749     return Reinterpret;
4750 
4751   // Zero the newly introduced lanes.
4752   SDValue Mask = DAG.getConstant(1, DL, InVT);
4753   Mask = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Mask);
4754   return DAG.getNode(ISD::AND, DL, VT, Reinterpret, Mask);
4755 }
4756 
4757 SDValue AArch64TargetLowering::getPStateSM(SelectionDAG &DAG, SDValue Chain,
4758                                            SMEAttrs Attrs, SDLoc DL,
4759                                            EVT VT) const {
4760   if (Attrs.hasStreamingInterfaceOrBody())
4761     return DAG.getConstant(1, DL, VT);
4762 
4763   if (Attrs.hasNonStreamingInterfaceAndBody())
4764     return DAG.getConstant(0, DL, VT);
4765 
4766   assert(Attrs.hasStreamingCompatibleInterface() && "Unexpected interface");
4767 
4768   SDValue Callee = DAG.getExternalSymbol("__arm_sme_state",
4769                                          getPointerTy(DAG.getDataLayout()));
4770   Type *Int64Ty = Type::getInt64Ty(*DAG.getContext());
4771   Type *RetTy = StructType::get(Int64Ty, Int64Ty);
4772   TargetLowering::CallLoweringInfo CLI(DAG);
4773   ArgListTy Args;
4774   CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
4775       CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2,
4776       RetTy, Callee, std::move(Args));
4777   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
4778   SDValue Mask = DAG.getConstant(/*PSTATE.SM*/ 1, DL, MVT::i64);
4779   return DAG.getNode(ISD::AND, DL, MVT::i64, CallResult.first.getOperand(0),
4780                      Mask);
4781 }
4782 
4783 static std::optional<SMEAttrs> getCalleeAttrsFromExternalFunction(SDValue V) {
4784   if (auto *ES = dyn_cast<ExternalSymbolSDNode>(V)) {
4785     StringRef S(ES->getSymbol());
4786     if (S == "__arm_sme_state" || S == "__arm_tpidr2_save")
4787       return SMEAttrs(SMEAttrs::SM_Compatible | SMEAttrs::ZA_Preserved);
4788     if (S == "__arm_tpidr2_restore")
4789       return SMEAttrs(SMEAttrs::SM_Compatible | SMEAttrs::ZA_Shared);
4790   }
4791   return std::nullopt;
4792 }
4793 
4794 SDValue AArch64TargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4795                                                    SelectionDAG &DAG) const {
4796   unsigned IntNo = Op.getConstantOperandVal(1);
4797   SDLoc DL(Op);
4798   switch (IntNo) {
4799   default:
4800     return SDValue(); // Don't custom lower most intrinsics.
4801   case Intrinsic::aarch64_prefetch: {
4802     SDValue Chain = Op.getOperand(0);
4803     SDValue Addr = Op.getOperand(2);
4804 
4805     unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
4806     unsigned Locality = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4807     unsigned IsStream = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
4808     unsigned IsData = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
4809     unsigned PrfOp = (IsWrite << 4) |    // Load/Store bit
4810                      (!IsData << 3) |    // IsDataCache bit
4811                      (Locality << 1) |   // Cache level bits
4812                      (unsigned)IsStream; // Stream bit
4813 
4814     return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Chain,
4815                        DAG.getTargetConstant(PrfOp, DL, MVT::i32), Addr);
4816   }
4817   case Intrinsic::aarch64_sme_za_enable:
4818     return DAG.getNode(
4819         AArch64ISD::SMSTART, DL, MVT::Other,
4820         Op->getOperand(0), // Chain
4821         DAG.getTargetConstant((int32_t)(AArch64SVCR::SVCRZA), DL, MVT::i32),
4822         DAG.getConstant(0, DL, MVT::i64), DAG.getConstant(1, DL, MVT::i64));
4823   case Intrinsic::aarch64_sme_za_disable:
4824     return DAG.getNode(
4825         AArch64ISD::SMSTOP, DL, MVT::Other,
4826         Op->getOperand(0), // Chain
4827         DAG.getTargetConstant((int32_t)(AArch64SVCR::SVCRZA), DL, MVT::i32),
4828         DAG.getConstant(0, DL, MVT::i64), DAG.getConstant(1, DL, MVT::i64));
4829   }
4830 }
4831 
4832 SDValue AArch64TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4833                                                       SelectionDAG &DAG) const {
4834   unsigned IntNo = Op.getConstantOperandVal(1);
4835   SDLoc DL(Op);
4836   switch (IntNo) {
4837   default:
4838     return SDValue(); // Don't custom lower most intrinsics.
4839   case Intrinsic::aarch64_mops_memset_tag: {
4840     auto Node = cast<MemIntrinsicSDNode>(Op.getNode());
4841     SDValue Chain = Node->getChain();
4842     SDValue Dst = Op.getOperand(2);
4843     SDValue Val = Op.getOperand(3);
4844     Val = DAG.getAnyExtOrTrunc(Val, DL, MVT::i64);
4845     SDValue Size = Op.getOperand(4);
4846     auto Alignment = Node->getMemOperand()->getAlign();
4847     bool IsVol = Node->isVolatile();
4848     auto DstPtrInfo = Node->getPointerInfo();
4849 
4850     const auto &SDI =
4851         static_cast<const AArch64SelectionDAGInfo &>(DAG.getSelectionDAGInfo());
4852     SDValue MS =
4853         SDI.EmitMOPS(AArch64ISD::MOPS_MEMSET_TAGGING, DAG, DL, Chain, Dst, Val,
4854                      Size, Alignment, IsVol, DstPtrInfo, MachinePointerInfo{});
4855 
4856     // MOPS_MEMSET_TAGGING has 3 results (DstWb, SizeWb, Chain) whereas the
4857     // intrinsic has 2. So hide SizeWb using MERGE_VALUES. Otherwise
4858     // LowerOperationWrapper will complain that the number of results has
4859     // changed.
4860     return DAG.getMergeValues({MS.getValue(0), MS.getValue(2)}, DL);
4861   }
4862   }
4863 }
4864 
4865 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4866                                                      SelectionDAG &DAG) const {
4867   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4868   SDLoc dl(Op);
4869   switch (IntNo) {
4870   default: return SDValue();    // Don't custom lower most intrinsics.
4871   case Intrinsic::thread_pointer: {
4872     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4873     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
4874   }
4875   case Intrinsic::aarch64_neon_abs: {
4876     EVT Ty = Op.getValueType();
4877     if (Ty == MVT::i64) {
4878       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
4879                                    Op.getOperand(1));
4880       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
4881       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
4882     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
4883       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
4884     } else {
4885       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
4886     }
4887   }
4888   case Intrinsic::aarch64_neon_pmull64: {
4889     SDValue LHS = Op.getOperand(1);
4890     SDValue RHS = Op.getOperand(2);
4891 
4892     std::optional<uint64_t> LHSLane =
4893         getConstantLaneNumOfExtractHalfOperand(LHS);
4894     std::optional<uint64_t> RHSLane =
4895         getConstantLaneNumOfExtractHalfOperand(RHS);
4896 
4897     assert((!LHSLane || *LHSLane < 2) && "Expect lane to be None or 0 or 1");
4898     assert((!RHSLane || *RHSLane < 2) && "Expect lane to be None or 0 or 1");
4899 
4900     // 'aarch64_neon_pmull64' takes i64 parameters; while pmull/pmull2
4901     // instructions execute on SIMD registers. So canonicalize i64 to v1i64,
4902     // which ISel recognizes better. For example, generate a ldr into d*
4903     // registers as opposed to a GPR load followed by a fmov.
4904     auto TryVectorizeOperand = [](SDValue N, std::optional<uint64_t> NLane,
4905                                   std::optional<uint64_t> OtherLane,
4906                                   const SDLoc &dl,
4907                                   SelectionDAG &DAG) -> SDValue {
4908       // If the operand is an higher half itself, rewrite it to
4909       // extract_high_v2i64; this way aarch64_neon_pmull64 could
4910       // re-use the dag-combiner function with aarch64_neon_{pmull,smull,umull}.
4911       if (NLane && *NLane == 1)
4912         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i64,
4913                            N.getOperand(0), DAG.getConstant(1, dl, MVT::i64));
4914 
4915       // Operand N is not a higher half but the other operand is.
4916       if (OtherLane && *OtherLane == 1) {
4917         // If this operand is a lower half, rewrite it to
4918         // extract_high_v2i64(duplane(<2 x Ty>, 0)). This saves a roundtrip to
4919         // align lanes of two operands. A roundtrip sequence (to move from lane
4920         // 1 to lane 0) is like this:
4921         //   mov x8, v0.d[1]
4922         //   fmov d0, x8
4923         if (NLane && *NLane == 0)
4924           return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i64,
4925                              DAG.getNode(AArch64ISD::DUPLANE64, dl, MVT::v2i64,
4926                                          N.getOperand(0),
4927                                          DAG.getConstant(0, dl, MVT::i64)),
4928                              DAG.getConstant(1, dl, MVT::i64));
4929 
4930         // Otherwise just dup from main to all lanes.
4931         return DAG.getNode(AArch64ISD::DUP, dl, MVT::v1i64, N);
4932       }
4933 
4934       // Neither operand is an extract of higher half, so codegen may just use
4935       // the non-high version of PMULL instruction. Use v1i64 to represent i64.
4936       assert(N.getValueType() == MVT::i64 &&
4937              "Intrinsic aarch64_neon_pmull64 requires i64 parameters");
4938       return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, N);
4939     };
4940 
4941     LHS = TryVectorizeOperand(LHS, LHSLane, RHSLane, dl, DAG);
4942     RHS = TryVectorizeOperand(RHS, RHSLane, LHSLane, dl, DAG);
4943 
4944     return DAG.getNode(AArch64ISD::PMULL, dl, Op.getValueType(), LHS, RHS);
4945   }
4946   case Intrinsic::aarch64_neon_smax:
4947     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
4948                        Op.getOperand(1), Op.getOperand(2));
4949   case Intrinsic::aarch64_neon_umax:
4950     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
4951                        Op.getOperand(1), Op.getOperand(2));
4952   case Intrinsic::aarch64_neon_smin:
4953     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
4954                        Op.getOperand(1), Op.getOperand(2));
4955   case Intrinsic::aarch64_neon_umin:
4956     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
4957                        Op.getOperand(1), Op.getOperand(2));
4958   case Intrinsic::aarch64_neon_scalar_sqxtn:
4959   case Intrinsic::aarch64_neon_scalar_sqxtun:
4960   case Intrinsic::aarch64_neon_scalar_uqxtn: {
4961     assert(Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::f32);
4962     if (Op.getValueType() == MVT::i32)
4963       return DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4964                          DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::f32,
4965                                      Op.getOperand(0),
4966                                      DAG.getNode(ISD::BITCAST, dl, MVT::f64,
4967                                                  Op.getOperand(1))));
4968     return SDValue();
4969   }
4970   case Intrinsic::aarch64_sve_whilelo:
4971     return optimizeWhile(Op, DAG, /*IsSigned=*/false, /*IsLess=*/true,
4972                          /*IsEqual=*/false);
4973   case Intrinsic::aarch64_sve_whilelt:
4974     return optimizeWhile(Op, DAG, /*IsSigned=*/true, /*IsLess=*/true,
4975                          /*IsEqual=*/false);
4976   case Intrinsic::aarch64_sve_whilels:
4977     return optimizeWhile(Op, DAG, /*IsSigned=*/false, /*IsLess=*/true,
4978                          /*IsEqual=*/true);
4979   case Intrinsic::aarch64_sve_whilele:
4980     return optimizeWhile(Op, DAG, /*IsSigned=*/true, /*IsLess=*/true,
4981                          /*IsEqual=*/true);
4982   case Intrinsic::aarch64_sve_whilege:
4983     return optimizeWhile(Op, DAG, /*IsSigned=*/true, /*IsLess=*/false,
4984                          /*IsEqual=*/true);
4985   case Intrinsic::aarch64_sve_whilegt:
4986     return optimizeWhile(Op, DAG, /*IsSigned=*/true, /*IsLess=*/false,
4987                          /*IsEqual=*/false);
4988   case Intrinsic::aarch64_sve_whilehs:
4989     return optimizeWhile(Op, DAG, /*IsSigned=*/false, /*IsLess=*/false,
4990                          /*IsEqual=*/true);
4991   case Intrinsic::aarch64_sve_whilehi:
4992     return optimizeWhile(Op, DAG, /*IsSigned=*/false, /*IsLess=*/false,
4993                          /*IsEqual=*/false);
4994   case Intrinsic::aarch64_sve_sunpkhi:
4995     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
4996                        Op.getOperand(1));
4997   case Intrinsic::aarch64_sve_sunpklo:
4998     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
4999                        Op.getOperand(1));
5000   case Intrinsic::aarch64_sve_uunpkhi:
5001     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
5002                        Op.getOperand(1));
5003   case Intrinsic::aarch64_sve_uunpklo:
5004     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
5005                        Op.getOperand(1));
5006   case Intrinsic::aarch64_sve_clasta_n:
5007     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
5008                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5009   case Intrinsic::aarch64_sve_clastb_n:
5010     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
5011                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5012   case Intrinsic::aarch64_sve_lasta:
5013     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
5014                        Op.getOperand(1), Op.getOperand(2));
5015   case Intrinsic::aarch64_sve_lastb:
5016     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
5017                        Op.getOperand(1), Op.getOperand(2));
5018   case Intrinsic::aarch64_sve_rev:
5019     return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(),
5020                        Op.getOperand(1));
5021   case Intrinsic::aarch64_sve_tbl:
5022     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
5023                        Op.getOperand(1), Op.getOperand(2));
5024   case Intrinsic::aarch64_sve_trn1:
5025     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
5026                        Op.getOperand(1), Op.getOperand(2));
5027   case Intrinsic::aarch64_sve_trn2:
5028     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
5029                        Op.getOperand(1), Op.getOperand(2));
5030   case Intrinsic::aarch64_sve_uzp1:
5031     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
5032                        Op.getOperand(1), Op.getOperand(2));
5033   case Intrinsic::aarch64_sve_uzp2:
5034     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
5035                        Op.getOperand(1), Op.getOperand(2));
5036   case Intrinsic::aarch64_sve_zip1:
5037     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
5038                        Op.getOperand(1), Op.getOperand(2));
5039   case Intrinsic::aarch64_sve_zip2:
5040     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
5041                        Op.getOperand(1), Op.getOperand(2));
5042   case Intrinsic::aarch64_sve_splice:
5043     return DAG.getNode(AArch64ISD::SPLICE, dl, Op.getValueType(),
5044                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5045   case Intrinsic::aarch64_sve_ptrue:
5046     return getPTrue(DAG, dl, Op.getValueType(),
5047                     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
5048   case Intrinsic::aarch64_sve_clz:
5049     return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
5050                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5051   case Intrinsic::aarch64_sme_cntsb:
5052     return DAG.getNode(AArch64ISD::RDSVL, dl, Op.getValueType(),
5053                        DAG.getConstant(1, dl, MVT::i32));
5054   case Intrinsic::aarch64_sme_cntsh: {
5055     SDValue One = DAG.getConstant(1, dl, MVT::i32);
5056     SDValue Bytes = DAG.getNode(AArch64ISD::RDSVL, dl, Op.getValueType(), One);
5057     return DAG.getNode(ISD::SRL, dl, Op.getValueType(), Bytes, One);
5058   }
5059   case Intrinsic::aarch64_sme_cntsw: {
5060     SDValue Bytes = DAG.getNode(AArch64ISD::RDSVL, dl, Op.getValueType(),
5061                                 DAG.getConstant(1, dl, MVT::i32));
5062     return DAG.getNode(ISD::SRL, dl, Op.getValueType(), Bytes,
5063                        DAG.getConstant(2, dl, MVT::i32));
5064   }
5065   case Intrinsic::aarch64_sme_cntsd: {
5066     SDValue Bytes = DAG.getNode(AArch64ISD::RDSVL, dl, Op.getValueType(),
5067                                 DAG.getConstant(1, dl, MVT::i32));
5068     return DAG.getNode(ISD::SRL, dl, Op.getValueType(), Bytes,
5069                        DAG.getConstant(3, dl, MVT::i32));
5070   }
5071   case Intrinsic::aarch64_sve_cnt: {
5072     SDValue Data = Op.getOperand(3);
5073     // CTPOP only supports integer operands.
5074     if (Data.getValueType().isFloatingPoint())
5075       Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
5076     return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
5077                        Op.getOperand(2), Data, Op.getOperand(1));
5078   }
5079   case Intrinsic::aarch64_sve_dupq_lane:
5080     return LowerDUPQLane(Op, DAG);
5081   case Intrinsic::aarch64_sve_convert_from_svbool:
5082     if (Op.getValueType() == MVT::aarch64svcount)
5083       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Op.getOperand(1));
5084     return getSVEPredicateBitCast(Op.getValueType(), Op.getOperand(1), DAG);
5085   case Intrinsic::aarch64_sve_convert_to_svbool:
5086     if (Op.getOperand(1).getValueType() == MVT::aarch64svcount)
5087       return DAG.getNode(ISD::BITCAST, dl, MVT::nxv16i1, Op.getOperand(1));
5088     return getSVEPredicateBitCast(MVT::nxv16i1, Op.getOperand(1), DAG);
5089   case Intrinsic::aarch64_sve_fneg:
5090     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
5091                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5092   case Intrinsic::aarch64_sve_frintp:
5093     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
5094                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5095   case Intrinsic::aarch64_sve_frintm:
5096     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
5097                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5098   case Intrinsic::aarch64_sve_frinti:
5099     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
5100                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5101   case Intrinsic::aarch64_sve_frintx:
5102     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
5103                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5104   case Intrinsic::aarch64_sve_frinta:
5105     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
5106                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5107   case Intrinsic::aarch64_sve_frintn:
5108     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
5109                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5110   case Intrinsic::aarch64_sve_frintz:
5111     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
5112                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5113   case Intrinsic::aarch64_sve_ucvtf:
5114     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
5115                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
5116                        Op.getOperand(1));
5117   case Intrinsic::aarch64_sve_scvtf:
5118     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
5119                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
5120                        Op.getOperand(1));
5121   case Intrinsic::aarch64_sve_fcvtzu:
5122     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
5123                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
5124                        Op.getOperand(1));
5125   case Intrinsic::aarch64_sve_fcvtzs:
5126     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
5127                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
5128                        Op.getOperand(1));
5129   case Intrinsic::aarch64_sve_fsqrt:
5130     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
5131                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5132   case Intrinsic::aarch64_sve_frecpx:
5133     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
5134                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5135   case Intrinsic::aarch64_sve_frecpe_x:
5136     return DAG.getNode(AArch64ISD::FRECPE, dl, Op.getValueType(),
5137                        Op.getOperand(1));
5138   case Intrinsic::aarch64_sve_frecps_x:
5139     return DAG.getNode(AArch64ISD::FRECPS, dl, Op.getValueType(),
5140                        Op.getOperand(1), Op.getOperand(2));
5141   case Intrinsic::aarch64_sve_frsqrte_x:
5142     return DAG.getNode(AArch64ISD::FRSQRTE, dl, Op.getValueType(),
5143                        Op.getOperand(1));
5144   case Intrinsic::aarch64_sve_frsqrts_x:
5145     return DAG.getNode(AArch64ISD::FRSQRTS, dl, Op.getValueType(),
5146                        Op.getOperand(1), Op.getOperand(2));
5147   case Intrinsic::aarch64_sve_fabs:
5148     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
5149                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5150   case Intrinsic::aarch64_sve_abs:
5151     return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
5152                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5153   case Intrinsic::aarch64_sve_neg:
5154     return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
5155                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5156   case Intrinsic::aarch64_sve_insr: {
5157     SDValue Scalar = Op.getOperand(2);
5158     EVT ScalarTy = Scalar.getValueType();
5159     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
5160       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
5161 
5162     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
5163                        Op.getOperand(1), Scalar);
5164   }
5165   case Intrinsic::aarch64_sve_rbit:
5166     return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
5167                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
5168                        Op.getOperand(1));
5169   case Intrinsic::aarch64_sve_revb:
5170     return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
5171                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5172   case Intrinsic::aarch64_sve_revh:
5173     return DAG.getNode(AArch64ISD::REVH_MERGE_PASSTHRU, dl, Op.getValueType(),
5174                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5175   case Intrinsic::aarch64_sve_revw:
5176     return DAG.getNode(AArch64ISD::REVW_MERGE_PASSTHRU, dl, Op.getValueType(),
5177                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5178   case Intrinsic::aarch64_sve_revd:
5179     return DAG.getNode(AArch64ISD::REVD_MERGE_PASSTHRU, dl, Op.getValueType(),
5180                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
5181   case Intrinsic::aarch64_sve_sxtb:
5182     return DAG.getNode(
5183         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
5184         Op.getOperand(2), Op.getOperand(3),
5185         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
5186         Op.getOperand(1));
5187   case Intrinsic::aarch64_sve_sxth:
5188     return DAG.getNode(
5189         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
5190         Op.getOperand(2), Op.getOperand(3),
5191         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
5192         Op.getOperand(1));
5193   case Intrinsic::aarch64_sve_sxtw:
5194     return DAG.getNode(
5195         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
5196         Op.getOperand(2), Op.getOperand(3),
5197         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
5198         Op.getOperand(1));
5199   case Intrinsic::aarch64_sve_uxtb:
5200     return DAG.getNode(
5201         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
5202         Op.getOperand(2), Op.getOperand(3),
5203         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
5204         Op.getOperand(1));
5205   case Intrinsic::aarch64_sve_uxth:
5206     return DAG.getNode(
5207         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
5208         Op.getOperand(2), Op.getOperand(3),
5209         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
5210         Op.getOperand(1));
5211   case Intrinsic::aarch64_sve_uxtw:
5212     return DAG.getNode(
5213         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
5214         Op.getOperand(2), Op.getOperand(3),
5215         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
5216         Op.getOperand(1));
5217   case Intrinsic::localaddress: {
5218     const auto &MF = DAG.getMachineFunction();
5219     const auto *RegInfo = Subtarget->getRegisterInfo();
5220     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
5221     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
5222                               Op.getSimpleValueType());
5223   }
5224 
5225   case Intrinsic::eh_recoverfp: {
5226     // FIXME: This needs to be implemented to correctly handle highly aligned
5227     // stack objects. For now we simply return the incoming FP. Refer D53541
5228     // for more details.
5229     SDValue FnOp = Op.getOperand(1);
5230     SDValue IncomingFPOp = Op.getOperand(2);
5231     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
5232     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
5233     if (!Fn)
5234       report_fatal_error(
5235           "llvm.eh.recoverfp must take a function as the first argument");
5236     return IncomingFPOp;
5237   }
5238 
5239   case Intrinsic::aarch64_neon_vsri:
5240   case Intrinsic::aarch64_neon_vsli: {
5241     EVT Ty = Op.getValueType();
5242 
5243     if (!Ty.isVector())
5244       report_fatal_error("Unexpected type for aarch64_neon_vsli");
5245 
5246     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
5247 
5248     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
5249     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
5250     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
5251                        Op.getOperand(3));
5252   }
5253 
5254   case Intrinsic::aarch64_neon_srhadd:
5255   case Intrinsic::aarch64_neon_urhadd:
5256   case Intrinsic::aarch64_neon_shadd:
5257   case Intrinsic::aarch64_neon_uhadd: {
5258     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
5259                         IntNo == Intrinsic::aarch64_neon_shadd);
5260     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
5261                           IntNo == Intrinsic::aarch64_neon_urhadd);
5262     unsigned Opcode = IsSignedAdd
5263                           ? (IsRoundingAdd ? ISD::AVGCEILS : ISD::AVGFLOORS)
5264                           : (IsRoundingAdd ? ISD::AVGCEILU : ISD::AVGFLOORU);
5265     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
5266                        Op.getOperand(2));
5267   }
5268   case Intrinsic::aarch64_neon_saddlp:
5269   case Intrinsic::aarch64_neon_uaddlp: {
5270     unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uaddlp
5271                           ? AArch64ISD::UADDLP
5272                           : AArch64ISD::SADDLP;
5273     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1));
5274   }
5275   case Intrinsic::aarch64_neon_sdot:
5276   case Intrinsic::aarch64_neon_udot:
5277   case Intrinsic::aarch64_sve_sdot:
5278   case Intrinsic::aarch64_sve_udot: {
5279     unsigned Opcode = (IntNo == Intrinsic::aarch64_neon_udot ||
5280                        IntNo == Intrinsic::aarch64_sve_udot)
5281                           ? AArch64ISD::UDOT
5282                           : AArch64ISD::SDOT;
5283     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
5284                        Op.getOperand(2), Op.getOperand(3));
5285   }
5286   case Intrinsic::get_active_lane_mask: {
5287     SDValue ID =
5288         DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, MVT::i64);
5289     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), ID,
5290                        Op.getOperand(1), Op.getOperand(2));
5291   }
5292   }
5293 }
5294 
5295 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const {
5296   if (VT.getVectorElementType() == MVT::i8 ||
5297       VT.getVectorElementType() == MVT::i16) {
5298     EltTy = MVT::i32;
5299     return true;
5300   }
5301   return false;
5302 }
5303 
5304 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
5305                                                           EVT DataVT) const {
5306   // SVE only supports implicit extension of 32-bit indices.
5307   if (!Subtarget->hasSVE() || IndexVT.getVectorElementType() != MVT::i32)
5308     return false;
5309 
5310   // Indices cannot be smaller than the main data type.
5311   if (IndexVT.getScalarSizeInBits() < DataVT.getScalarSizeInBits())
5312     return false;
5313 
5314   // Scalable vectors with "vscale * 2" or fewer elements sit within a 64-bit
5315   // element container type, which would violate the previous clause.
5316   return DataVT.isFixedLengthVector() || DataVT.getVectorMinNumElements() > 2;
5317 }
5318 
5319 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
5320   return ExtVal.getValueType().isScalableVector() ||
5321          Subtarget->useSVEForFixedLengthVectors();
5322 }
5323 
5324 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
5325   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
5326       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
5327        AArch64ISD::GLD1_MERGE_ZERO},
5328       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
5329        AArch64ISD::GLD1_UXTW_MERGE_ZERO},
5330       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
5331        AArch64ISD::GLD1_MERGE_ZERO},
5332       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
5333        AArch64ISD::GLD1_SXTW_MERGE_ZERO},
5334       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
5335        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
5336       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
5337        AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
5338       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
5339        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
5340       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
5341        AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
5342   };
5343   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
5344   return AddrModes.find(Key)->second;
5345 }
5346 
5347 unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
5348   switch (Opcode) {
5349   default:
5350     llvm_unreachable("unimplemented opcode");
5351     return Opcode;
5352   case AArch64ISD::GLD1_MERGE_ZERO:
5353     return AArch64ISD::GLD1S_MERGE_ZERO;
5354   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
5355     return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
5356   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
5357     return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
5358   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
5359     return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
5360   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
5361     return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
5362   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
5363     return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
5364   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
5365     return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
5366   }
5367 }
5368 
5369 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
5370                                             SelectionDAG &DAG) const {
5371   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
5372 
5373   SDLoc DL(Op);
5374   SDValue Chain = MGT->getChain();
5375   SDValue PassThru = MGT->getPassThru();
5376   SDValue Mask = MGT->getMask();
5377   SDValue BasePtr = MGT->getBasePtr();
5378   SDValue Index = MGT->getIndex();
5379   SDValue Scale = MGT->getScale();
5380   EVT VT = Op.getValueType();
5381   EVT MemVT = MGT->getMemoryVT();
5382   ISD::LoadExtType ExtType = MGT->getExtensionType();
5383   ISD::MemIndexType IndexType = MGT->getIndexType();
5384 
5385   // SVE supports zero (and so undef) passthrough values only, everything else
5386   // must be handled manually by an explicit select on the load's output.
5387   if (!PassThru->isUndef() && !isZerosVector(PassThru.getNode())) {
5388     SDValue Ops[] = {Chain, DAG.getUNDEF(VT), Mask, BasePtr, Index, Scale};
5389     SDValue Load =
5390         DAG.getMaskedGather(MGT->getVTList(), MemVT, DL, Ops,
5391                             MGT->getMemOperand(), IndexType, ExtType);
5392     SDValue Select = DAG.getSelect(DL, VT, Mask, Load, PassThru);
5393     return DAG.getMergeValues({Select, Load.getValue(1)}, DL);
5394   }
5395 
5396   bool IsScaled = MGT->isIndexScaled();
5397   bool IsSigned = MGT->isIndexSigned();
5398 
5399   // SVE supports an index scaled by sizeof(MemVT.elt) only, everything else
5400   // must be calculated before hand.
5401   uint64_t ScaleVal = cast<ConstantSDNode>(Scale)->getZExtValue();
5402   if (IsScaled && ScaleVal != MemVT.getScalarStoreSize()) {
5403     assert(isPowerOf2_64(ScaleVal) && "Expecting power-of-two types");
5404     EVT IndexVT = Index.getValueType();
5405     Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index,
5406                         DAG.getConstant(Log2_32(ScaleVal), DL, IndexVT));
5407     Scale = DAG.getTargetConstant(1, DL, Scale.getValueType());
5408 
5409     SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
5410     return DAG.getMaskedGather(MGT->getVTList(), MemVT, DL, Ops,
5411                                MGT->getMemOperand(), IndexType, ExtType);
5412   }
5413 
5414   // Lower fixed length gather to a scalable equivalent.
5415   if (VT.isFixedLengthVector()) {
5416     assert(Subtarget->useSVEForFixedLengthVectors() &&
5417            "Cannot lower when not using SVE for fixed vectors!");
5418 
5419     // NOTE: Handle floating-point as if integer then bitcast the result.
5420     EVT DataVT = VT.changeVectorElementTypeToInteger();
5421     MemVT = MemVT.changeVectorElementTypeToInteger();
5422 
5423     // Find the smallest integer fixed length vector we can use for the gather.
5424     EVT PromotedVT = VT.changeVectorElementType(MVT::i32);
5425     if (DataVT.getVectorElementType() == MVT::i64 ||
5426         Index.getValueType().getVectorElementType() == MVT::i64 ||
5427         Mask.getValueType().getVectorElementType() == MVT::i64)
5428       PromotedVT = VT.changeVectorElementType(MVT::i64);
5429 
5430     // Promote vector operands except for passthrough, which we know is either
5431     // undef or zero, and thus best constructed directly.
5432     unsigned ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5433     Index = DAG.getNode(ExtOpcode, DL, PromotedVT, Index);
5434     Mask = DAG.getNode(ISD::SIGN_EXTEND, DL, PromotedVT, Mask);
5435 
5436     // A promoted result type forces the need for an extending load.
5437     if (PromotedVT != DataVT && ExtType == ISD::NON_EXTLOAD)
5438       ExtType = ISD::EXTLOAD;
5439 
5440     EVT ContainerVT = getContainerForFixedLengthVector(DAG, PromotedVT);
5441 
5442     // Convert fixed length vector operands to scalable.
5443     MemVT = ContainerVT.changeVectorElementType(MemVT.getVectorElementType());
5444     Index = convertToScalableVector(DAG, ContainerVT, Index);
5445     Mask = convertFixedMaskToScalableVector(Mask, DAG);
5446     PassThru = PassThru->isUndef() ? DAG.getUNDEF(ContainerVT)
5447                                    : DAG.getConstant(0, DL, ContainerVT);
5448 
5449     // Emit equivalent scalable vector gather.
5450     SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
5451     SDValue Load =
5452         DAG.getMaskedGather(DAG.getVTList(ContainerVT, MVT::Other), MemVT, DL,
5453                             Ops, MGT->getMemOperand(), IndexType, ExtType);
5454 
5455     // Extract fixed length data then convert to the required result type.
5456     SDValue Result = convertFromScalableVector(DAG, PromotedVT, Load);
5457     Result = DAG.getNode(ISD::TRUNCATE, DL, DataVT, Result);
5458     if (VT.isFloatingPoint())
5459       Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
5460 
5461     return DAG.getMergeValues({Result, Load.getValue(1)}, DL);
5462   }
5463 
5464   // Everything else is legal.
5465   return Op;
5466 }
5467 
5468 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
5469                                              SelectionDAG &DAG) const {
5470   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
5471 
5472   SDLoc DL(Op);
5473   SDValue Chain = MSC->getChain();
5474   SDValue StoreVal = MSC->getValue();
5475   SDValue Mask = MSC->getMask();
5476   SDValue BasePtr = MSC->getBasePtr();
5477   SDValue Index = MSC->getIndex();
5478   SDValue Scale = MSC->getScale();
5479   EVT VT = StoreVal.getValueType();
5480   EVT MemVT = MSC->getMemoryVT();
5481   ISD::MemIndexType IndexType = MSC->getIndexType();
5482   bool Truncating = MSC->isTruncatingStore();
5483 
5484   bool IsScaled = MSC->isIndexScaled();
5485   bool IsSigned = MSC->isIndexSigned();
5486 
5487   // SVE supports an index scaled by sizeof(MemVT.elt) only, everything else
5488   // must be calculated before hand.
5489   uint64_t ScaleVal = cast<ConstantSDNode>(Scale)->getZExtValue();
5490   if (IsScaled && ScaleVal != MemVT.getScalarStoreSize()) {
5491     assert(isPowerOf2_64(ScaleVal) && "Expecting power-of-two types");
5492     EVT IndexVT = Index.getValueType();
5493     Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index,
5494                         DAG.getConstant(Log2_32(ScaleVal), DL, IndexVT));
5495     Scale = DAG.getTargetConstant(1, DL, Scale.getValueType());
5496 
5497     SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
5498     return DAG.getMaskedScatter(MSC->getVTList(), MemVT, DL, Ops,
5499                                 MSC->getMemOperand(), IndexType, Truncating);
5500   }
5501 
5502   // Lower fixed length scatter to a scalable equivalent.
5503   if (VT.isFixedLengthVector()) {
5504     assert(Subtarget->useSVEForFixedLengthVectors() &&
5505            "Cannot lower when not using SVE for fixed vectors!");
5506 
5507     // Once bitcast we treat floating-point scatters as if integer.
5508     if (VT.isFloatingPoint()) {
5509       VT = VT.changeVectorElementTypeToInteger();
5510       MemVT = MemVT.changeVectorElementTypeToInteger();
5511       StoreVal = DAG.getNode(ISD::BITCAST, DL, VT, StoreVal);
5512     }
5513 
5514     // Find the smallest integer fixed length vector we can use for the scatter.
5515     EVT PromotedVT = VT.changeVectorElementType(MVT::i32);
5516     if (VT.getVectorElementType() == MVT::i64 ||
5517         Index.getValueType().getVectorElementType() == MVT::i64 ||
5518         Mask.getValueType().getVectorElementType() == MVT::i64)
5519       PromotedVT = VT.changeVectorElementType(MVT::i64);
5520 
5521     // Promote vector operands.
5522     unsigned ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5523     Index = DAG.getNode(ExtOpcode, DL, PromotedVT, Index);
5524     Mask = DAG.getNode(ISD::SIGN_EXTEND, DL, PromotedVT, Mask);
5525     StoreVal = DAG.getNode(ISD::ANY_EXTEND, DL, PromotedVT, StoreVal);
5526 
5527     // A promoted value type forces the need for a truncating store.
5528     if (PromotedVT != VT)
5529       Truncating = true;
5530 
5531     EVT ContainerVT = getContainerForFixedLengthVector(DAG, PromotedVT);
5532 
5533     // Convert fixed length vector operands to scalable.
5534     MemVT = ContainerVT.changeVectorElementType(MemVT.getVectorElementType());
5535     Index = convertToScalableVector(DAG, ContainerVT, Index);
5536     Mask = convertFixedMaskToScalableVector(Mask, DAG);
5537     StoreVal = convertToScalableVector(DAG, ContainerVT, StoreVal);
5538 
5539     // Emit equivalent scalable vector scatter.
5540     SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
5541     return DAG.getMaskedScatter(MSC->getVTList(), MemVT, DL, Ops,
5542                                 MSC->getMemOperand(), IndexType, Truncating);
5543   }
5544 
5545   // Everything else is legal.
5546   return Op;
5547 }
5548 
5549 SDValue AArch64TargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
5550   SDLoc DL(Op);
5551   MaskedLoadSDNode *LoadNode = cast<MaskedLoadSDNode>(Op);
5552   assert(LoadNode && "Expected custom lowering of a masked load node");
5553   EVT VT = Op->getValueType(0);
5554 
5555   if (useSVEForFixedLengthVectorVT(
5556           VT,
5557           /*OverrideNEON=*/Subtarget->useSVEForFixedLengthVectors()))
5558     return LowerFixedLengthVectorMLoadToSVE(Op, DAG);
5559 
5560   SDValue PassThru = LoadNode->getPassThru();
5561   SDValue Mask = LoadNode->getMask();
5562 
5563   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
5564     return Op;
5565 
5566   SDValue Load = DAG.getMaskedLoad(
5567       VT, DL, LoadNode->getChain(), LoadNode->getBasePtr(),
5568       LoadNode->getOffset(), Mask, DAG.getUNDEF(VT), LoadNode->getMemoryVT(),
5569       LoadNode->getMemOperand(), LoadNode->getAddressingMode(),
5570       LoadNode->getExtensionType());
5571 
5572   SDValue Result = DAG.getSelect(DL, VT, Mask, Load, PassThru);
5573 
5574   return DAG.getMergeValues({Result, Load.getValue(1)}, DL);
5575 }
5576 
5577 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
5578 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
5579                                         EVT VT, EVT MemVT,
5580                                         SelectionDAG &DAG) {
5581   assert(VT.isVector() && "VT should be a vector type");
5582   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
5583 
5584   SDValue Value = ST->getValue();
5585 
5586   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
5587   // the word lane which represent the v4i8 subvector.  It optimizes the store
5588   // to:
5589   //
5590   //   xtn  v0.8b, v0.8h
5591   //   str  s0, [x0]
5592 
5593   SDValue Undef = DAG.getUNDEF(MVT::i16);
5594   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
5595                                         {Undef, Undef, Undef, Undef});
5596 
5597   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
5598                                  Value, UndefVec);
5599   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
5600 
5601   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
5602   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5603                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
5604 
5605   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
5606                       ST->getBasePtr(), ST->getMemOperand());
5607 }
5608 
5609 // Custom lowering for any store, vector or scalar and/or default or with
5610 // a truncate operations.  Currently only custom lower truncate operation
5611 // from vector v4i16 to v4i8 or volatile stores of i128.
5612 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
5613                                           SelectionDAG &DAG) const {
5614   SDLoc Dl(Op);
5615   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
5616   assert (StoreNode && "Can only custom lower store nodes");
5617 
5618   SDValue Value = StoreNode->getValue();
5619 
5620   EVT VT = Value.getValueType();
5621   EVT MemVT = StoreNode->getMemoryVT();
5622 
5623   if (VT.isVector()) {
5624     if (useSVEForFixedLengthVectorVT(
5625             VT,
5626             /*OverrideNEON=*/Subtarget->useSVEForFixedLengthVectors()))
5627       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
5628 
5629     unsigned AS = StoreNode->getAddressSpace();
5630     Align Alignment = StoreNode->getAlign();
5631     if (Alignment < MemVT.getStoreSize() &&
5632         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment,
5633                                         StoreNode->getMemOperand()->getFlags(),
5634                                         nullptr)) {
5635       return scalarizeVectorStore(StoreNode, DAG);
5636     }
5637 
5638     if (StoreNode->isTruncatingStore() && VT == MVT::v4i16 &&
5639         MemVT == MVT::v4i8) {
5640       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
5641     }
5642     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
5643     // the custom lowering, as there are no un-paired non-temporal stores and
5644     // legalization will break up 256 bit inputs.
5645     ElementCount EC = MemVT.getVectorElementCount();
5646     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
5647         EC.isKnownEven() &&
5648         ((MemVT.getScalarSizeInBits() == 8u ||
5649           MemVT.getScalarSizeInBits() == 16u ||
5650           MemVT.getScalarSizeInBits() == 32u ||
5651           MemVT.getScalarSizeInBits() == 64u))) {
5652       SDValue Lo =
5653           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
5654                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
5655                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
5656       SDValue Hi =
5657           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
5658                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
5659                       StoreNode->getValue(),
5660                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
5661       SDValue Result = DAG.getMemIntrinsicNode(
5662           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
5663           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
5664           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
5665       return Result;
5666     }
5667   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
5668     return LowerStore128(Op, DAG);
5669   } else if (MemVT == MVT::i64x8) {
5670     SDValue Value = StoreNode->getValue();
5671     assert(Value->getValueType(0) == MVT::i64x8);
5672     SDValue Chain = StoreNode->getChain();
5673     SDValue Base = StoreNode->getBasePtr();
5674     EVT PtrVT = Base.getValueType();
5675     for (unsigned i = 0; i < 8; i++) {
5676       SDValue Part = DAG.getNode(AArch64ISD::LS64_EXTRACT, Dl, MVT::i64,
5677                                  Value, DAG.getConstant(i, Dl, MVT::i32));
5678       SDValue Ptr = DAG.getNode(ISD::ADD, Dl, PtrVT, Base,
5679                                 DAG.getConstant(i * 8, Dl, PtrVT));
5680       Chain = DAG.getStore(Chain, Dl, Part, Ptr, StoreNode->getPointerInfo(),
5681                            StoreNode->getOriginalAlign());
5682     }
5683     return Chain;
5684   }
5685 
5686   return SDValue();
5687 }
5688 
5689 /// Lower atomic or volatile 128-bit stores to a single STP instruction.
5690 SDValue AArch64TargetLowering::LowerStore128(SDValue Op,
5691                                              SelectionDAG &DAG) const {
5692   MemSDNode *StoreNode = cast<MemSDNode>(Op);
5693   assert(StoreNode->getMemoryVT() == MVT::i128);
5694   assert(StoreNode->isVolatile() || StoreNode->isAtomic());
5695 
5696   bool IsStoreRelease =
5697       StoreNode->getMergedOrdering() == AtomicOrdering::Release;
5698   if (StoreNode->isAtomic())
5699     assert((Subtarget->hasFeature(AArch64::FeatureLSE2) &&
5700             Subtarget->hasFeature(AArch64::FeatureRCPC3) && IsStoreRelease) ||
5701            StoreNode->getMergedOrdering() == AtomicOrdering::Unordered ||
5702            StoreNode->getMergedOrdering() == AtomicOrdering::Monotonic);
5703 
5704   SDValue Value = StoreNode->getOpcode() == ISD::STORE
5705                       ? StoreNode->getOperand(1)
5706                       : StoreNode->getOperand(2);
5707   SDLoc DL(Op);
5708   auto StoreValue = DAG.SplitScalar(Value, DL, MVT::i64, MVT::i64);
5709   unsigned Opcode = IsStoreRelease ? AArch64ISD::STILP : AArch64ISD::STP;
5710   SDValue Result = DAG.getMemIntrinsicNode(
5711       Opcode, DL, DAG.getVTList(MVT::Other),
5712       {StoreNode->getChain(), StoreValue.first, StoreValue.second,
5713        StoreNode->getBasePtr()},
5714       StoreNode->getMemoryVT(), StoreNode->getMemOperand());
5715   return Result;
5716 }
5717 
5718 SDValue AArch64TargetLowering::LowerLOAD(SDValue Op,
5719                                          SelectionDAG &DAG) const {
5720   SDLoc DL(Op);
5721   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
5722   assert(LoadNode && "Expected custom lowering of a load node");
5723 
5724   if (LoadNode->getMemoryVT() == MVT::i64x8) {
5725     SmallVector<SDValue, 8> Ops;
5726     SDValue Base = LoadNode->getBasePtr();
5727     SDValue Chain = LoadNode->getChain();
5728     EVT PtrVT = Base.getValueType();
5729     for (unsigned i = 0; i < 8; i++) {
5730       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
5731                                 DAG.getConstant(i * 8, DL, PtrVT));
5732       SDValue Part = DAG.getLoad(MVT::i64, DL, Chain, Ptr,
5733                                  LoadNode->getPointerInfo(),
5734                                  LoadNode->getOriginalAlign());
5735       Ops.push_back(Part);
5736       Chain = SDValue(Part.getNode(), 1);
5737     }
5738     SDValue Loaded = DAG.getNode(AArch64ISD::LS64_BUILD, DL, MVT::i64x8, Ops);
5739     return DAG.getMergeValues({Loaded, Chain}, DL);
5740   }
5741 
5742   // Custom lowering for extending v4i8 vector loads.
5743   EVT VT = Op->getValueType(0);
5744   assert((VT == MVT::v4i16 || VT == MVT::v4i32) && "Expected v4i16 or v4i32");
5745 
5746   if (LoadNode->getMemoryVT() != MVT::v4i8)
5747     return SDValue();
5748 
5749   unsigned ExtType;
5750   if (LoadNode->getExtensionType() == ISD::SEXTLOAD)
5751     ExtType = ISD::SIGN_EXTEND;
5752   else if (LoadNode->getExtensionType() == ISD::ZEXTLOAD ||
5753            LoadNode->getExtensionType() == ISD::EXTLOAD)
5754     ExtType = ISD::ZERO_EXTEND;
5755   else
5756     return SDValue();
5757 
5758   SDValue Load = DAG.getLoad(MVT::f32, DL, LoadNode->getChain(),
5759                              LoadNode->getBasePtr(), MachinePointerInfo());
5760   SDValue Chain = Load.getValue(1);
5761   SDValue Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f32, Load);
5762   SDValue BC = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Vec);
5763   SDValue Ext = DAG.getNode(ExtType, DL, MVT::v8i16, BC);
5764   Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Ext,
5765                     DAG.getConstant(0, DL, MVT::i64));
5766   if (VT == MVT::v4i32)
5767     Ext = DAG.getNode(ExtType, DL, MVT::v4i32, Ext);
5768   return DAG.getMergeValues({Ext, Chain}, DL);
5769 }
5770 
5771 // Generate SUBS and CSEL for integer abs.
5772 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5773   MVT VT = Op.getSimpleValueType();
5774 
5775   if (VT.isVector())
5776     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
5777 
5778   SDLoc DL(Op);
5779   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
5780                             Op.getOperand(0));
5781   // Generate SUBS & CSEL.
5782   SDValue Cmp =
5783       DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
5784                   Op.getOperand(0), DAG.getConstant(0, DL, VT));
5785   return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
5786                      DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
5787                      Cmp.getValue(1));
5788 }
5789 
5790 static SDValue LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5791   SDValue Chain = Op.getOperand(0);
5792   SDValue Cond = Op.getOperand(1);
5793   SDValue Dest = Op.getOperand(2);
5794 
5795   AArch64CC::CondCode CC;
5796   if (SDValue Cmp = emitConjunction(DAG, Cond, CC)) {
5797     SDLoc dl(Op);
5798     SDValue CCVal = DAG.getConstant(CC, dl, MVT::i32);
5799     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5800                        Cmp);
5801   }
5802 
5803   return SDValue();
5804 }
5805 
5806 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
5807                                               SelectionDAG &DAG) const {
5808   LLVM_DEBUG(dbgs() << "Custom lowering: ");
5809   LLVM_DEBUG(Op.dump());
5810 
5811   switch (Op.getOpcode()) {
5812   default:
5813     llvm_unreachable("unimplemented operand");
5814     return SDValue();
5815   case ISD::BITCAST:
5816     return LowerBITCAST(Op, DAG);
5817   case ISD::GlobalAddress:
5818     return LowerGlobalAddress(Op, DAG);
5819   case ISD::GlobalTLSAddress:
5820     return LowerGlobalTLSAddress(Op, DAG);
5821   case ISD::SETCC:
5822   case ISD::STRICT_FSETCC:
5823   case ISD::STRICT_FSETCCS:
5824     return LowerSETCC(Op, DAG);
5825   case ISD::SETCCCARRY:
5826     return LowerSETCCCARRY(Op, DAG);
5827   case ISD::BRCOND:
5828     return LowerBRCOND(Op, DAG);
5829   case ISD::BR_CC:
5830     return LowerBR_CC(Op, DAG);
5831   case ISD::SELECT:
5832     return LowerSELECT(Op, DAG);
5833   case ISD::SELECT_CC:
5834     return LowerSELECT_CC(Op, DAG);
5835   case ISD::JumpTable:
5836     return LowerJumpTable(Op, DAG);
5837   case ISD::BR_JT:
5838     return LowerBR_JT(Op, DAG);
5839   case ISD::ConstantPool:
5840     return LowerConstantPool(Op, DAG);
5841   case ISD::BlockAddress:
5842     return LowerBlockAddress(Op, DAG);
5843   case ISD::VASTART:
5844     return LowerVASTART(Op, DAG);
5845   case ISD::VACOPY:
5846     return LowerVACOPY(Op, DAG);
5847   case ISD::VAARG:
5848     return LowerVAARG(Op, DAG);
5849   case ISD::UADDO_CARRY:
5850     return lowerADDSUBO_CARRY(Op, DAG, AArch64ISD::ADCS, false /*unsigned*/);
5851   case ISD::USUBO_CARRY:
5852     return lowerADDSUBO_CARRY(Op, DAG, AArch64ISD::SBCS, false /*unsigned*/);
5853   case ISD::SADDO_CARRY:
5854     return lowerADDSUBO_CARRY(Op, DAG, AArch64ISD::ADCS, true /*signed*/);
5855   case ISD::SSUBO_CARRY:
5856     return lowerADDSUBO_CARRY(Op, DAG, AArch64ISD::SBCS, true /*signed*/);
5857   case ISD::SADDO:
5858   case ISD::UADDO:
5859   case ISD::SSUBO:
5860   case ISD::USUBO:
5861   case ISD::SMULO:
5862   case ISD::UMULO:
5863     return LowerXALUO(Op, DAG);
5864   case ISD::FADD:
5865     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
5866   case ISD::FSUB:
5867     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
5868   case ISD::FMUL:
5869     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
5870   case ISD::FMA:
5871     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
5872   case ISD::FDIV:
5873     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
5874   case ISD::FNEG:
5875     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
5876   case ISD::FCEIL:
5877     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
5878   case ISD::FFLOOR:
5879     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
5880   case ISD::FNEARBYINT:
5881     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
5882   case ISD::FRINT:
5883     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
5884   case ISD::FROUND:
5885     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
5886   case ISD::FROUNDEVEN:
5887     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
5888   case ISD::FTRUNC:
5889     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
5890   case ISD::FSQRT:
5891     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
5892   case ISD::FABS:
5893     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
5894   case ISD::FP_ROUND:
5895   case ISD::STRICT_FP_ROUND:
5896     return LowerFP_ROUND(Op, DAG);
5897   case ISD::FP_EXTEND:
5898     return LowerFP_EXTEND(Op, DAG);
5899   case ISD::FRAMEADDR:
5900     return LowerFRAMEADDR(Op, DAG);
5901   case ISD::SPONENTRY:
5902     return LowerSPONENTRY(Op, DAG);
5903   case ISD::RETURNADDR:
5904     return LowerRETURNADDR(Op, DAG);
5905   case ISD::ADDROFRETURNADDR:
5906     return LowerADDROFRETURNADDR(Op, DAG);
5907   case ISD::CONCAT_VECTORS:
5908     return LowerCONCAT_VECTORS(Op, DAG);
5909   case ISD::INSERT_VECTOR_ELT:
5910     return LowerINSERT_VECTOR_ELT(Op, DAG);
5911   case ISD::EXTRACT_VECTOR_ELT:
5912     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5913   case ISD::BUILD_VECTOR:
5914     return LowerBUILD_VECTOR(Op, DAG);
5915   case ISD::ZERO_EXTEND_VECTOR_INREG:
5916     return LowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
5917   case ISD::VECTOR_SHUFFLE:
5918     return LowerVECTOR_SHUFFLE(Op, DAG);
5919   case ISD::SPLAT_VECTOR:
5920     return LowerSPLAT_VECTOR(Op, DAG);
5921   case ISD::EXTRACT_SUBVECTOR:
5922     return LowerEXTRACT_SUBVECTOR(Op, DAG);
5923   case ISD::INSERT_SUBVECTOR:
5924     return LowerINSERT_SUBVECTOR(Op, DAG);
5925   case ISD::SDIV:
5926   case ISD::UDIV:
5927     return LowerDIV(Op, DAG);
5928   case ISD::SMIN:
5929   case ISD::UMIN:
5930   case ISD::SMAX:
5931   case ISD::UMAX:
5932     return LowerMinMax(Op, DAG);
5933   case ISD::SRA:
5934   case ISD::SRL:
5935   case ISD::SHL:
5936     return LowerVectorSRA_SRL_SHL(Op, DAG);
5937   case ISD::SHL_PARTS:
5938   case ISD::SRL_PARTS:
5939   case ISD::SRA_PARTS:
5940     return LowerShiftParts(Op, DAG);
5941   case ISD::CTPOP:
5942   case ISD::PARITY:
5943     return LowerCTPOP_PARITY(Op, DAG);
5944   case ISD::FCOPYSIGN:
5945     return LowerFCOPYSIGN(Op, DAG);
5946   case ISD::OR:
5947     return LowerVectorOR(Op, DAG);
5948   case ISD::XOR:
5949     return LowerXOR(Op, DAG);
5950   case ISD::PREFETCH:
5951     return LowerPREFETCH(Op, DAG);
5952   case ISD::SINT_TO_FP:
5953   case ISD::UINT_TO_FP:
5954   case ISD::STRICT_SINT_TO_FP:
5955   case ISD::STRICT_UINT_TO_FP:
5956     return LowerINT_TO_FP(Op, DAG);
5957   case ISD::FP_TO_SINT:
5958   case ISD::FP_TO_UINT:
5959   case ISD::STRICT_FP_TO_SINT:
5960   case ISD::STRICT_FP_TO_UINT:
5961     return LowerFP_TO_INT(Op, DAG);
5962   case ISD::FP_TO_SINT_SAT:
5963   case ISD::FP_TO_UINT_SAT:
5964     return LowerFP_TO_INT_SAT(Op, DAG);
5965   case ISD::FSINCOS:
5966     return LowerFSINCOS(Op, DAG);
5967   case ISD::GET_ROUNDING:
5968     return LowerGET_ROUNDING(Op, DAG);
5969   case ISD::SET_ROUNDING:
5970     return LowerSET_ROUNDING(Op, DAG);
5971   case ISD::MUL:
5972     return LowerMUL(Op, DAG);
5973   case ISD::MULHS:
5974     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHS_PRED);
5975   case ISD::MULHU:
5976     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHU_PRED);
5977   case ISD::INTRINSIC_W_CHAIN:
5978     return LowerINTRINSIC_W_CHAIN(Op, DAG);
5979   case ISD::INTRINSIC_WO_CHAIN:
5980     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5981   case ISD::INTRINSIC_VOID:
5982     return LowerINTRINSIC_VOID(Op, DAG);
5983   case ISD::ATOMIC_STORE:
5984     if (cast<MemSDNode>(Op)->getMemoryVT() == MVT::i128) {
5985       assert(Subtarget->hasLSE2() || Subtarget->hasRCPC3());
5986       return LowerStore128(Op, DAG);
5987     }
5988     return SDValue();
5989   case ISD::STORE:
5990     return LowerSTORE(Op, DAG);
5991   case ISD::MSTORE:
5992     return LowerFixedLengthVectorMStoreToSVE(Op, DAG);
5993   case ISD::MGATHER:
5994     return LowerMGATHER(Op, DAG);
5995   case ISD::MSCATTER:
5996     return LowerMSCATTER(Op, DAG);
5997   case ISD::VECREDUCE_SEQ_FADD:
5998     return LowerVECREDUCE_SEQ_FADD(Op, DAG);
5999   case ISD::VECREDUCE_ADD:
6000   case ISD::VECREDUCE_AND:
6001   case ISD::VECREDUCE_OR:
6002   case ISD::VECREDUCE_XOR:
6003   case ISD::VECREDUCE_SMAX:
6004   case ISD::VECREDUCE_SMIN:
6005   case ISD::VECREDUCE_UMAX:
6006   case ISD::VECREDUCE_UMIN:
6007   case ISD::VECREDUCE_FADD:
6008   case ISD::VECREDUCE_FMAX:
6009   case ISD::VECREDUCE_FMIN:
6010   case ISD::VECREDUCE_FMAXIMUM:
6011   case ISD::VECREDUCE_FMINIMUM:
6012     return LowerVECREDUCE(Op, DAG);
6013   case ISD::ATOMIC_LOAD_SUB:
6014     return LowerATOMIC_LOAD_SUB(Op, DAG);
6015   case ISD::ATOMIC_LOAD_AND:
6016     return LowerATOMIC_LOAD_AND(Op, DAG);
6017   case ISD::DYNAMIC_STACKALLOC:
6018     return LowerDYNAMIC_STACKALLOC(Op, DAG);
6019   case ISD::VSCALE:
6020     return LowerVSCALE(Op, DAG);
6021   case ISD::ANY_EXTEND:
6022   case ISD::SIGN_EXTEND:
6023   case ISD::ZERO_EXTEND:
6024     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
6025   case ISD::SIGN_EXTEND_INREG: {
6026     // Only custom lower when ExtraVT has a legal byte based element type.
6027     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6028     EVT ExtraEltVT = ExtraVT.getVectorElementType();
6029     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
6030         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
6031       return SDValue();
6032 
6033     return LowerToPredicatedOp(Op, DAG,
6034                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
6035   }
6036   case ISD::TRUNCATE:
6037     return LowerTRUNCATE(Op, DAG);
6038   case ISD::MLOAD:
6039     return LowerMLOAD(Op, DAG);
6040   case ISD::LOAD:
6041     if (useSVEForFixedLengthVectorVT(Op.getValueType(),
6042                                      !Subtarget->isNeonAvailable()))
6043       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
6044     return LowerLOAD(Op, DAG);
6045   case ISD::ADD:
6046   case ISD::AND:
6047   case ISD::SUB:
6048     return LowerToScalableOp(Op, DAG);
6049   case ISD::FMAXIMUM:
6050     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED);
6051   case ISD::FMAXNUM:
6052     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
6053   case ISD::FMINIMUM:
6054     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED);
6055   case ISD::FMINNUM:
6056     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
6057   case ISD::VSELECT:
6058     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
6059   case ISD::ABS:
6060     return LowerABS(Op, DAG);
6061   case ISD::ABDS:
6062     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABDS_PRED);
6063   case ISD::ABDU:
6064     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABDU_PRED);
6065   case ISD::AVGFLOORS:
6066     return LowerAVG(Op, DAG, AArch64ISD::HADDS_PRED);
6067   case ISD::AVGFLOORU:
6068     return LowerAVG(Op, DAG, AArch64ISD::HADDU_PRED);
6069   case ISD::AVGCEILS:
6070     return LowerAVG(Op, DAG, AArch64ISD::RHADDS_PRED);
6071   case ISD::AVGCEILU:
6072     return LowerAVG(Op, DAG, AArch64ISD::RHADDU_PRED);
6073   case ISD::BITREVERSE:
6074     return LowerBitreverse(Op, DAG);
6075   case ISD::BSWAP:
6076     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
6077   case ISD::CTLZ:
6078     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU);
6079   case ISD::CTTZ:
6080     return LowerCTTZ(Op, DAG);
6081   case ISD::VECTOR_SPLICE:
6082     return LowerVECTOR_SPLICE(Op, DAG);
6083   case ISD::VECTOR_DEINTERLEAVE:
6084     return LowerVECTOR_DEINTERLEAVE(Op, DAG);
6085   case ISD::VECTOR_INTERLEAVE:
6086     return LowerVECTOR_INTERLEAVE(Op, DAG);
6087   case ISD::STRICT_LROUND:
6088   case ISD::STRICT_LLROUND:
6089   case ISD::STRICT_LRINT:
6090   case ISD::STRICT_LLRINT: {
6091     assert(Op.getOperand(1).getValueType() == MVT::f16 &&
6092            "Expected custom lowering of rounding operations only for f16");
6093     SDLoc DL(Op);
6094     SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
6095                               {Op.getOperand(0), Op.getOperand(1)});
6096     return DAG.getNode(Op.getOpcode(), DL, {Op.getValueType(), MVT::Other},
6097                        {Ext.getValue(1), Ext.getValue(0)});
6098   }
6099   case ISD::WRITE_REGISTER: {
6100     assert(Op.getOperand(2).getValueType() == MVT::i128 &&
6101            "WRITE_REGISTER custom lowering is only for 128-bit sysregs");
6102     SDLoc DL(Op);
6103 
6104     SDValue Chain = Op.getOperand(0);
6105     SDValue SysRegName = Op.getOperand(1);
6106     std::pair<SDValue, SDValue> Pair =
6107         DAG.SplitScalar(Op.getOperand(2), DL, MVT::i64, MVT::i64);
6108 
6109     // chain = MSRR(chain, sysregname, lo, hi)
6110     SDValue Result = DAG.getNode(AArch64ISD::MSRR, DL, MVT::Other, Chain,
6111                                  SysRegName, Pair.first, Pair.second);
6112 
6113     return Result;
6114   }
6115   }
6116 }
6117 
6118 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
6119   return !Subtarget->useSVEForFixedLengthVectors();
6120 }
6121 
6122 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
6123     EVT VT, bool OverrideNEON) const {
6124   if (!VT.isFixedLengthVector() || !VT.isSimple())
6125     return false;
6126 
6127   // Don't use SVE for vectors we cannot scalarize if required.
6128   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6129   // Fixed length predicates should be promoted to i8.
6130   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
6131   case MVT::i1:
6132   default:
6133     return false;
6134   case MVT::i8:
6135   case MVT::i16:
6136   case MVT::i32:
6137   case MVT::i64:
6138   case MVT::f16:
6139   case MVT::f32:
6140   case MVT::f64:
6141     break;
6142   }
6143 
6144   // All SVE implementations support NEON sized vectors.
6145   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
6146     return Subtarget->hasSVE();
6147 
6148   // Ensure NEON MVTs only belong to a single register class.
6149   if (VT.getFixedSizeInBits() <= 128)
6150     return false;
6151 
6152   // Ensure wider than NEON code generation is enabled.
6153   if (!Subtarget->useSVEForFixedLengthVectors())
6154     return false;
6155 
6156   // Don't use SVE for types that don't fit.
6157   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
6158     return false;
6159 
6160   // TODO: Perhaps an artificial restriction, but worth having whilst getting
6161   // the base fixed length SVE support in place.
6162   if (!VT.isPow2VectorType())
6163     return false;
6164 
6165   return true;
6166 }
6167 
6168 //===----------------------------------------------------------------------===//
6169 //                      Calling Convention Implementation
6170 //===----------------------------------------------------------------------===//
6171 
6172 static unsigned getIntrinsicID(const SDNode *N) {
6173   unsigned Opcode = N->getOpcode();
6174   switch (Opcode) {
6175   default:
6176     return Intrinsic::not_intrinsic;
6177   case ISD::INTRINSIC_WO_CHAIN: {
6178     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6179     if (IID < Intrinsic::num_intrinsics)
6180       return IID;
6181     return Intrinsic::not_intrinsic;
6182   }
6183   }
6184 }
6185 
6186 bool AArch64TargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
6187                                                 SDValue N1) const {
6188   if (!N0.hasOneUse())
6189     return false;
6190 
6191   unsigned IID = getIntrinsicID(N1.getNode());
6192   // Avoid reassociating expressions that can be lowered to smlal/umlal.
6193   if (IID == Intrinsic::aarch64_neon_umull ||
6194       N1.getOpcode() == AArch64ISD::UMULL ||
6195       IID == Intrinsic::aarch64_neon_smull ||
6196       N1.getOpcode() == AArch64ISD::SMULL)
6197     return N0.getOpcode() != ISD::ADD;
6198 
6199   return true;
6200 }
6201 
6202 /// Selects the correct CCAssignFn for a given CallingConvention value.
6203 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
6204                                                      bool IsVarArg) const {
6205   switch (CC) {
6206   default:
6207     report_fatal_error("Unsupported calling convention.");
6208   case CallingConv::WebKit_JS:
6209     return CC_AArch64_WebKit_JS;
6210   case CallingConv::GHC:
6211     return CC_AArch64_GHC;
6212   case CallingConv::C:
6213   case CallingConv::Fast:
6214   case CallingConv::PreserveMost:
6215   case CallingConv::PreserveAll:
6216   case CallingConv::CXX_FAST_TLS:
6217   case CallingConv::Swift:
6218   case CallingConv::SwiftTail:
6219   case CallingConv::Tail:
6220     if (Subtarget->isTargetWindows() && IsVarArg) {
6221       if (Subtarget->isWindowsArm64EC())
6222         return CC_AArch64_Arm64EC_VarArg;
6223       return CC_AArch64_Win64_VarArg;
6224     }
6225     if (!Subtarget->isTargetDarwin())
6226       return CC_AArch64_AAPCS;
6227     if (!IsVarArg)
6228       return CC_AArch64_DarwinPCS;
6229     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
6230                                       : CC_AArch64_DarwinPCS_VarArg;
6231    case CallingConv::Win64:
6232      if (IsVarArg) {
6233        if (Subtarget->isWindowsArm64EC())
6234          return CC_AArch64_Arm64EC_VarArg;
6235        return CC_AArch64_Win64_VarArg;
6236      }
6237      return CC_AArch64_AAPCS;
6238    case CallingConv::CFGuard_Check:
6239      return CC_AArch64_Win64_CFGuard_Check;
6240    case CallingConv::AArch64_VectorCall:
6241    case CallingConv::AArch64_SVE_VectorCall:
6242    case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
6243    case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
6244      return CC_AArch64_AAPCS;
6245   }
6246 }
6247 
6248 CCAssignFn *
6249 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
6250   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
6251                                       : RetCC_AArch64_AAPCS;
6252 }
6253 
6254 
6255 unsigned
6256 AArch64TargetLowering::allocateLazySaveBuffer(SDValue &Chain, const SDLoc &DL,
6257                                               SelectionDAG &DAG) const {
6258   MachineFunction &MF = DAG.getMachineFunction();
6259   MachineFrameInfo &MFI = MF.getFrameInfo();
6260 
6261   // Allocate a lazy-save buffer object of size SVL.B * SVL.B (worst-case)
6262   SDValue N = DAG.getNode(AArch64ISD::RDSVL, DL, MVT::i64,
6263                           DAG.getConstant(1, DL, MVT::i32));
6264   SDValue NN = DAG.getNode(ISD::MUL, DL, MVT::i64, N, N);
6265   SDValue Ops[] = {Chain, NN, DAG.getConstant(1, DL, MVT::i64)};
6266   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6267   SDValue Buffer = DAG.getNode(ISD::DYNAMIC_STACKALLOC, DL, VTs, Ops);
6268   Chain = Buffer.getValue(1);
6269   MFI.CreateVariableSizedObject(Align(1), nullptr);
6270 
6271   // Allocate an additional TPIDR2 object on the stack (16 bytes)
6272   unsigned TPIDR2Obj = MFI.CreateStackObject(16, Align(16), false);
6273 
6274   // Store the buffer pointer to the TPIDR2 stack object.
6275   MachinePointerInfo MPI = MachinePointerInfo::getStack(MF, TPIDR2Obj);
6276   SDValue Ptr = DAG.getFrameIndex(
6277       TPIDR2Obj,
6278       DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
6279   Chain = DAG.getStore(Chain, DL, Buffer, Ptr, MPI);
6280 
6281   return TPIDR2Obj;
6282 }
6283 
6284 SDValue AArch64TargetLowering::LowerFormalArguments(
6285     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6286     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
6287     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6288   MachineFunction &MF = DAG.getMachineFunction();
6289   const Function &F = MF.getFunction();
6290   MachineFrameInfo &MFI = MF.getFrameInfo();
6291   bool IsWin64 = Subtarget->isCallingConvWin64(F.getCallingConv());
6292   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6293 
6294   SmallVector<ISD::OutputArg, 4> Outs;
6295   GetReturnInfo(CallConv, F.getReturnType(), F.getAttributes(), Outs,
6296                 DAG.getTargetLoweringInfo(), MF.getDataLayout());
6297   if (any_of(Outs, [](ISD::OutputArg &Out){ return Out.VT.isScalableVector(); }))
6298     FuncInfo->setIsSVECC(true);
6299 
6300   // Assign locations to all of the incoming arguments.
6301   SmallVector<CCValAssign, 16> ArgLocs;
6302   DenseMap<unsigned, SDValue> CopiedRegs;
6303   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6304 
6305   // At this point, Ins[].VT may already be promoted to i32. To correctly
6306   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
6307   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
6308   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
6309   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
6310   // LocVT.
6311   unsigned NumArgs = Ins.size();
6312   Function::const_arg_iterator CurOrigArg = F.arg_begin();
6313   unsigned CurArgIdx = 0;
6314   for (unsigned i = 0; i != NumArgs; ++i) {
6315     MVT ValVT = Ins[i].VT;
6316     if (Ins[i].isOrigArg()) {
6317       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
6318       CurArgIdx = Ins[i].getOrigArgIndex();
6319 
6320       // Get type of the original argument.
6321       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
6322                                   /*AllowUnknown*/ true);
6323       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
6324       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
6325       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
6326         ValVT = MVT::i8;
6327       else if (ActualMVT == MVT::i16)
6328         ValVT = MVT::i16;
6329     }
6330     bool UseVarArgCC = false;
6331     if (IsWin64)
6332       UseVarArgCC = isVarArg;
6333     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
6334     bool Res =
6335         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
6336     assert(!Res && "Call operand has unhandled type");
6337     (void)Res;
6338   }
6339 
6340   SMEAttrs Attrs(MF.getFunction());
6341   bool IsLocallyStreaming =
6342       !Attrs.hasStreamingInterface() && Attrs.hasStreamingBody();
6343   assert(Chain.getOpcode() == ISD::EntryToken && "Unexpected Chain value");
6344   SDValue Glue = Chain.getValue(1);
6345 
6346   SmallVector<SDValue, 16> ArgValues;
6347   unsigned ExtraArgLocs = 0;
6348   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6349     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
6350 
6351     if (Ins[i].Flags.isByVal()) {
6352       // Byval is used for HFAs in the PCS, but the system should work in a
6353       // non-compliant manner for larger structs.
6354       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6355       int Size = Ins[i].Flags.getByValSize();
6356       unsigned NumRegs = (Size + 7) / 8;
6357 
6358       // FIXME: This works on big-endian for composite byvals, which are the common
6359       // case. It should also work for fundamental types too.
6360       unsigned FrameIdx =
6361         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
6362       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
6363       InVals.push_back(FrameIdxN);
6364 
6365       continue;
6366     }
6367 
6368     if (Ins[i].Flags.isSwiftAsync())
6369       MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
6370 
6371     SDValue ArgValue;
6372     if (VA.isRegLoc()) {
6373       // Arguments stored in registers.
6374       EVT RegVT = VA.getLocVT();
6375       const TargetRegisterClass *RC;
6376 
6377       if (RegVT == MVT::i32)
6378         RC = &AArch64::GPR32RegClass;
6379       else if (RegVT == MVT::i64)
6380         RC = &AArch64::GPR64RegClass;
6381       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
6382         RC = &AArch64::FPR16RegClass;
6383       else if (RegVT == MVT::f32)
6384         RC = &AArch64::FPR32RegClass;
6385       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
6386         RC = &AArch64::FPR64RegClass;
6387       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
6388         RC = &AArch64::FPR128RegClass;
6389       else if (RegVT.isScalableVector() &&
6390                RegVT.getVectorElementType() == MVT::i1) {
6391         FuncInfo->setIsSVECC(true);
6392         RC = &AArch64::PPRRegClass;
6393       } else if (RegVT == MVT::aarch64svcount) {
6394         FuncInfo->setIsSVECC(true);
6395         RC = &AArch64::PPRRegClass;
6396       } else if (RegVT.isScalableVector()) {
6397         FuncInfo->setIsSVECC(true);
6398         RC = &AArch64::ZPRRegClass;
6399       } else
6400         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
6401 
6402       // Transform the arguments in physical registers into virtual ones.
6403       Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
6404 
6405       if (IsLocallyStreaming) {
6406         // LocallyStreamingFunctions must insert the SMSTART in the correct
6407         // position, so we use Glue to ensure no instructions can be scheduled
6408         // between the chain of:
6409         //        t0: ch,glue = EntryNode
6410         //      t1:  res,ch,glue = CopyFromReg
6411         //     ...
6412         //   tn: res,ch,glue = CopyFromReg t(n-1), ..
6413         // t(n+1): ch, glue = SMSTART t0:0, ...., tn:2
6414         // ^^^^^^
6415         // This will be the new Chain/Root node.
6416         ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT, Glue);
6417         Glue = ArgValue.getValue(2);
6418       } else
6419         ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
6420 
6421       // If this is an 8, 16 or 32-bit value, it is really passed promoted
6422       // to 64 bits.  Insert an assert[sz]ext to capture this, then
6423       // truncate to the right size.
6424       switch (VA.getLocInfo()) {
6425       default:
6426         llvm_unreachable("Unknown loc info!");
6427       case CCValAssign::Full:
6428         break;
6429       case CCValAssign::Indirect:
6430         assert(
6431             (VA.getValVT().isScalableVT() || Subtarget->isWindowsArm64EC()) &&
6432             "Indirect arguments should be scalable on most subtargets");
6433         break;
6434       case CCValAssign::BCvt:
6435         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
6436         break;
6437       case CCValAssign::AExt:
6438       case CCValAssign::SExt:
6439       case CCValAssign::ZExt:
6440         break;
6441       case CCValAssign::AExtUpper:
6442         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
6443                                DAG.getConstant(32, DL, RegVT));
6444         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
6445         break;
6446       }
6447     } else { // VA.isRegLoc()
6448       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
6449       unsigned ArgOffset = VA.getLocMemOffset();
6450       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
6451                               ? VA.getLocVT().getSizeInBits()
6452                               : VA.getValVT().getSizeInBits()) / 8;
6453 
6454       uint32_t BEAlign = 0;
6455       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
6456           !Ins[i].Flags.isInConsecutiveRegs())
6457         BEAlign = 8 - ArgSize;
6458 
6459       SDValue FIN;
6460       MachinePointerInfo PtrInfo;
6461       if (isVarArg && Subtarget->isWindowsArm64EC()) {
6462         // In the ARM64EC varargs convention, fixed arguments on the stack are
6463         // accessed relative to x4, not sp.
6464         unsigned ObjOffset = ArgOffset + BEAlign;
6465         Register VReg = MF.addLiveIn(AArch64::X4, &AArch64::GPR64RegClass);
6466         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
6467         FIN = DAG.getNode(ISD::ADD, DL, MVT::i64, Val,
6468                           DAG.getConstant(ObjOffset, DL, MVT::i64));
6469         PtrInfo = MachinePointerInfo::getUnknownStack(MF);
6470       } else {
6471         int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
6472 
6473         // Create load nodes to retrieve arguments from the stack.
6474         FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
6475         PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
6476       }
6477 
6478       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
6479       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6480       MVT MemVT = VA.getValVT();
6481 
6482       switch (VA.getLocInfo()) {
6483       default:
6484         break;
6485       case CCValAssign::Trunc:
6486       case CCValAssign::BCvt:
6487         MemVT = VA.getLocVT();
6488         break;
6489       case CCValAssign::Indirect:
6490         assert((VA.getValVT().isScalableVector() ||
6491                 Subtarget->isWindowsArm64EC()) &&
6492                "Indirect arguments should be scalable on most subtargets");
6493         MemVT = VA.getLocVT();
6494         break;
6495       case CCValAssign::SExt:
6496         ExtType = ISD::SEXTLOAD;
6497         break;
6498       case CCValAssign::ZExt:
6499         ExtType = ISD::ZEXTLOAD;
6500         break;
6501       case CCValAssign::AExt:
6502         ExtType = ISD::EXTLOAD;
6503         break;
6504       }
6505 
6506       ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN, PtrInfo,
6507                                 MemVT);
6508     }
6509 
6510     if (VA.getLocInfo() == CCValAssign::Indirect) {
6511       assert((VA.getValVT().isScalableVT() ||
6512               Subtarget->isWindowsArm64EC()) &&
6513              "Indirect arguments should be scalable on most subtargets");
6514 
6515       uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinValue();
6516       unsigned NumParts = 1;
6517       if (Ins[i].Flags.isInConsecutiveRegs()) {
6518         assert(!Ins[i].Flags.isInConsecutiveRegsLast());
6519         while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
6520           ++NumParts;
6521       }
6522 
6523       MVT PartLoad = VA.getValVT();
6524       SDValue Ptr = ArgValue;
6525 
6526       // Ensure we generate all loads for each tuple part, whilst updating the
6527       // pointer after each load correctly using vscale.
6528       while (NumParts > 0) {
6529         ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
6530         InVals.push_back(ArgValue);
6531         NumParts--;
6532         if (NumParts > 0) {
6533           SDValue BytesIncrement;
6534           if (PartLoad.isScalableVector()) {
6535             BytesIncrement = DAG.getVScale(
6536                 DL, Ptr.getValueType(),
6537                 APInt(Ptr.getValueSizeInBits().getFixedValue(), PartSize));
6538           } else {
6539             BytesIncrement = DAG.getConstant(
6540                 APInt(Ptr.getValueSizeInBits().getFixedValue(), PartSize), DL,
6541                 Ptr.getValueType());
6542           }
6543           SDNodeFlags Flags;
6544           Flags.setNoUnsignedWrap(true);
6545           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6546                             BytesIncrement, Flags);
6547           ExtraArgLocs++;
6548           i++;
6549         }
6550       }
6551     } else {
6552       if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
6553         ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
6554                                ArgValue, DAG.getValueType(MVT::i32));
6555 
6556       // i1 arguments are zero-extended to i8 by the caller. Emit a
6557       // hint to reflect this.
6558       if (Ins[i].isOrigArg()) {
6559         Argument *OrigArg = F.getArg(Ins[i].getOrigArgIndex());
6560         if (OrigArg->getType()->isIntegerTy(1)) {
6561           if (!Ins[i].Flags.isZExt()) {
6562             ArgValue = DAG.getNode(AArch64ISD::ASSERT_ZEXT_BOOL, DL,
6563                                    ArgValue.getValueType(), ArgValue);
6564           }
6565         }
6566       }
6567 
6568       InVals.push_back(ArgValue);
6569     }
6570   }
6571   assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
6572 
6573   // Insert the SMSTART if this is a locally streaming function and
6574   // make sure it is Glued to the last CopyFromReg value.
6575   if (IsLocallyStreaming) {
6576     const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6577     Chain = DAG.getNode(
6578         AArch64ISD::SMSTART, DL, DAG.getVTList(MVT::Other, MVT::Glue),
6579         {DAG.getRoot(),
6580           DAG.getTargetConstant((int32_t)AArch64SVCR::SVCRSM, DL, MVT::i32),
6581          DAG.getConstant(0, DL, MVT::i64), DAG.getConstant(1, DL, MVT::i64),
6582          DAG.getRegisterMask(TRI->getSMStartStopCallPreservedMask()), Glue});
6583     // Ensure that the SMSTART happens after the CopyWithChain such that its
6584     // chain result is used.
6585     for (unsigned I=0; I<InVals.size(); ++I) {
6586       Register Reg = MF.getRegInfo().createVirtualRegister(
6587           getRegClassFor(InVals[I].getValueType().getSimpleVT()));
6588       Chain = DAG.getCopyToReg(Chain, DL, Reg, InVals[I]);
6589       InVals[I] = DAG.getCopyFromReg(Chain, DL, Reg,
6590                                      InVals[I].getValueType());
6591     }
6592   }
6593 
6594   // varargs
6595   if (isVarArg) {
6596     if (!Subtarget->isTargetDarwin() || IsWin64) {
6597       // The AAPCS variadic function ABI is identical to the non-variadic
6598       // one. As a result there may be more arguments in registers and we should
6599       // save them for future reference.
6600       // Win64 variadic functions also pass arguments in registers, but all float
6601       // arguments are passed in integer registers.
6602       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
6603     }
6604 
6605     // This will point to the next argument passed via stack.
6606     unsigned VarArgsOffset = CCInfo.getStackSize();
6607     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
6608     VarArgsOffset = alignTo(VarArgsOffset, Subtarget->isTargetILP32() ? 4 : 8);
6609     FuncInfo->setVarArgsStackOffset(VarArgsOffset);
6610     FuncInfo->setVarArgsStackIndex(
6611         MFI.CreateFixedObject(4, VarArgsOffset, true));
6612 
6613     if (MFI.hasMustTailInVarArgFunc()) {
6614       SmallVector<MVT, 2> RegParmTypes;
6615       RegParmTypes.push_back(MVT::i64);
6616       RegParmTypes.push_back(MVT::f128);
6617       // Compute the set of forwarded registers. The rest are scratch.
6618       SmallVectorImpl<ForwardedRegister> &Forwards =
6619                                        FuncInfo->getForwardedMustTailRegParms();
6620       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
6621                                                CC_AArch64_AAPCS);
6622 
6623       // Conservatively forward X8, since it might be used for aggregate return.
6624       if (!CCInfo.isAllocated(AArch64::X8)) {
6625         Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
6626         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
6627       }
6628     }
6629   }
6630 
6631   // On Windows, InReg pointers must be returned, so record the pointer in a
6632   // virtual register at the start of the function so it can be returned in the
6633   // epilogue.
6634   if (IsWin64) {
6635     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
6636       if (Ins[I].Flags.isInReg() && Ins[I].Flags.isSRet()) {
6637         assert(!FuncInfo->getSRetReturnReg());
6638 
6639         MVT PtrTy = getPointerTy(DAG.getDataLayout());
6640         Register Reg =
6641             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
6642         FuncInfo->setSRetReturnReg(Reg);
6643 
6644         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
6645         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
6646         break;
6647       }
6648     }
6649   }
6650 
6651   unsigned StackArgSize = CCInfo.getStackSize();
6652   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
6653   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
6654     // This is a non-standard ABI so by fiat I say we're allowed to make full
6655     // use of the stack area to be popped, which must be aligned to 16 bytes in
6656     // any case:
6657     StackArgSize = alignTo(StackArgSize, 16);
6658 
6659     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
6660     // a multiple of 16.
6661     FuncInfo->setArgumentStackToRestore(StackArgSize);
6662 
6663     // This realignment carries over to the available bytes below. Our own
6664     // callers will guarantee the space is free by giving an aligned value to
6665     // CALLSEQ_START.
6666   }
6667   // Even if we're not expected to free up the space, it's useful to know how
6668   // much is there while considering tail calls (because we can reuse it).
6669   FuncInfo->setBytesInStackArgArea(StackArgSize);
6670 
6671   if (Subtarget->hasCustomCallingConv())
6672     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
6673 
6674   // Conservatively assume the function requires the lazy-save mechanism.
6675   if (SMEAttrs(MF.getFunction()).hasZAState()) {
6676     unsigned TPIDR2Obj = allocateLazySaveBuffer(Chain, DL, DAG);
6677     FuncInfo->setLazySaveTPIDR2Obj(TPIDR2Obj);
6678   }
6679 
6680   return Chain;
6681 }
6682 
6683 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
6684                                                 SelectionDAG &DAG,
6685                                                 const SDLoc &DL,
6686                                                 SDValue &Chain) const {
6687   MachineFunction &MF = DAG.getMachineFunction();
6688   MachineFrameInfo &MFI = MF.getFrameInfo();
6689   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6690   auto PtrVT = getPointerTy(DAG.getDataLayout());
6691   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
6692 
6693   SmallVector<SDValue, 8> MemOps;
6694 
6695   auto GPRArgRegs = AArch64::getGPRArgRegs();
6696   unsigned NumGPRArgRegs = GPRArgRegs.size();
6697   if (Subtarget->isWindowsArm64EC()) {
6698     // In the ARM64EC ABI, only x0-x3 are used to pass arguments to varargs
6699     // functions.
6700     NumGPRArgRegs = 4;
6701   }
6702   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
6703 
6704   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
6705   int GPRIdx = 0;
6706   if (GPRSaveSize != 0) {
6707     if (IsWin64) {
6708       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
6709       if (GPRSaveSize & 15)
6710         // The extra size here, if triggered, will always be 8.
6711         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
6712     } else
6713       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
6714 
6715     SDValue FIN;
6716     if (Subtarget->isWindowsArm64EC()) {
6717       // With the Arm64EC ABI, we reserve the save area as usual, but we
6718       // compute its address relative to x4.  For a normal AArch64->AArch64
6719       // call, x4 == sp on entry, but calls from an entry thunk can pass in a
6720       // different address.
6721       Register VReg = MF.addLiveIn(AArch64::X4, &AArch64::GPR64RegClass);
6722       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
6723       FIN = DAG.getNode(ISD::SUB, DL, MVT::i64, Val,
6724                         DAG.getConstant(GPRSaveSize, DL, MVT::i64));
6725     } else {
6726       FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
6727     }
6728 
6729     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
6730       Register VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
6731       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
6732       SDValue Store =
6733           DAG.getStore(Val.getValue(1), DL, Val, FIN,
6734                        IsWin64 ? MachinePointerInfo::getFixedStack(
6735                                      MF, GPRIdx, (i - FirstVariadicGPR) * 8)
6736                                : MachinePointerInfo::getStack(MF, i * 8));
6737       MemOps.push_back(Store);
6738       FIN =
6739           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
6740     }
6741   }
6742   FuncInfo->setVarArgsGPRIndex(GPRIdx);
6743   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
6744 
6745   if (Subtarget->hasFPARMv8() && !IsWin64) {
6746     auto FPRArgRegs = AArch64::getFPRArgRegs();
6747     const unsigned NumFPRArgRegs = FPRArgRegs.size();
6748     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
6749 
6750     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
6751     int FPRIdx = 0;
6752     if (FPRSaveSize != 0) {
6753       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
6754 
6755       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
6756 
6757       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
6758         Register VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
6759         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
6760 
6761         SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
6762                                      MachinePointerInfo::getStack(MF, i * 16));
6763         MemOps.push_back(Store);
6764         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
6765                           DAG.getConstant(16, DL, PtrVT));
6766       }
6767     }
6768     FuncInfo->setVarArgsFPRIndex(FPRIdx);
6769     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
6770   }
6771 
6772   if (!MemOps.empty()) {
6773     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6774   }
6775 }
6776 
6777 /// LowerCallResult - Lower the result values of a call into the
6778 /// appropriate copies out of appropriate physical registers.
6779 SDValue AArch64TargetLowering::LowerCallResult(
6780     SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
6781     const SmallVectorImpl<CCValAssign> &RVLocs, const SDLoc &DL,
6782     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
6783     SDValue ThisVal) const {
6784   DenseMap<unsigned, SDValue> CopiedRegs;
6785   // Copy all of the result registers out of their specified physreg.
6786   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6787     CCValAssign VA = RVLocs[i];
6788 
6789     // Pass 'this' value directly from the argument to return value, to avoid
6790     // reg unit interference
6791     if (i == 0 && isThisReturn) {
6792       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
6793              "unexpected return calling convention register assignment");
6794       InVals.push_back(ThisVal);
6795       continue;
6796     }
6797 
6798     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
6799     // allows one use of a physreg per block.
6800     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
6801     if (!Val) {
6802       Val =
6803           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
6804       Chain = Val.getValue(1);
6805       InGlue = Val.getValue(2);
6806       CopiedRegs[VA.getLocReg()] = Val;
6807     }
6808 
6809     switch (VA.getLocInfo()) {
6810     default:
6811       llvm_unreachable("Unknown loc info!");
6812     case CCValAssign::Full:
6813       break;
6814     case CCValAssign::BCvt:
6815       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
6816       break;
6817     case CCValAssign::AExtUpper:
6818       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
6819                         DAG.getConstant(32, DL, VA.getLocVT()));
6820       [[fallthrough]];
6821     case CCValAssign::AExt:
6822       [[fallthrough]];
6823     case CCValAssign::ZExt:
6824       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
6825       break;
6826     }
6827 
6828     InVals.push_back(Val);
6829   }
6830 
6831   return Chain;
6832 }
6833 
6834 /// Return true if the calling convention is one that we can guarantee TCO for.
6835 static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
6836   return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
6837          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
6838 }
6839 
6840 /// Return true if we might ever do TCO for calls with this calling convention.
6841 static bool mayTailCallThisCC(CallingConv::ID CC) {
6842   switch (CC) {
6843   case CallingConv::C:
6844   case CallingConv::AArch64_SVE_VectorCall:
6845   case CallingConv::PreserveMost:
6846   case CallingConv::PreserveAll:
6847   case CallingConv::Swift:
6848   case CallingConv::SwiftTail:
6849   case CallingConv::Tail:
6850   case CallingConv::Fast:
6851     return true;
6852   default:
6853     return false;
6854   }
6855 }
6856 
6857 static void analyzeCallOperands(const AArch64TargetLowering &TLI,
6858                                 const AArch64Subtarget *Subtarget,
6859                                 const TargetLowering::CallLoweringInfo &CLI,
6860                                 CCState &CCInfo) {
6861   const SelectionDAG &DAG = CLI.DAG;
6862   CallingConv::ID CalleeCC = CLI.CallConv;
6863   bool IsVarArg = CLI.IsVarArg;
6864   const SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
6865   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
6866 
6867   unsigned NumArgs = Outs.size();
6868   for (unsigned i = 0; i != NumArgs; ++i) {
6869     MVT ArgVT = Outs[i].VT;
6870     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
6871 
6872     bool UseVarArgCC = false;
6873     if (IsVarArg) {
6874       // On Windows, the fixed arguments in a vararg call are passed in GPRs
6875       // too, so use the vararg CC to force them to integer registers.
6876       if (IsCalleeWin64) {
6877         UseVarArgCC = true;
6878       } else {
6879         UseVarArgCC = !Outs[i].IsFixed;
6880       }
6881     }
6882 
6883     if (!UseVarArgCC) {
6884       // Get type of the original argument.
6885       EVT ActualVT =
6886           TLI.getValueType(DAG.getDataLayout(), CLI.Args[Outs[i].OrigArgIndex].Ty,
6887                        /*AllowUnknown*/ true);
6888       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ArgVT;
6889       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
6890       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
6891         ArgVT = MVT::i8;
6892       else if (ActualMVT == MVT::i16)
6893         ArgVT = MVT::i16;
6894     }
6895 
6896     CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CalleeCC, UseVarArgCC);
6897     bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
6898     assert(!Res && "Call operand has unhandled type");
6899     (void)Res;
6900   }
6901 }
6902 
6903 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
6904     const CallLoweringInfo &CLI) const {
6905   CallingConv::ID CalleeCC = CLI.CallConv;
6906   if (!mayTailCallThisCC(CalleeCC))
6907     return false;
6908 
6909   SDValue Callee = CLI.Callee;
6910   bool IsVarArg = CLI.IsVarArg;
6911   const SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
6912   const SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
6913   const SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
6914   const SelectionDAG &DAG = CLI.DAG;
6915   MachineFunction &MF = DAG.getMachineFunction();
6916   const Function &CallerF = MF.getFunction();
6917   CallingConv::ID CallerCC = CallerF.getCallingConv();
6918 
6919   // SME Streaming functions are not eligible for TCO as they may require
6920   // the streaming mode or ZA to be restored after returning from the call.
6921   SMEAttrs CallerAttrs(MF.getFunction());
6922   auto CalleeAttrs = CLI.CB ? SMEAttrs(*CLI.CB) : SMEAttrs(SMEAttrs::Normal);
6923   if (CallerAttrs.requiresSMChange(CalleeAttrs) ||
6924       CallerAttrs.requiresLazySave(CalleeAttrs))
6925     return false;
6926 
6927   // Functions using the C or Fast calling convention that have an SVE signature
6928   // preserve more registers and should assume the SVE_VectorCall CC.
6929   // The check for matching callee-saved regs will determine whether it is
6930   // eligible for TCO.
6931   if ((CallerCC == CallingConv::C || CallerCC == CallingConv::Fast) &&
6932       MF.getInfo<AArch64FunctionInfo>()->isSVECC())
6933     CallerCC = CallingConv::AArch64_SVE_VectorCall;
6934 
6935   bool CCMatch = CallerCC == CalleeCC;
6936 
6937   // When using the Windows calling convention on a non-windows OS, we want
6938   // to back up and restore X18 in such functions; we can't do a tail call
6939   // from those functions.
6940   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
6941       CalleeCC != CallingConv::Win64)
6942     return false;
6943 
6944   // Byval parameters hand the function a pointer directly into the stack area
6945   // we want to reuse during a tail call. Working around this *is* possible (see
6946   // X86) but less efficient and uglier in LowerCall.
6947   for (Function::const_arg_iterator i = CallerF.arg_begin(),
6948                                     e = CallerF.arg_end();
6949        i != e; ++i) {
6950     if (i->hasByValAttr())
6951       return false;
6952 
6953     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
6954     // In this case, it is necessary to save/restore X0 in the callee. Tail
6955     // call opt interferes with this. So we disable tail call opt when the
6956     // caller has an argument with "inreg" attribute.
6957 
6958     // FIXME: Check whether the callee also has an "inreg" argument.
6959     if (i->hasInRegAttr())
6960       return false;
6961   }
6962 
6963   if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
6964     return CCMatch;
6965 
6966   // Externally-defined functions with weak linkage should not be
6967   // tail-called on AArch64 when the OS does not support dynamic
6968   // pre-emption of symbols, as the AAELF spec requires normal calls
6969   // to undefined weak functions to be replaced with a NOP or jump to the
6970   // next instruction. The behaviour of branch instructions in this
6971   // situation (as used for tail calls) is implementation-defined, so we
6972   // cannot rely on the linker replacing the tail call with a return.
6973   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
6974     const GlobalValue *GV = G->getGlobal();
6975     const Triple &TT = getTargetMachine().getTargetTriple();
6976     if (GV->hasExternalWeakLinkage() &&
6977         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
6978       return false;
6979   }
6980 
6981   // Now we search for cases where we can use a tail call without changing the
6982   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
6983   // concept.
6984 
6985   // I want anyone implementing a new calling convention to think long and hard
6986   // about this assert.
6987   assert((!IsVarArg || CalleeCC == CallingConv::C) &&
6988          "Unexpected variadic calling convention");
6989 
6990   LLVMContext &C = *DAG.getContext();
6991   // Check that the call results are passed in the same way.
6992   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
6993                                   CCAssignFnForCall(CalleeCC, IsVarArg),
6994                                   CCAssignFnForCall(CallerCC, IsVarArg)))
6995     return false;
6996   // The callee has to preserve all registers the caller needs to preserve.
6997   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6998   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
6999   if (!CCMatch) {
7000     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
7001     if (Subtarget->hasCustomCallingConv()) {
7002       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
7003       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
7004     }
7005     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
7006       return false;
7007   }
7008 
7009   // Nothing more to check if the callee is taking no arguments
7010   if (Outs.empty())
7011     return true;
7012 
7013   SmallVector<CCValAssign, 16> ArgLocs;
7014   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
7015 
7016   analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
7017 
7018   if (IsVarArg && !(CLI.CB && CLI.CB->isMustTailCall())) {
7019     // When we are musttail, additional checks have been done and we can safely ignore this check
7020     // At least two cases here: if caller is fastcc then we can't have any
7021     // memory arguments (we'd be expected to clean up the stack afterwards). If
7022     // caller is C then we could potentially use its argument area.
7023 
7024     // FIXME: for now we take the most conservative of these in both cases:
7025     // disallow all variadic memory operands.
7026     for (const CCValAssign &ArgLoc : ArgLocs)
7027       if (!ArgLoc.isRegLoc())
7028         return false;
7029   }
7030 
7031   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
7032 
7033   // If any of the arguments is passed indirectly, it must be SVE, so the
7034   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
7035   // allocate space on the stack. That is why we determine this explicitly here
7036   // the call cannot be a tailcall.
7037   if (llvm::any_of(ArgLocs, [&](CCValAssign &A) {
7038         assert((A.getLocInfo() != CCValAssign::Indirect ||
7039                 A.getValVT().isScalableVector() ||
7040                 Subtarget->isWindowsArm64EC()) &&
7041                "Expected value to be scalable");
7042         return A.getLocInfo() == CCValAssign::Indirect;
7043       }))
7044     return false;
7045 
7046   // If the stack arguments for this call do not fit into our own save area then
7047   // the call cannot be made tail.
7048   if (CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea())
7049     return false;
7050 
7051   const MachineRegisterInfo &MRI = MF.getRegInfo();
7052   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
7053     return false;
7054 
7055   return true;
7056 }
7057 
7058 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
7059                                                    SelectionDAG &DAG,
7060                                                    MachineFrameInfo &MFI,
7061                                                    int ClobberedFI) const {
7062   SmallVector<SDValue, 8> ArgChains;
7063   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
7064   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
7065 
7066   // Include the original chain at the beginning of the list. When this is
7067   // used by target LowerCall hooks, this helps legalize find the
7068   // CALLSEQ_BEGIN node.
7069   ArgChains.push_back(Chain);
7070 
7071   // Add a chain value for each stack argument corresponding
7072   for (SDNode *U : DAG.getEntryNode().getNode()->uses())
7073     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
7074       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
7075         if (FI->getIndex() < 0) {
7076           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
7077           int64_t InLastByte = InFirstByte;
7078           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
7079 
7080           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
7081               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
7082             ArgChains.push_back(SDValue(L, 1));
7083         }
7084 
7085   // Build a tokenfactor for all the chains.
7086   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
7087 }
7088 
7089 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
7090                                                    bool TailCallOpt) const {
7091   return (CallCC == CallingConv::Fast && TailCallOpt) ||
7092          CallCC == CallingConv::Tail || CallCC == CallingConv::SwiftTail;
7093 }
7094 
7095 // Check if the value is zero-extended from i1 to i8
7096 static bool checkZExtBool(SDValue Arg, const SelectionDAG &DAG) {
7097   unsigned SizeInBits = Arg.getValueType().getSizeInBits();
7098   if (SizeInBits < 8)
7099     return false;
7100 
7101   APInt RequredZero(SizeInBits, 0xFE);
7102   KnownBits Bits = DAG.computeKnownBits(Arg, 4);
7103   bool ZExtBool = (Bits.Zero & RequredZero) == RequredZero;
7104   return ZExtBool;
7105 }
7106 
7107 SDValue AArch64TargetLowering::changeStreamingMode(
7108     SelectionDAG &DAG, SDLoc DL, bool Enable,
7109     SDValue Chain, SDValue InGlue, SDValue PStateSM, bool Entry) const {
7110   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7111   SDValue RegMask = DAG.getRegisterMask(TRI->getSMStartStopCallPreservedMask());
7112   SDValue MSROp =
7113       DAG.getTargetConstant((int32_t)AArch64SVCR::SVCRSM, DL, MVT::i32);
7114 
7115   SDValue ExpectedSMVal =
7116       DAG.getTargetConstant(Entry ? Enable : !Enable, DL, MVT::i64);
7117   SmallVector<SDValue> Ops = {Chain, MSROp, PStateSM, ExpectedSMVal, RegMask};
7118 
7119   if (InGlue)
7120     Ops.push_back(InGlue);
7121 
7122   unsigned Opcode = Enable ? AArch64ISD::SMSTART : AArch64ISD::SMSTOP;
7123   return DAG.getNode(Opcode, DL, DAG.getVTList(MVT::Other, MVT::Glue), Ops);
7124 }
7125 
7126 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
7127 /// and add input and output parameter nodes.
7128 SDValue
7129 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
7130                                  SmallVectorImpl<SDValue> &InVals) const {
7131   SelectionDAG &DAG = CLI.DAG;
7132   SDLoc &DL = CLI.DL;
7133   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
7134   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
7135   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
7136   SDValue Chain = CLI.Chain;
7137   SDValue Callee = CLI.Callee;
7138   bool &IsTailCall = CLI.IsTailCall;
7139   CallingConv::ID &CallConv = CLI.CallConv;
7140   bool IsVarArg = CLI.IsVarArg;
7141 
7142   MachineFunction &MF = DAG.getMachineFunction();
7143   MachineFunction::CallSiteInfo CSInfo;
7144   bool IsThisReturn = false;
7145 
7146   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
7147   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
7148   bool IsCFICall = CLI.CB && CLI.CB->isIndirectCall() && CLI.CFIType;
7149   bool IsSibCall = false;
7150   bool GuardWithBTI = false;
7151 
7152   if (CLI.CB && CLI.CB->hasFnAttr(Attribute::ReturnsTwice) &&
7153       !Subtarget->noBTIAtReturnTwice()) {
7154     GuardWithBTI = FuncInfo->branchTargetEnforcement();
7155   }
7156 
7157   // Analyze operands of the call, assigning locations to each operand.
7158   SmallVector<CCValAssign, 16> ArgLocs;
7159   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
7160 
7161   if (IsVarArg) {
7162     unsigned NumArgs = Outs.size();
7163 
7164     for (unsigned i = 0; i != NumArgs; ++i) {
7165       if (!Outs[i].IsFixed && Outs[i].VT.isScalableVector())
7166         report_fatal_error("Passing SVE types to variadic functions is "
7167                            "currently not supported");
7168     }
7169   }
7170 
7171   analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
7172 
7173   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
7174   // Assign locations to each value returned by this call.
7175   SmallVector<CCValAssign, 16> RVLocs;
7176   CCState RetCCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
7177                     *DAG.getContext());
7178   RetCCInfo.AnalyzeCallResult(Ins, RetCC);
7179 
7180   // Check callee args/returns for SVE registers and set calling convention
7181   // accordingly.
7182   if (CallConv == CallingConv::C || CallConv == CallingConv::Fast) {
7183     auto HasSVERegLoc = [](CCValAssign &Loc) {
7184       if (!Loc.isRegLoc())
7185         return false;
7186       return AArch64::ZPRRegClass.contains(Loc.getLocReg()) ||
7187              AArch64::PPRRegClass.contains(Loc.getLocReg());
7188     };
7189     if (any_of(RVLocs, HasSVERegLoc) || any_of(ArgLocs, HasSVERegLoc))
7190       CallConv = CallingConv::AArch64_SVE_VectorCall;
7191   }
7192 
7193   if (IsTailCall) {
7194     // Check if it's really possible to do a tail call.
7195     IsTailCall = isEligibleForTailCallOptimization(CLI);
7196 
7197     // A sibling call is one where we're under the usual C ABI and not planning
7198     // to change that but can still do a tail call:
7199     if (!TailCallOpt && IsTailCall && CallConv != CallingConv::Tail &&
7200         CallConv != CallingConv::SwiftTail)
7201       IsSibCall = true;
7202 
7203     if (IsTailCall)
7204       ++NumTailCalls;
7205   }
7206 
7207   if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
7208     report_fatal_error("failed to perform tail call elimination on a call "
7209                        "site marked musttail");
7210 
7211   // Get a count of how many bytes are to be pushed on the stack.
7212   unsigned NumBytes = CCInfo.getStackSize();
7213 
7214   if (IsSibCall) {
7215     // Since we're not changing the ABI to make this a tail call, the memory
7216     // operands are already available in the caller's incoming argument space.
7217     NumBytes = 0;
7218   }
7219 
7220   // FPDiff is the byte offset of the call's argument area from the callee's.
7221   // Stores to callee stack arguments will be placed in FixedStackSlots offset
7222   // by this amount for a tail call. In a sibling call it must be 0 because the
7223   // caller will deallocate the entire stack and the callee still expects its
7224   // arguments to begin at SP+0. Completely unused for non-tail calls.
7225   int FPDiff = 0;
7226 
7227   if (IsTailCall && !IsSibCall) {
7228     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
7229 
7230     // Since callee will pop argument stack as a tail call, we must keep the
7231     // popped size 16-byte aligned.
7232     NumBytes = alignTo(NumBytes, 16);
7233 
7234     // FPDiff will be negative if this tail call requires more space than we
7235     // would automatically have in our incoming argument space. Positive if we
7236     // can actually shrink the stack.
7237     FPDiff = NumReusableBytes - NumBytes;
7238 
7239     // Update the required reserved area if this is the tail call requiring the
7240     // most argument stack space.
7241     if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
7242       FuncInfo->setTailCallReservedStack(-FPDiff);
7243 
7244     // The stack pointer must be 16-byte aligned at all times it's used for a
7245     // memory operation, which in practice means at *all* times and in
7246     // particular across call boundaries. Therefore our own arguments started at
7247     // a 16-byte aligned SP and the delta applied for the tail call should
7248     // satisfy the same constraint.
7249     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
7250   }
7251 
7252   // Determine whether we need any streaming mode changes.
7253   SMEAttrs CalleeAttrs, CallerAttrs(MF.getFunction());
7254   if (CLI.CB)
7255     CalleeAttrs = SMEAttrs(*CLI.CB);
7256   else if (std::optional<SMEAttrs> Attrs =
7257                getCalleeAttrsFromExternalFunction(CLI.Callee))
7258     CalleeAttrs = *Attrs;
7259 
7260   bool RequiresLazySave = CallerAttrs.requiresLazySave(CalleeAttrs);
7261 
7262   MachineFrameInfo &MFI = MF.getFrameInfo();
7263   if (RequiresLazySave) {
7264     // Set up a lazy save mechanism by storing the runtime live slices
7265     // (worst-case N*N) to the TPIDR2 stack object.
7266     SDValue N = DAG.getNode(AArch64ISD::RDSVL, DL, MVT::i64,
7267                             DAG.getConstant(1, DL, MVT::i32));
7268     SDValue NN = DAG.getNode(ISD::MUL, DL, MVT::i64, N, N);
7269     unsigned TPIDR2Obj = FuncInfo->getLazySaveTPIDR2Obj();
7270 
7271     MachinePointerInfo MPI = MachinePointerInfo::getStack(MF, TPIDR2Obj);
7272     SDValue TPIDR2ObjAddr = DAG.getFrameIndex(TPIDR2Obj,
7273         DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
7274     SDValue BufferPtrAddr =
7275         DAG.getNode(ISD::ADD, DL, TPIDR2ObjAddr.getValueType(), TPIDR2ObjAddr,
7276                     DAG.getConstant(8, DL, TPIDR2ObjAddr.getValueType()));
7277     Chain = DAG.getTruncStore(Chain, DL, NN, BufferPtrAddr, MPI, MVT::i16);
7278     Chain = DAG.getNode(
7279         ISD::INTRINSIC_VOID, DL, MVT::Other, Chain,
7280         DAG.getConstant(Intrinsic::aarch64_sme_set_tpidr2, DL, MVT::i32),
7281         TPIDR2ObjAddr);
7282   }
7283 
7284   SDValue PStateSM;
7285   std::optional<bool> RequiresSMChange =
7286       CallerAttrs.requiresSMChange(CalleeAttrs);
7287   if (RequiresSMChange)
7288     PStateSM = getPStateSM(DAG, Chain, CallerAttrs, DL, MVT::i64);
7289 
7290   // Adjust the stack pointer for the new arguments...
7291   // These operations are automatically eliminated by the prolog/epilog pass
7292   if (!IsSibCall)
7293     Chain = DAG.getCALLSEQ_START(Chain, IsTailCall ? 0 : NumBytes, 0, DL);
7294 
7295   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
7296                                         getPointerTy(DAG.getDataLayout()));
7297 
7298   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7299   SmallSet<unsigned, 8> RegsUsed;
7300   SmallVector<SDValue, 8> MemOpChains;
7301   auto PtrVT = getPointerTy(DAG.getDataLayout());
7302 
7303   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
7304     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
7305     for (const auto &F : Forwards) {
7306       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
7307        RegsToPass.emplace_back(F.PReg, Val);
7308     }
7309   }
7310 
7311   // Walk the register/memloc assignments, inserting copies/loads.
7312   unsigned ExtraArgLocs = 0;
7313   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
7314     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
7315     SDValue Arg = OutVals[i];
7316     ISD::ArgFlagsTy Flags = Outs[i].Flags;
7317 
7318     // Promote the value if needed.
7319     switch (VA.getLocInfo()) {
7320     default:
7321       llvm_unreachable("Unknown loc info!");
7322     case CCValAssign::Full:
7323       break;
7324     case CCValAssign::SExt:
7325       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
7326       break;
7327     case CCValAssign::ZExt:
7328       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
7329       break;
7330     case CCValAssign::AExt:
7331       if (Outs[i].ArgVT == MVT::i1) {
7332         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
7333         //
7334         // Check if we actually have to do this, because the value may
7335         // already be zero-extended.
7336         //
7337         // We cannot just emit a (zext i8 (trunc (assert-zext i8)))
7338         // and rely on DAGCombiner to fold this, because the following
7339         // (anyext i32) is combined with (zext i8) in DAG.getNode:
7340         //
7341         //   (ext (zext x)) -> (zext x)
7342         //
7343         // This will give us (zext i32), which we cannot remove, so
7344         // try to check this beforehand.
7345         if (!checkZExtBool(Arg, DAG)) {
7346           Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
7347           Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
7348         }
7349       }
7350       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
7351       break;
7352     case CCValAssign::AExtUpper:
7353       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
7354       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
7355       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
7356                         DAG.getConstant(32, DL, VA.getLocVT()));
7357       break;
7358     case CCValAssign::BCvt:
7359       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
7360       break;
7361     case CCValAssign::Trunc:
7362       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
7363       break;
7364     case CCValAssign::FPExt:
7365       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
7366       break;
7367     case CCValAssign::Indirect:
7368       bool isScalable = VA.getValVT().isScalableVT();
7369       assert((isScalable || Subtarget->isWindowsArm64EC()) &&
7370              "Indirect arguments should be scalable on most subtargets");
7371 
7372       uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinValue();
7373       uint64_t PartSize = StoreSize;
7374       unsigned NumParts = 1;
7375       if (Outs[i].Flags.isInConsecutiveRegs()) {
7376         assert(!Outs[i].Flags.isInConsecutiveRegsLast());
7377         while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
7378           ++NumParts;
7379         StoreSize *= NumParts;
7380       }
7381 
7382       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
7383       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
7384       int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
7385       if (isScalable)
7386         MFI.setStackID(FI, TargetStackID::ScalableVector);
7387 
7388       MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7389       SDValue Ptr = DAG.getFrameIndex(
7390           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
7391       SDValue SpillSlot = Ptr;
7392 
7393       // Ensure we generate all stores for each tuple part, whilst updating the
7394       // pointer after each store correctly using vscale.
7395       while (NumParts) {
7396         SDValue Store = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
7397         MemOpChains.push_back(Store);
7398 
7399         NumParts--;
7400         if (NumParts > 0) {
7401           SDValue BytesIncrement;
7402           if (isScalable) {
7403             BytesIncrement = DAG.getVScale(
7404                 DL, Ptr.getValueType(),
7405                 APInt(Ptr.getValueSizeInBits().getFixedValue(), PartSize));
7406           } else {
7407             BytesIncrement = DAG.getConstant(
7408                 APInt(Ptr.getValueSizeInBits().getFixedValue(), PartSize), DL,
7409                 Ptr.getValueType());
7410           }
7411           SDNodeFlags Flags;
7412           Flags.setNoUnsignedWrap(true);
7413 
7414           MPI = MachinePointerInfo(MPI.getAddrSpace());
7415           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7416                             BytesIncrement, Flags);
7417           ExtraArgLocs++;
7418           i++;
7419         }
7420       }
7421 
7422       Arg = SpillSlot;
7423       break;
7424     }
7425 
7426     if (VA.isRegLoc()) {
7427       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
7428           Outs[0].VT == MVT::i64) {
7429         assert(VA.getLocVT() == MVT::i64 &&
7430                "unexpected calling convention register assignment");
7431         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
7432                "unexpected use of 'returned'");
7433         IsThisReturn = true;
7434       }
7435       if (RegsUsed.count(VA.getLocReg())) {
7436         // If this register has already been used then we're trying to pack
7437         // parts of an [N x i32] into an X-register. The extension type will
7438         // take care of putting the two halves in the right place but we have to
7439         // combine them.
7440         SDValue &Bits =
7441             llvm::find_if(RegsToPass,
7442                           [=](const std::pair<unsigned, SDValue> &Elt) {
7443                             return Elt.first == VA.getLocReg();
7444                           })
7445                 ->second;
7446         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
7447         // Call site info is used for function's parameter entry value
7448         // tracking. For now we track only simple cases when parameter
7449         // is transferred through whole register.
7450         llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
7451           return ArgReg.Reg == VA.getLocReg();
7452         });
7453       } else {
7454         // Add an extra level of indirection for streaming mode changes by
7455         // using a pseudo copy node that cannot be rematerialised between a
7456         // smstart/smstop and the call by the simple register coalescer.
7457         if (RequiresSMChange && isa<FrameIndexSDNode>(Arg))
7458           Arg = DAG.getNode(AArch64ISD::OBSCURE_COPY, DL, MVT::i64, Arg);
7459         RegsToPass.emplace_back(VA.getLocReg(), Arg);
7460         RegsUsed.insert(VA.getLocReg());
7461         const TargetOptions &Options = DAG.getTarget().Options;
7462         if (Options.EmitCallSiteInfo)
7463           CSInfo.emplace_back(VA.getLocReg(), i);
7464       }
7465     } else {
7466       assert(VA.isMemLoc());
7467 
7468       SDValue DstAddr;
7469       MachinePointerInfo DstInfo;
7470 
7471       // FIXME: This works on big-endian for composite byvals, which are the
7472       // common case. It should also work for fundamental types too.
7473       uint32_t BEAlign = 0;
7474       unsigned OpSize;
7475       if (VA.getLocInfo() == CCValAssign::Indirect ||
7476           VA.getLocInfo() == CCValAssign::Trunc)
7477         OpSize = VA.getLocVT().getFixedSizeInBits();
7478       else
7479         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
7480                                  : VA.getValVT().getSizeInBits();
7481       OpSize = (OpSize + 7) / 8;
7482       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
7483           !Flags.isInConsecutiveRegs()) {
7484         if (OpSize < 8)
7485           BEAlign = 8 - OpSize;
7486       }
7487       unsigned LocMemOffset = VA.getLocMemOffset();
7488       int32_t Offset = LocMemOffset + BEAlign;
7489       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
7490       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
7491 
7492       if (IsTailCall) {
7493         Offset = Offset + FPDiff;
7494         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
7495 
7496         DstAddr = DAG.getFrameIndex(FI, PtrVT);
7497         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
7498 
7499         // Make sure any stack arguments overlapping with where we're storing
7500         // are loaded before this eventual operation. Otherwise they'll be
7501         // clobbered.
7502         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
7503       } else {
7504         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
7505 
7506         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
7507         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
7508       }
7509 
7510       if (Outs[i].Flags.isByVal()) {
7511         SDValue SizeNode =
7512             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
7513         SDValue Cpy = DAG.getMemcpy(
7514             Chain, DL, DstAddr, Arg, SizeNode,
7515             Outs[i].Flags.getNonZeroByValAlign(),
7516             /*isVol = */ false, /*AlwaysInline = */ false,
7517             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
7518 
7519         MemOpChains.push_back(Cpy);
7520       } else {
7521         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
7522         // promoted to a legal register type i32, we should truncate Arg back to
7523         // i1/i8/i16.
7524         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
7525             VA.getValVT() == MVT::i16)
7526           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
7527 
7528         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
7529         MemOpChains.push_back(Store);
7530       }
7531     }
7532   }
7533 
7534   if (IsVarArg && Subtarget->isWindowsArm64EC()) {
7535     // For vararg calls, the Arm64EC ABI requires values in x4 and x5
7536     // describing the argument list.  x4 contains the address of the
7537     // first stack parameter. x5 contains the size in bytes of all parameters
7538     // passed on the stack.
7539     RegsToPass.emplace_back(AArch64::X4, StackPtr);
7540     RegsToPass.emplace_back(AArch64::X5,
7541                             DAG.getConstant(NumBytes, DL, MVT::i64));
7542   }
7543 
7544   if (!MemOpChains.empty())
7545     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
7546 
7547   SDValue InGlue;
7548   if (RequiresSMChange) {
7549     SDValue NewChain = changeStreamingMode(DAG, DL, *RequiresSMChange, Chain,
7550                                            InGlue, PStateSM, true);
7551     Chain = NewChain.getValue(0);
7552     InGlue = NewChain.getValue(1);
7553   }
7554 
7555   // Build a sequence of copy-to-reg nodes chained together with token chain
7556   // and flag operands which copy the outgoing args into the appropriate regs.
7557   for (auto &RegToPass : RegsToPass) {
7558     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
7559                              RegToPass.second, InGlue);
7560     InGlue = Chain.getValue(1);
7561   }
7562 
7563   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
7564   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
7565   // node so that legalize doesn't hack it.
7566   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
7567     auto GV = G->getGlobal();
7568     unsigned OpFlags =
7569         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
7570     if (OpFlags & AArch64II::MO_GOT) {
7571       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
7572       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
7573     } else {
7574       const GlobalValue *GV = G->getGlobal();
7575       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
7576     }
7577   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
7578     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
7579         Subtarget->isTargetMachO()) {
7580       const char *Sym = S->getSymbol();
7581       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
7582       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
7583     } else {
7584       const char *Sym = S->getSymbol();
7585       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
7586     }
7587   }
7588 
7589   // We don't usually want to end the call-sequence here because we would tidy
7590   // the frame up *after* the call, however in the ABI-changing tail-call case
7591   // we've carefully laid out the parameters so that when sp is reset they'll be
7592   // in the correct location.
7593   if (IsTailCall && !IsSibCall) {
7594     Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
7595     InGlue = Chain.getValue(1);
7596   }
7597 
7598   std::vector<SDValue> Ops;
7599   Ops.push_back(Chain);
7600   Ops.push_back(Callee);
7601 
7602   if (IsTailCall) {
7603     // Each tail call may have to adjust the stack by a different amount, so
7604     // this information must travel along with the operation for eventual
7605     // consumption by emitEpilogue.
7606     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
7607   }
7608 
7609   // Add argument registers to the end of the list so that they are known live
7610   // into the call.
7611   for (auto &RegToPass : RegsToPass)
7612     Ops.push_back(DAG.getRegister(RegToPass.first,
7613                                   RegToPass.second.getValueType()));
7614 
7615   // Add a register mask operand representing the call-preserved registers.
7616   const uint32_t *Mask;
7617   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7618   if (IsThisReturn) {
7619     // For 'this' returns, use the X0-preserving mask if applicable
7620     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
7621     if (!Mask) {
7622       IsThisReturn = false;
7623       Mask = TRI->getCallPreservedMask(MF, CallConv);
7624     }
7625   } else
7626     Mask = TRI->getCallPreservedMask(MF, CallConv);
7627 
7628   if (Subtarget->hasCustomCallingConv())
7629     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
7630 
7631   if (TRI->isAnyArgRegReserved(MF))
7632     TRI->emitReservedArgRegCallError(MF);
7633 
7634   assert(Mask && "Missing call preserved mask for calling convention");
7635   Ops.push_back(DAG.getRegisterMask(Mask));
7636 
7637   if (InGlue.getNode())
7638     Ops.push_back(InGlue);
7639 
7640   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7641 
7642   // If we're doing a tall call, use a TC_RETURN here rather than an
7643   // actual call instruction.
7644   if (IsTailCall) {
7645     MF.getFrameInfo().setHasTailCall();
7646     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
7647 
7648     if (IsCFICall)
7649       Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
7650 
7651     DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
7652     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
7653     return Ret;
7654   }
7655 
7656   unsigned CallOpc = AArch64ISD::CALL;
7657   // Calls with operand bundle "clang.arc.attachedcall" are special. They should
7658   // be expanded to the call, directly followed by a special marker sequence and
7659   // a call to an ObjC library function.  Use CALL_RVMARKER to do that.
7660   if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
7661     assert(!IsTailCall &&
7662            "tail calls cannot be marked with clang.arc.attachedcall");
7663     CallOpc = AArch64ISD::CALL_RVMARKER;
7664 
7665     // Add a target global address for the retainRV/claimRV runtime function
7666     // just before the call target.
7667     Function *ARCFn = *objcarc::getAttachedARCFunction(CLI.CB);
7668     auto GA = DAG.getTargetGlobalAddress(ARCFn, DL, PtrVT);
7669     Ops.insert(Ops.begin() + 1, GA);
7670   } else if (GuardWithBTI)
7671     CallOpc = AArch64ISD::CALL_BTI;
7672 
7673   // Returns a chain and a flag for retval copy to use.
7674   Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
7675 
7676   if (IsCFICall)
7677     Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
7678 
7679   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
7680   InGlue = Chain.getValue(1);
7681   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
7682 
7683   uint64_t CalleePopBytes =
7684       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
7685 
7686   Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, DL);
7687   InGlue = Chain.getValue(1);
7688 
7689   // Handle result values, copying them out of physregs into vregs that we
7690   // return.
7691   SDValue Result = LowerCallResult(Chain, InGlue, CallConv, IsVarArg, RVLocs,
7692                                    DL, DAG, InVals, IsThisReturn,
7693                                    IsThisReturn ? OutVals[0] : SDValue());
7694 
7695   if (!Ins.empty())
7696     InGlue = Result.getValue(Result->getNumValues() - 1);
7697 
7698   if (RequiresSMChange) {
7699     assert(PStateSM && "Expected a PStateSM to be set");
7700     Result = changeStreamingMode(DAG, DL, !*RequiresSMChange, Result, InGlue,
7701                                  PStateSM, false);
7702   }
7703 
7704   if (RequiresLazySave) {
7705     // Unconditionally resume ZA.
7706     Result = DAG.getNode(
7707         AArch64ISD::SMSTART, DL, MVT::Other, Result,
7708         DAG.getTargetConstant((int32_t)(AArch64SVCR::SVCRZA), DL, MVT::i32),
7709         DAG.getConstant(0, DL, MVT::i64), DAG.getConstant(1, DL, MVT::i64));
7710 
7711     // Conditionally restore the lazy save using a pseudo node.
7712     unsigned FI = FuncInfo->getLazySaveTPIDR2Obj();
7713     SDValue RegMask = DAG.getRegisterMask(
7714         TRI->SMEABISupportRoutinesCallPreservedMaskFromX0());
7715     SDValue RestoreRoutine = DAG.getTargetExternalSymbol(
7716         "__arm_tpidr2_restore", getPointerTy(DAG.getDataLayout()));
7717     SDValue TPIDR2_EL0 = DAG.getNode(
7718         ISD::INTRINSIC_W_CHAIN, DL, MVT::i64, Result,
7719         DAG.getConstant(Intrinsic::aarch64_sme_get_tpidr2, DL, MVT::i32));
7720 
7721     // Copy the address of the TPIDR2 block into X0 before 'calling' the
7722     // RESTORE_ZA pseudo.
7723     SDValue Glue;
7724     SDValue TPIDR2Block = DAG.getFrameIndex(
7725         FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
7726     Result = DAG.getCopyToReg(Result, DL, AArch64::X0, TPIDR2Block, Glue);
7727     Result = DAG.getNode(AArch64ISD::RESTORE_ZA, DL, MVT::Other,
7728                          {Result, TPIDR2_EL0,
7729                           DAG.getRegister(AArch64::X0, MVT::i64),
7730                           RestoreRoutine,
7731                           RegMask,
7732                           Result.getValue(1)});
7733 
7734     // Finally reset the TPIDR2_EL0 register to 0.
7735     Result = DAG.getNode(
7736         ISD::INTRINSIC_VOID, DL, MVT::Other, Result,
7737         DAG.getConstant(Intrinsic::aarch64_sme_set_tpidr2, DL, MVT::i32),
7738         DAG.getConstant(0, DL, MVT::i64));
7739   }
7740 
7741   if (RequiresSMChange || RequiresLazySave) {
7742     for (unsigned I = 0; I < InVals.size(); ++I) {
7743       // The smstart/smstop is chained as part of the call, but when the
7744       // resulting chain is discarded (which happens when the call is not part
7745       // of a chain, e.g. a call to @llvm.cos()), we need to ensure the
7746       // smstart/smstop is chained to the result value. We can do that by doing
7747       // a vreg -> vreg copy.
7748       Register Reg = MF.getRegInfo().createVirtualRegister(
7749           getRegClassFor(InVals[I].getValueType().getSimpleVT()));
7750       SDValue X = DAG.getCopyToReg(Result, DL, Reg, InVals[I]);
7751       InVals[I] = DAG.getCopyFromReg(X, DL, Reg,
7752                                      InVals[I].getValueType());
7753     }
7754   }
7755 
7756   return Result;
7757 }
7758 
7759 bool AArch64TargetLowering::CanLowerReturn(
7760     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
7761     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
7762   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
7763   SmallVector<CCValAssign, 16> RVLocs;
7764   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7765   return CCInfo.CheckReturn(Outs, RetCC);
7766 }
7767 
7768 SDValue
7769 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7770                                    bool isVarArg,
7771                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
7772                                    const SmallVectorImpl<SDValue> &OutVals,
7773                                    const SDLoc &DL, SelectionDAG &DAG) const {
7774   auto &MF = DAG.getMachineFunction();
7775   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
7776 
7777   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
7778   SmallVector<CCValAssign, 16> RVLocs;
7779   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
7780   CCInfo.AnalyzeReturn(Outs, RetCC);
7781 
7782   // Copy the result values into the output registers.
7783   SDValue Glue;
7784   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
7785   SmallSet<unsigned, 4> RegsUsed;
7786   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
7787        ++i, ++realRVLocIdx) {
7788     CCValAssign &VA = RVLocs[i];
7789     assert(VA.isRegLoc() && "Can only return in registers!");
7790     SDValue Arg = OutVals[realRVLocIdx];
7791 
7792     switch (VA.getLocInfo()) {
7793     default:
7794       llvm_unreachable("Unknown loc info!");
7795     case CCValAssign::Full:
7796       if (Outs[i].ArgVT == MVT::i1) {
7797         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
7798         // value. This is strictly redundant on Darwin (which uses "zeroext
7799         // i1"), but will be optimised out before ISel.
7800         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
7801         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
7802       }
7803       break;
7804     case CCValAssign::BCvt:
7805       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
7806       break;
7807     case CCValAssign::AExt:
7808     case CCValAssign::ZExt:
7809       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
7810       break;
7811     case CCValAssign::AExtUpper:
7812       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
7813       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
7814       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
7815                         DAG.getConstant(32, DL, VA.getLocVT()));
7816       break;
7817     }
7818 
7819     if (RegsUsed.count(VA.getLocReg())) {
7820       SDValue &Bits =
7821           llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
7822             return Elt.first == VA.getLocReg();
7823           })->second;
7824       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
7825     } else {
7826       RetVals.emplace_back(VA.getLocReg(), Arg);
7827       RegsUsed.insert(VA.getLocReg());
7828     }
7829   }
7830 
7831   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7832 
7833   // Emit SMSTOP before returning from a locally streaming function
7834   SMEAttrs FuncAttrs(MF.getFunction());
7835   if (FuncAttrs.hasStreamingBody() && !FuncAttrs.hasStreamingInterface()) {
7836     Chain = DAG.getNode(
7837         AArch64ISD::SMSTOP, DL, DAG.getVTList(MVT::Other, MVT::Glue), Chain,
7838         DAG.getTargetConstant((int32_t)AArch64SVCR::SVCRSM, DL, MVT::i32),
7839         DAG.getConstant(1, DL, MVT::i64), DAG.getConstant(0, DL, MVT::i64),
7840         DAG.getRegisterMask(TRI->getSMStartStopCallPreservedMask()));
7841     Glue = Chain.getValue(1);
7842   }
7843 
7844   SmallVector<SDValue, 4> RetOps(1, Chain);
7845   for (auto &RetVal : RetVals) {
7846     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Glue);
7847     Glue = Chain.getValue(1);
7848     RetOps.push_back(
7849         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
7850   }
7851 
7852   // Windows AArch64 ABIs require that for returning structs by value we copy
7853   // the sret argument into X0 for the return.
7854   // We saved the argument into a virtual register in the entry block,
7855   // so now we copy the value out and into X0.
7856   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
7857     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
7858                                      getPointerTy(MF.getDataLayout()));
7859 
7860     unsigned RetValReg = AArch64::X0;
7861     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Glue);
7862     Glue = Chain.getValue(1);
7863 
7864     RetOps.push_back(
7865       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
7866   }
7867 
7868   const MCPhysReg *I = TRI->getCalleeSavedRegsViaCopy(&MF);
7869   if (I) {
7870     for (; *I; ++I) {
7871       if (AArch64::GPR64RegClass.contains(*I))
7872         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7873       else if (AArch64::FPR64RegClass.contains(*I))
7874         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7875       else
7876         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7877     }
7878   }
7879 
7880   RetOps[0] = Chain; // Update chain.
7881 
7882   // Add the glue if we have it.
7883   if (Glue.getNode())
7884     RetOps.push_back(Glue);
7885 
7886   return DAG.getNode(AArch64ISD::RET_GLUE, DL, MVT::Other, RetOps);
7887 }
7888 
7889 //===----------------------------------------------------------------------===//
7890 //  Other Lowering Code
7891 //===----------------------------------------------------------------------===//
7892 
7893 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
7894                                              SelectionDAG &DAG,
7895                                              unsigned Flag) const {
7896   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
7897                                     N->getOffset(), Flag);
7898 }
7899 
7900 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
7901                                              SelectionDAG &DAG,
7902                                              unsigned Flag) const {
7903   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
7904 }
7905 
7906 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
7907                                              SelectionDAG &DAG,
7908                                              unsigned Flag) const {
7909   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
7910                                    N->getOffset(), Flag);
7911 }
7912 
7913 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
7914                                              SelectionDAG &DAG,
7915                                              unsigned Flag) const {
7916   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
7917 }
7918 
7919 // (loadGOT sym)
7920 template <class NodeTy>
7921 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
7922                                       unsigned Flags) const {
7923   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
7924   SDLoc DL(N);
7925   EVT Ty = getPointerTy(DAG.getDataLayout());
7926   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
7927   // FIXME: Once remat is capable of dealing with instructions with register
7928   // operands, expand this into two nodes instead of using a wrapper node.
7929   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
7930 }
7931 
7932 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
7933 template <class NodeTy>
7934 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
7935                                             unsigned Flags) const {
7936   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
7937   SDLoc DL(N);
7938   EVT Ty = getPointerTy(DAG.getDataLayout());
7939   const unsigned char MO_NC = AArch64II::MO_NC;
7940   return DAG.getNode(
7941       AArch64ISD::WrapperLarge, DL, Ty,
7942       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
7943       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
7944       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
7945       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
7946 }
7947 
7948 // (addlow (adrp %hi(sym)) %lo(sym))
7949 template <class NodeTy>
7950 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
7951                                        unsigned Flags) const {
7952   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
7953   SDLoc DL(N);
7954   EVT Ty = getPointerTy(DAG.getDataLayout());
7955   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
7956   SDValue Lo = getTargetNode(N, Ty, DAG,
7957                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
7958   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
7959   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
7960 }
7961 
7962 // (adr sym)
7963 template <class NodeTy>
7964 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
7965                                            unsigned Flags) const {
7966   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
7967   SDLoc DL(N);
7968   EVT Ty = getPointerTy(DAG.getDataLayout());
7969   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
7970   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
7971 }
7972 
7973 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
7974                                                   SelectionDAG &DAG) const {
7975   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
7976   const GlobalValue *GV = GN->getGlobal();
7977   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7978 
7979   if (OpFlags != AArch64II::MO_NO_FLAG)
7980     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
7981            "unexpected offset in global node");
7982 
7983   // This also catches the large code model case for Darwin, and tiny code
7984   // model with got relocations.
7985   if ((OpFlags & AArch64II::MO_GOT) != 0) {
7986     return getGOT(GN, DAG, OpFlags);
7987   }
7988 
7989   SDValue Result;
7990   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
7991     Result = getAddrLarge(GN, DAG, OpFlags);
7992   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7993     Result = getAddrTiny(GN, DAG, OpFlags);
7994   } else {
7995     Result = getAddr(GN, DAG, OpFlags);
7996   }
7997   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7998   SDLoc DL(GN);
7999   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_DLLIMPORTAUX |
8000                  AArch64II::MO_COFFSTUB))
8001     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
8002                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
8003   return Result;
8004 }
8005 
8006 /// Convert a TLS address reference into the correct sequence of loads
8007 /// and calls to compute the variable's address (for Darwin, currently) and
8008 /// return an SDValue containing the final node.
8009 
8010 /// Darwin only has one TLS scheme which must be capable of dealing with the
8011 /// fully general situation, in the worst case. This means:
8012 ///     + "extern __thread" declaration.
8013 ///     + Defined in a possibly unknown dynamic library.
8014 ///
8015 /// The general system is that each __thread variable has a [3 x i64] descriptor
8016 /// which contains information used by the runtime to calculate the address. The
8017 /// only part of this the compiler needs to know about is the first xword, which
8018 /// contains a function pointer that must be called with the address of the
8019 /// entire descriptor in "x0".
8020 ///
8021 /// Since this descriptor may be in a different unit, in general even the
8022 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
8023 /// is:
8024 ///     adrp x0, _var@TLVPPAGE
8025 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
8026 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
8027 ///                                      ; the function pointer
8028 ///     blr x1                           ; Uses descriptor address in x0
8029 ///     ; Address of _var is now in x0.
8030 ///
8031 /// If the address of _var's descriptor *is* known to the linker, then it can
8032 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
8033 /// a slight efficiency gain.
8034 SDValue
8035 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
8036                                                    SelectionDAG &DAG) const {
8037   assert(Subtarget->isTargetDarwin() &&
8038          "This function expects a Darwin target");
8039 
8040   SDLoc DL(Op);
8041   MVT PtrVT = getPointerTy(DAG.getDataLayout());
8042   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
8043   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8044 
8045   SDValue TLVPAddr =
8046       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
8047   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
8048 
8049   // The first entry in the descriptor is a function pointer that we must call
8050   // to obtain the address of the variable.
8051   SDValue Chain = DAG.getEntryNode();
8052   SDValue FuncTLVGet = DAG.getLoad(
8053       PtrMemVT, DL, Chain, DescAddr,
8054       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
8055       Align(PtrMemVT.getSizeInBits() / 8),
8056       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8057   Chain = FuncTLVGet.getValue(1);
8058 
8059   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
8060   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
8061 
8062   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8063   MFI.setAdjustsStack(true);
8064 
8065   // TLS calls preserve all registers except those that absolutely must be
8066   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
8067   // silly).
8068   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8069   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
8070   if (Subtarget->hasCustomCallingConv())
8071     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8072 
8073   // Finally, we can make the call. This is just a degenerate version of a
8074   // normal AArch64 call node: x0 takes the address of the descriptor, and
8075   // returns the address of the variable in this thread.
8076   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
8077   Chain =
8078       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
8079                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
8080                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8081   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
8082 }
8083 
8084 /// Convert a thread-local variable reference into a sequence of instructions to
8085 /// compute the variable's address for the local exec TLS model of ELF targets.
8086 /// The sequence depends on the maximum TLS area size.
8087 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
8088                                                     SDValue ThreadBase,
8089                                                     const SDLoc &DL,
8090                                                     SelectionDAG &DAG) const {
8091   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8092   SDValue TPOff, Addr;
8093 
8094   switch (DAG.getTarget().Options.TLSSize) {
8095   default:
8096     llvm_unreachable("Unexpected TLS size");
8097 
8098   case 12: {
8099     // mrs   x0, TPIDR_EL0
8100     // add   x0, x0, :tprel_lo12:a
8101     SDValue Var = DAG.getTargetGlobalAddress(
8102         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
8103     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
8104                                       Var,
8105                                       DAG.getTargetConstant(0, DL, MVT::i32)),
8106                    0);
8107   }
8108 
8109   case 24: {
8110     // mrs   x0, TPIDR_EL0
8111     // add   x0, x0, :tprel_hi12:a
8112     // add   x0, x0, :tprel_lo12_nc:a
8113     SDValue HiVar = DAG.getTargetGlobalAddress(
8114         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
8115     SDValue LoVar = DAG.getTargetGlobalAddress(
8116         GV, DL, PtrVT, 0,
8117         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
8118     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
8119                                       HiVar,
8120                                       DAG.getTargetConstant(0, DL, MVT::i32)),
8121                    0);
8122     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
8123                                       LoVar,
8124                                       DAG.getTargetConstant(0, DL, MVT::i32)),
8125                    0);
8126   }
8127 
8128   case 32: {
8129     // mrs   x1, TPIDR_EL0
8130     // movz  x0, #:tprel_g1:a
8131     // movk  x0, #:tprel_g0_nc:a
8132     // add   x0, x1, x0
8133     SDValue HiVar = DAG.getTargetGlobalAddress(
8134         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
8135     SDValue LoVar = DAG.getTargetGlobalAddress(
8136         GV, DL, PtrVT, 0,
8137         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
8138     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
8139                                        DAG.getTargetConstant(16, DL, MVT::i32)),
8140                     0);
8141     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
8142                                        DAG.getTargetConstant(0, DL, MVT::i32)),
8143                     0);
8144     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
8145   }
8146 
8147   case 48: {
8148     // mrs   x1, TPIDR_EL0
8149     // movz  x0, #:tprel_g2:a
8150     // movk  x0, #:tprel_g1_nc:a
8151     // movk  x0, #:tprel_g0_nc:a
8152     // add   x0, x1, x0
8153     SDValue HiVar = DAG.getTargetGlobalAddress(
8154         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
8155     SDValue MiVar = DAG.getTargetGlobalAddress(
8156         GV, DL, PtrVT, 0,
8157         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
8158     SDValue LoVar = DAG.getTargetGlobalAddress(
8159         GV, DL, PtrVT, 0,
8160         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
8161     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
8162                                        DAG.getTargetConstant(32, DL, MVT::i32)),
8163                     0);
8164     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
8165                                        DAG.getTargetConstant(16, DL, MVT::i32)),
8166                     0);
8167     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
8168                                        DAG.getTargetConstant(0, DL, MVT::i32)),
8169                     0);
8170     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
8171   }
8172   }
8173 }
8174 
8175 /// When accessing thread-local variables under either the general-dynamic or
8176 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
8177 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
8178 /// is a function pointer to carry out the resolution.
8179 ///
8180 /// The sequence is:
8181 ///    adrp  x0, :tlsdesc:var
8182 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
8183 ///    add   x0, x0, #:tlsdesc_lo12:var
8184 ///    .tlsdesccall var
8185 ///    blr   x1
8186 ///    (TPIDR_EL0 offset now in x0)
8187 ///
8188 ///  The above sequence must be produced unscheduled, to enable the linker to
8189 ///  optimize/relax this sequence.
8190 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
8191 ///  above sequence, and expanded really late in the compilation flow, to ensure
8192 ///  the sequence is produced as per above.
8193 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
8194                                                       const SDLoc &DL,
8195                                                       SelectionDAG &DAG) const {
8196   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8197 
8198   SDValue Chain = DAG.getEntryNode();
8199   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8200 
8201   Chain =
8202       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
8203   SDValue Glue = Chain.getValue(1);
8204 
8205   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
8206 }
8207 
8208 SDValue
8209 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
8210                                                 SelectionDAG &DAG) const {
8211   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
8212 
8213   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8214 
8215   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
8216 
8217   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
8218     if (Model == TLSModel::LocalDynamic)
8219       Model = TLSModel::GeneralDynamic;
8220   }
8221 
8222   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
8223       Model != TLSModel::LocalExec)
8224     report_fatal_error("ELF TLS only supported in small memory model or "
8225                        "in local exec TLS model");
8226   // Different choices can be made for the maximum size of the TLS area for a
8227   // module. For the small address model, the default TLS size is 16MiB and the
8228   // maximum TLS size is 4GiB.
8229   // FIXME: add tiny and large code model support for TLS access models other
8230   // than local exec. We currently generate the same code as small for tiny,
8231   // which may be larger than needed.
8232 
8233   SDValue TPOff;
8234   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8235   SDLoc DL(Op);
8236   const GlobalValue *GV = GA->getGlobal();
8237 
8238   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
8239 
8240   if (Model == TLSModel::LocalExec) {
8241     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
8242   } else if (Model == TLSModel::InitialExec) {
8243     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
8244     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
8245   } else if (Model == TLSModel::LocalDynamic) {
8246     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
8247     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
8248     // the beginning of the module's TLS region, followed by a DTPREL offset
8249     // calculation.
8250 
8251     // These accesses will need deduplicating if there's more than one.
8252     AArch64FunctionInfo *MFI =
8253         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
8254     MFI->incNumLocalDynamicTLSAccesses();
8255 
8256     // The call needs a relocation too for linker relaxation. It doesn't make
8257     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
8258     // the address.
8259     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
8260                                                   AArch64II::MO_TLS);
8261 
8262     // Now we can calculate the offset from TPIDR_EL0 to this module's
8263     // thread-local area.
8264     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
8265 
8266     // Now use :dtprel_whatever: operations to calculate this variable's offset
8267     // in its thread-storage area.
8268     SDValue HiVar = DAG.getTargetGlobalAddress(
8269         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
8270     SDValue LoVar = DAG.getTargetGlobalAddress(
8271         GV, DL, MVT::i64, 0,
8272         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
8273 
8274     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
8275                                        DAG.getTargetConstant(0, DL, MVT::i32)),
8276                     0);
8277     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
8278                                        DAG.getTargetConstant(0, DL, MVT::i32)),
8279                     0);
8280   } else if (Model == TLSModel::GeneralDynamic) {
8281     // The call needs a relocation too for linker relaxation. It doesn't make
8282     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
8283     // the address.
8284     SDValue SymAddr =
8285         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
8286 
8287     // Finally we can make a call to calculate the offset from tpidr_el0.
8288     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
8289   } else
8290     llvm_unreachable("Unsupported ELF TLS access model");
8291 
8292   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
8293 }
8294 
8295 SDValue
8296 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
8297                                                     SelectionDAG &DAG) const {
8298   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
8299 
8300   SDValue Chain = DAG.getEntryNode();
8301   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8302   SDLoc DL(Op);
8303 
8304   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
8305 
8306   // Load the ThreadLocalStoragePointer from the TEB
8307   // A pointer to the TLS array is located at offset 0x58 from the TEB.
8308   SDValue TLSArray =
8309       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
8310   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
8311   Chain = TLSArray.getValue(1);
8312 
8313   // Load the TLS index from the C runtime;
8314   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
8315   // This also does the same as LOADgot, but using a generic i32 load,
8316   // while LOADgot only loads i64.
8317   SDValue TLSIndexHi =
8318       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
8319   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
8320       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
8321   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
8322   SDValue TLSIndex =
8323       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
8324   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
8325   Chain = TLSIndex.getValue(1);
8326 
8327   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
8328   // offset into the TLSArray.
8329   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
8330   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
8331                              DAG.getConstant(3, DL, PtrVT));
8332   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
8333                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
8334                             MachinePointerInfo());
8335   Chain = TLS.getValue(1);
8336 
8337   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8338   const GlobalValue *GV = GA->getGlobal();
8339   SDValue TGAHi = DAG.getTargetGlobalAddress(
8340       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
8341   SDValue TGALo = DAG.getTargetGlobalAddress(
8342       GV, DL, PtrVT, 0,
8343       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
8344 
8345   // Add the offset from the start of the .tls section (section base).
8346   SDValue Addr =
8347       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
8348                                  DAG.getTargetConstant(0, DL, MVT::i32)),
8349               0);
8350   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
8351   return Addr;
8352 }
8353 
8354 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
8355                                                      SelectionDAG &DAG) const {
8356   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8357   if (DAG.getTarget().useEmulatedTLS())
8358     return LowerToTLSEmulatedModel(GA, DAG);
8359 
8360   if (Subtarget->isTargetDarwin())
8361     return LowerDarwinGlobalTLSAddress(Op, DAG);
8362   if (Subtarget->isTargetELF())
8363     return LowerELFGlobalTLSAddress(Op, DAG);
8364   if (Subtarget->isTargetWindows())
8365     return LowerWindowsGlobalTLSAddress(Op, DAG);
8366 
8367   llvm_unreachable("Unexpected platform trying to use TLS");
8368 }
8369 
8370 // Looks through \param Val to determine the bit that can be used to
8371 // check the sign of the value. It returns the unextended value and
8372 // the sign bit position.
8373 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
8374   if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
8375     return {Val.getOperand(0),
8376             cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
8377                 1};
8378 
8379   if (Val.getOpcode() == ISD::SIGN_EXTEND)
8380     return {Val.getOperand(0),
8381             Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
8382 
8383   return {Val, Val.getValueSizeInBits() - 1};
8384 }
8385 
8386 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
8387   SDValue Chain = Op.getOperand(0);
8388   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
8389   SDValue LHS = Op.getOperand(2);
8390   SDValue RHS = Op.getOperand(3);
8391   SDValue Dest = Op.getOperand(4);
8392   SDLoc dl(Op);
8393 
8394   MachineFunction &MF = DAG.getMachineFunction();
8395   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
8396   // will not be produced, as they are conditional branch instructions that do
8397   // not set flags.
8398   bool ProduceNonFlagSettingCondBr =
8399       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
8400 
8401   // Handle f128 first, since lowering it will result in comparing the return
8402   // value of a libcall against zero, which is just what the rest of LowerBR_CC
8403   // is expecting to deal with.
8404   if (LHS.getValueType() == MVT::f128) {
8405     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
8406 
8407     // If softenSetCCOperands returned a scalar, we need to compare the result
8408     // against zero to select between true and false values.
8409     if (!RHS.getNode()) {
8410       RHS = DAG.getConstant(0, dl, LHS.getValueType());
8411       CC = ISD::SETNE;
8412     }
8413   }
8414 
8415   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
8416   // instruction.
8417   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
8418       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8419     // Only lower legal XALUO ops.
8420     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
8421       return SDValue();
8422 
8423     // The actual operation with overflow check.
8424     AArch64CC::CondCode OFCC;
8425     SDValue Value, Overflow;
8426     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
8427 
8428     if (CC == ISD::SETNE)
8429       OFCC = getInvertedCondCode(OFCC);
8430     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
8431 
8432     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
8433                        Overflow);
8434   }
8435 
8436   if (LHS.getValueType().isInteger()) {
8437     assert((LHS.getValueType() == RHS.getValueType()) &&
8438            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
8439 
8440     // If the RHS of the comparison is zero, we can potentially fold this
8441     // to a specialized branch.
8442     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
8443     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
8444       if (CC == ISD::SETEQ) {
8445         // See if we can use a TBZ to fold in an AND as well.
8446         // TBZ has a smaller branch displacement than CBZ.  If the offset is
8447         // out of bounds, a late MI-layer pass rewrites branches.
8448         // 403.gcc is an example that hits this case.
8449         if (LHS.getOpcode() == ISD::AND &&
8450             isa<ConstantSDNode>(LHS.getOperand(1)) &&
8451             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
8452           SDValue Test = LHS.getOperand(0);
8453           uint64_t Mask = LHS.getConstantOperandVal(1);
8454           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
8455                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
8456                              Dest);
8457         }
8458 
8459         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
8460       } else if (CC == ISD::SETNE) {
8461         // See if we can use a TBZ to fold in an AND as well.
8462         // TBZ has a smaller branch displacement than CBZ.  If the offset is
8463         // out of bounds, a late MI-layer pass rewrites branches.
8464         // 403.gcc is an example that hits this case.
8465         if (LHS.getOpcode() == ISD::AND &&
8466             isa<ConstantSDNode>(LHS.getOperand(1)) &&
8467             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
8468           SDValue Test = LHS.getOperand(0);
8469           uint64_t Mask = LHS.getConstantOperandVal(1);
8470           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
8471                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
8472                              Dest);
8473         }
8474 
8475         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
8476       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
8477         // Don't combine AND since emitComparison converts the AND to an ANDS
8478         // (a.k.a. TST) and the test in the test bit and branch instruction
8479         // becomes redundant.  This would also increase register pressure.
8480         uint64_t SignBitPos;
8481         std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
8482         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
8483                            DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
8484       }
8485     }
8486     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
8487         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
8488       // Don't combine AND since emitComparison converts the AND to an ANDS
8489       // (a.k.a. TST) and the test in the test bit and branch instruction
8490       // becomes redundant.  This would also increase register pressure.
8491       uint64_t SignBitPos;
8492       std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
8493       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
8494                          DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
8495     }
8496 
8497     SDValue CCVal;
8498     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
8499     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
8500                        Cmp);
8501   }
8502 
8503   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
8504          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
8505 
8506   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8507   // clean.  Some of them require two branches to implement.
8508   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
8509   AArch64CC::CondCode CC1, CC2;
8510   changeFPCCToAArch64CC(CC, CC1, CC2);
8511   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
8512   SDValue BR1 =
8513       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
8514   if (CC2 != AArch64CC::AL) {
8515     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
8516     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
8517                        Cmp);
8518   }
8519 
8520   return BR1;
8521 }
8522 
8523 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
8524                                               SelectionDAG &DAG) const {
8525   if (!Subtarget->hasNEON())
8526     return SDValue();
8527 
8528   EVT VT = Op.getValueType();
8529   EVT IntVT = VT.changeTypeToInteger();
8530   SDLoc DL(Op);
8531 
8532   SDValue In1 = Op.getOperand(0);
8533   SDValue In2 = Op.getOperand(1);
8534   EVT SrcVT = In2.getValueType();
8535 
8536   if (!SrcVT.bitsEq(VT))
8537     In2 = DAG.getFPExtendOrRound(In2, DL, VT);
8538 
8539   if (VT.isScalableVector())
8540     IntVT =
8541         getPackedSVEVectorVT(VT.getVectorElementType().changeTypeToInteger());
8542 
8543   if (VT.isFixedLengthVector() &&
8544       useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable())) {
8545     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
8546 
8547     In1 = convertToScalableVector(DAG, ContainerVT, In1);
8548     In2 = convertToScalableVector(DAG, ContainerVT, In2);
8549 
8550     SDValue Res = DAG.getNode(ISD::FCOPYSIGN, DL, ContainerVT, In1, In2);
8551     return convertFromScalableVector(DAG, VT, Res);
8552   }
8553 
8554   auto BitCast = [this](EVT VT, SDValue Op, SelectionDAG &DAG) {
8555     if (VT.isScalableVector())
8556       return getSVESafeBitCast(VT, Op, DAG);
8557 
8558     return DAG.getBitcast(VT, Op);
8559   };
8560 
8561   SDValue VecVal1, VecVal2;
8562   EVT VecVT;
8563   auto SetVecVal = [&](int Idx = -1) {
8564     if (!VT.isVector()) {
8565       VecVal1 =
8566           DAG.getTargetInsertSubreg(Idx, DL, VecVT, DAG.getUNDEF(VecVT), In1);
8567       VecVal2 =
8568           DAG.getTargetInsertSubreg(Idx, DL, VecVT, DAG.getUNDEF(VecVT), In2);
8569     } else {
8570       VecVal1 = BitCast(VecVT, In1, DAG);
8571       VecVal2 = BitCast(VecVT, In2, DAG);
8572     }
8573   };
8574   if (VT.isVector()) {
8575     VecVT = IntVT;
8576     SetVecVal();
8577   } else if (VT == MVT::f64) {
8578     VecVT = MVT::v2i64;
8579     SetVecVal(AArch64::dsub);
8580   } else if (VT == MVT::f32) {
8581     VecVT = MVT::v4i32;
8582     SetVecVal(AArch64::ssub);
8583   } else if (VT == MVT::f16) {
8584     VecVT = MVT::v8i16;
8585     SetVecVal(AArch64::hsub);
8586   } else {
8587     llvm_unreachable("Invalid type for copysign!");
8588   }
8589 
8590   unsigned BitWidth = In1.getScalarValueSizeInBits();
8591   SDValue SignMaskV = DAG.getConstant(~APInt::getSignMask(BitWidth), DL, VecVT);
8592 
8593   // We want to materialize a mask with every bit but the high bit set, but the
8594   // AdvSIMD immediate moves cannot materialize that in a single instruction for
8595   // 64-bit elements. Instead, materialize all bits set and then negate that.
8596   if (VT == MVT::f64 || VT == MVT::v2f64) {
8597     SignMaskV = DAG.getConstant(APInt::getAllOnes(BitWidth), DL, VecVT);
8598     SignMaskV = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, SignMaskV);
8599     SignMaskV = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, SignMaskV);
8600     SignMaskV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, SignMaskV);
8601   }
8602 
8603   SDValue BSP =
8604       DAG.getNode(AArch64ISD::BSP, DL, VecVT, SignMaskV, VecVal1, VecVal2);
8605   if (VT == MVT::f16)
8606     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, BSP);
8607   if (VT == MVT::f32)
8608     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, BSP);
8609   if (VT == MVT::f64)
8610     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, BSP);
8611 
8612   return BitCast(VT, BSP, DAG);
8613 }
8614 
8615 SDValue AArch64TargetLowering::LowerCTPOP_PARITY(SDValue Op,
8616                                                  SelectionDAG &DAG) const {
8617   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8618           Attribute::NoImplicitFloat))
8619     return SDValue();
8620 
8621   if (!Subtarget->hasNEON())
8622     return SDValue();
8623 
8624   bool IsParity = Op.getOpcode() == ISD::PARITY;
8625   SDValue Val = Op.getOperand(0);
8626   SDLoc DL(Op);
8627   EVT VT = Op.getValueType();
8628 
8629   // for i32, general parity function using EORs is more efficient compared to
8630   // using floating point
8631   if (VT == MVT::i32 && IsParity)
8632     return SDValue();
8633 
8634   // If there is no CNT instruction available, GPR popcount can
8635   // be more efficiently lowered to the following sequence that uses
8636   // AdvSIMD registers/instructions as long as the copies to/from
8637   // the AdvSIMD registers are cheap.
8638   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
8639   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
8640   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
8641   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
8642   if (VT == MVT::i32 || VT == MVT::i64) {
8643     if (VT == MVT::i32)
8644       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
8645     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
8646 
8647     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
8648     SDValue UaddLV = DAG.getNode(
8649         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
8650         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
8651 
8652     if (IsParity)
8653       UaddLV = DAG.getNode(ISD::AND, DL, MVT::i32, UaddLV,
8654                            DAG.getConstant(1, DL, MVT::i32));
8655 
8656     if (VT == MVT::i64)
8657       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
8658     return UaddLV;
8659   } else if (VT == MVT::i128) {
8660     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
8661 
8662     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
8663     SDValue UaddLV = DAG.getNode(
8664         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
8665         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
8666 
8667     if (IsParity)
8668       UaddLV = DAG.getNode(ISD::AND, DL, MVT::i32, UaddLV,
8669                            DAG.getConstant(1, DL, MVT::i32));
8670 
8671     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
8672   }
8673 
8674   assert(!IsParity && "ISD::PARITY of vector types not supported");
8675 
8676   if (VT.isScalableVector() ||
8677       useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
8678     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
8679 
8680   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
8681           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
8682          "Unexpected type for custom ctpop lowering");
8683 
8684   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
8685   Val = DAG.getBitcast(VT8Bit, Val);
8686   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
8687 
8688   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
8689   unsigned EltSize = 8;
8690   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
8691   while (EltSize != VT.getScalarSizeInBits()) {
8692     EltSize *= 2;
8693     NumElts /= 2;
8694     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
8695     Val = DAG.getNode(
8696         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
8697         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
8698   }
8699 
8700   return Val;
8701 }
8702 
8703 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8704   EVT VT = Op.getValueType();
8705   assert(VT.isScalableVector() ||
8706          useSVEForFixedLengthVectorVT(
8707              VT, /*OverrideNEON=*/Subtarget->useSVEForFixedLengthVectors()));
8708 
8709   SDLoc DL(Op);
8710   SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
8711   return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
8712 }
8713 
8714 SDValue AArch64TargetLowering::LowerMinMax(SDValue Op,
8715                                            SelectionDAG &DAG) const {
8716 
8717   EVT VT = Op.getValueType();
8718   SDLoc DL(Op);
8719   unsigned Opcode = Op.getOpcode();
8720   ISD::CondCode CC;
8721   switch (Opcode) {
8722   default:
8723     llvm_unreachable("Wrong instruction");
8724   case ISD::SMAX:
8725     CC = ISD::SETGT;
8726     break;
8727   case ISD::SMIN:
8728     CC = ISD::SETLT;
8729     break;
8730   case ISD::UMAX:
8731     CC = ISD::SETUGT;
8732     break;
8733   case ISD::UMIN:
8734     CC = ISD::SETULT;
8735     break;
8736   }
8737 
8738   if (VT.isScalableVector() ||
8739       useSVEForFixedLengthVectorVT(
8740           VT, /*OverrideNEON=*/Subtarget->useSVEForFixedLengthVectors())) {
8741     switch (Opcode) {
8742     default:
8743       llvm_unreachable("Wrong instruction");
8744     case ISD::SMAX:
8745       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED);
8746     case ISD::SMIN:
8747       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED);
8748     case ISD::UMAX:
8749       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED);
8750     case ISD::UMIN:
8751       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED);
8752     }
8753   }
8754 
8755   SDValue Op0 = Op.getOperand(0);
8756   SDValue Op1 = Op.getOperand(1);
8757   SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC);
8758   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8759 }
8760 
8761 SDValue AArch64TargetLowering::LowerBitreverse(SDValue Op,
8762                                                SelectionDAG &DAG) const {
8763   EVT VT = Op.getValueType();
8764 
8765   if (VT.isScalableVector() ||
8766       useSVEForFixedLengthVectorVT(
8767           VT, /*OverrideNEON=*/Subtarget->useSVEForFixedLengthVectors()))
8768     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU);
8769 
8770   SDLoc DL(Op);
8771   SDValue REVB;
8772   MVT VST;
8773 
8774   switch (VT.getSimpleVT().SimpleTy) {
8775   default:
8776     llvm_unreachable("Invalid type for bitreverse!");
8777 
8778   case MVT::v2i32: {
8779     VST = MVT::v8i8;
8780     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
8781 
8782     break;
8783   }
8784 
8785   case MVT::v4i32: {
8786     VST = MVT::v16i8;
8787     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
8788 
8789     break;
8790   }
8791 
8792   case MVT::v1i64: {
8793     VST = MVT::v8i8;
8794     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
8795 
8796     break;
8797   }
8798 
8799   case MVT::v2i64: {
8800     VST = MVT::v16i8;
8801     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
8802 
8803     break;
8804   }
8805   }
8806 
8807   return DAG.getNode(AArch64ISD::NVCAST, DL, VT,
8808                      DAG.getNode(ISD::BITREVERSE, DL, VST, REVB));
8809 }
8810 
8811 // Check whether the continuous comparison sequence.
8812 static bool
8813 isOrXorChain(SDValue N, unsigned &Num,
8814              SmallVector<std::pair<SDValue, SDValue>, 16> &WorkList) {
8815   if (Num == MaxXors)
8816     return false;
8817 
8818   // Skip the one-use zext
8819   if (N->getOpcode() == ISD::ZERO_EXTEND && N->hasOneUse())
8820     N = N->getOperand(0);
8821 
8822   // The leaf node must be XOR
8823   if (N->getOpcode() == ISD::XOR) {
8824     WorkList.push_back(std::make_pair(N->getOperand(0), N->getOperand(1)));
8825     Num++;
8826     return true;
8827   }
8828 
8829   // All the non-leaf nodes must be OR.
8830   if (N->getOpcode() != ISD::OR || !N->hasOneUse())
8831     return false;
8832 
8833   if (isOrXorChain(N->getOperand(0), Num, WorkList) &&
8834       isOrXorChain(N->getOperand(1), Num, WorkList))
8835     return true;
8836   return false;
8837 }
8838 
8839 // Transform chains of ORs and XORs, which usually outlined by memcmp/bmp.
8840 static SDValue performOrXorChainCombine(SDNode *N, SelectionDAG &DAG) {
8841   SDValue LHS = N->getOperand(0);
8842   SDValue RHS = N->getOperand(1);
8843   SDLoc DL(N);
8844   EVT VT = N->getValueType(0);
8845   SmallVector<std::pair<SDValue, SDValue>, 16> WorkList;
8846 
8847   // Only handle integer compares.
8848   if (N->getOpcode() != ISD::SETCC)
8849     return SDValue();
8850 
8851   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
8852   // Try to express conjunction "cmp 0 (or (xor A0 A1) (xor B0 B1))" as:
8853   // sub A0, A1; ccmp B0, B1, 0, eq; cmp inv(Cond) flag
8854   unsigned NumXors = 0;
8855   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && isNullConstant(RHS) &&
8856       LHS->getOpcode() == ISD::OR && LHS->hasOneUse() &&
8857       isOrXorChain(LHS, NumXors, WorkList)) {
8858     SDValue XOR0, XOR1;
8859     std::tie(XOR0, XOR1) = WorkList[0];
8860     unsigned LogicOp = (Cond == ISD::SETEQ) ? ISD::AND : ISD::OR;
8861     SDValue Cmp = DAG.getSetCC(DL, VT, XOR0, XOR1, Cond);
8862     for (unsigned I = 1; I < WorkList.size(); I++) {
8863       std::tie(XOR0, XOR1) = WorkList[I];
8864       SDValue CmpChain = DAG.getSetCC(DL, VT, XOR0, XOR1, Cond);
8865       Cmp = DAG.getNode(LogicOp, DL, VT, Cmp, CmpChain);
8866     }
8867 
8868     // Exit early by inverting the condition, which help reduce indentations.
8869     return Cmp;
8870   }
8871 
8872   return SDValue();
8873 }
8874 
8875 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8876 
8877   if (Op.getValueType().isVector())
8878     return LowerVSETCC(Op, DAG);
8879 
8880   bool IsStrict = Op->isStrictFPOpcode();
8881   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
8882   unsigned OpNo = IsStrict ? 1 : 0;
8883   SDValue Chain;
8884   if (IsStrict)
8885     Chain = Op.getOperand(0);
8886   SDValue LHS = Op.getOperand(OpNo + 0);
8887   SDValue RHS = Op.getOperand(OpNo + 1);
8888   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
8889   SDLoc dl(Op);
8890 
8891   // We chose ZeroOrOneBooleanContents, so use zero and one.
8892   EVT VT = Op.getValueType();
8893   SDValue TVal = DAG.getConstant(1, dl, VT);
8894   SDValue FVal = DAG.getConstant(0, dl, VT);
8895 
8896   // Handle f128 first, since one possible outcome is a normal integer
8897   // comparison which gets picked up by the next if statement.
8898   if (LHS.getValueType() == MVT::f128) {
8899     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
8900                         IsSignaling);
8901 
8902     // If softenSetCCOperands returned a scalar, use it.
8903     if (!RHS.getNode()) {
8904       assert(LHS.getValueType() == Op.getValueType() &&
8905              "Unexpected setcc expansion!");
8906       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
8907     }
8908   }
8909 
8910   if (LHS.getValueType().isInteger()) {
8911     SDValue CCVal;
8912     SDValue Cmp = getAArch64Cmp(
8913         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
8914 
8915     // Note that we inverted the condition above, so we reverse the order of
8916     // the true and false operands here.  This will allow the setcc to be
8917     // matched to a single CSINC instruction.
8918     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
8919     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
8920   }
8921 
8922   // Now we know we're dealing with FP values.
8923   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
8924          LHS.getValueType() == MVT::f64);
8925 
8926   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
8927   // and do the comparison.
8928   SDValue Cmp;
8929   if (IsStrict)
8930     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
8931   else
8932     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
8933 
8934   AArch64CC::CondCode CC1, CC2;
8935   changeFPCCToAArch64CC(CC, CC1, CC2);
8936   SDValue Res;
8937   if (CC2 == AArch64CC::AL) {
8938     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
8939                           CC2);
8940     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
8941 
8942     // Note that we inverted the condition above, so we reverse the order of
8943     // the true and false operands here.  This will allow the setcc to be
8944     // matched to a single CSINC instruction.
8945     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
8946   } else {
8947     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
8948     // totally clean.  Some of them require two CSELs to implement.  As is in
8949     // this case, we emit the first CSEL and then emit a second using the output
8950     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
8951 
8952     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
8953     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
8954     SDValue CS1 =
8955         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
8956 
8957     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
8958     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
8959   }
8960   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
8961 }
8962 
8963 SDValue AArch64TargetLowering::LowerSETCCCARRY(SDValue Op,
8964                                                SelectionDAG &DAG) const {
8965 
8966   SDValue LHS = Op.getOperand(0);
8967   SDValue RHS = Op.getOperand(1);
8968   EVT VT = LHS.getValueType();
8969   if (VT != MVT::i32 && VT != MVT::i64)
8970     return SDValue();
8971 
8972   SDLoc DL(Op);
8973   SDValue Carry = Op.getOperand(2);
8974   // SBCS uses a carry not a borrow so the carry flag should be inverted first.
8975   SDValue InvCarry = valueToCarryFlag(Carry, DAG, true);
8976   SDValue Cmp = DAG.getNode(AArch64ISD::SBCS, DL, DAG.getVTList(VT, MVT::Glue),
8977                             LHS, RHS, InvCarry);
8978 
8979   EVT OpVT = Op.getValueType();
8980   SDValue TVal = DAG.getConstant(1, DL, OpVT);
8981   SDValue FVal = DAG.getConstant(0, DL, OpVT);
8982 
8983   ISD::CondCode Cond = cast<CondCodeSDNode>(Op.getOperand(3))->get();
8984   ISD::CondCode CondInv = ISD::getSetCCInverse(Cond, VT);
8985   SDValue CCVal =
8986       DAG.getConstant(changeIntCCToAArch64CC(CondInv), DL, MVT::i32);
8987   // Inputs are swapped because the condition is inverted. This will allow
8988   // matching with a single CSINC instruction.
8989   return DAG.getNode(AArch64ISD::CSEL, DL, OpVT, FVal, TVal, CCVal,
8990                      Cmp.getValue(1));
8991 }
8992 
8993 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
8994                                               SDValue RHS, SDValue TVal,
8995                                               SDValue FVal, const SDLoc &dl,
8996                                               SelectionDAG &DAG) const {
8997   // Handle f128 first, because it will result in a comparison of some RTLIB
8998   // call result against zero.
8999   if (LHS.getValueType() == MVT::f128) {
9000     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
9001 
9002     // If softenSetCCOperands returned a scalar, we need to compare the result
9003     // against zero to select between true and false values.
9004     if (!RHS.getNode()) {
9005       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9006       CC = ISD::SETNE;
9007     }
9008   }
9009 
9010   // Also handle f16, for which we need to do a f32 comparison.
9011   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
9012     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
9013     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
9014   }
9015 
9016   // Next, handle integers.
9017   if (LHS.getValueType().isInteger()) {
9018     assert((LHS.getValueType() == RHS.getValueType()) &&
9019            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
9020 
9021     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
9022     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
9023     ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
9024     // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
9025     // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
9026     // supported types.
9027     if (CC == ISD::SETGT && RHSC && RHSC->isAllOnes() && CTVal && CFVal &&
9028         CTVal->isOne() && CFVal->isAllOnes() &&
9029         LHS.getValueType() == TVal.getValueType()) {
9030       EVT VT = LHS.getValueType();
9031       SDValue Shift =
9032           DAG.getNode(ISD::SRA, dl, VT, LHS,
9033                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
9034       return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
9035     }
9036 
9037     // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
9038     // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
9039     // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
9040     // Both require less instructions than compare and conditional select.
9041     if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TVal &&
9042         RHSC && RHSC->isZero() && CFVal && CFVal->isZero() &&
9043         LHS.getValueType() == RHS.getValueType()) {
9044       EVT VT = LHS.getValueType();
9045       SDValue Shift =
9046           DAG.getNode(ISD::SRA, dl, VT, LHS,
9047                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
9048 
9049       if (CC == ISD::SETGT)
9050         Shift = DAG.getNOT(dl, Shift, VT);
9051 
9052       return DAG.getNode(ISD::AND, dl, VT, LHS, Shift);
9053     }
9054 
9055     unsigned Opcode = AArch64ISD::CSEL;
9056 
9057     // If both the TVal and the FVal are constants, see if we can swap them in
9058     // order to for a CSINV or CSINC out of them.
9059     if (CTVal && CFVal && CTVal->isAllOnes() && CFVal->isZero()) {
9060       std::swap(TVal, FVal);
9061       std::swap(CTVal, CFVal);
9062       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
9063     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isZero()) {
9064       std::swap(TVal, FVal);
9065       std::swap(CTVal, CFVal);
9066       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
9067     } else if (TVal.getOpcode() == ISD::XOR) {
9068       // If TVal is a NOT we want to swap TVal and FVal so that we can match
9069       // with a CSINV rather than a CSEL.
9070       if (isAllOnesConstant(TVal.getOperand(1))) {
9071         std::swap(TVal, FVal);
9072         std::swap(CTVal, CFVal);
9073         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
9074       }
9075     } else if (TVal.getOpcode() == ISD::SUB) {
9076       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
9077       // that we can match with a CSNEG rather than a CSEL.
9078       if (isNullConstant(TVal.getOperand(0))) {
9079         std::swap(TVal, FVal);
9080         std::swap(CTVal, CFVal);
9081         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
9082       }
9083     } else if (CTVal && CFVal) {
9084       const int64_t TrueVal = CTVal->getSExtValue();
9085       const int64_t FalseVal = CFVal->getSExtValue();
9086       bool Swap = false;
9087 
9088       // If both TVal and FVal are constants, see if FVal is the
9089       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
9090       // instead of a CSEL in that case.
9091       if (TrueVal == ~FalseVal) {
9092         Opcode = AArch64ISD::CSINV;
9093       } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
9094                  TrueVal == -FalseVal) {
9095         Opcode = AArch64ISD::CSNEG;
9096       } else if (TVal.getValueType() == MVT::i32) {
9097         // If our operands are only 32-bit wide, make sure we use 32-bit
9098         // arithmetic for the check whether we can use CSINC. This ensures that
9099         // the addition in the check will wrap around properly in case there is
9100         // an overflow (which would not be the case if we do the check with
9101         // 64-bit arithmetic).
9102         const uint32_t TrueVal32 = CTVal->getZExtValue();
9103         const uint32_t FalseVal32 = CFVal->getZExtValue();
9104 
9105         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
9106           Opcode = AArch64ISD::CSINC;
9107 
9108           if (TrueVal32 > FalseVal32) {
9109             Swap = true;
9110           }
9111         }
9112       } else {
9113         // 64-bit check whether we can use CSINC.
9114         const uint64_t TrueVal64 = TrueVal;
9115         const uint64_t FalseVal64 = FalseVal;
9116 
9117         if ((TrueVal64 == FalseVal64 + 1) || (TrueVal64 + 1 == FalseVal64)) {
9118           Opcode = AArch64ISD::CSINC;
9119 
9120           if (TrueVal > FalseVal) {
9121             Swap = true;
9122           }
9123         }
9124       }
9125 
9126       // Swap TVal and FVal if necessary.
9127       if (Swap) {
9128         std::swap(TVal, FVal);
9129         std::swap(CTVal, CFVal);
9130         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
9131       }
9132 
9133       if (Opcode != AArch64ISD::CSEL) {
9134         // Drop FVal since we can get its value by simply inverting/negating
9135         // TVal.
9136         FVal = TVal;
9137       }
9138     }
9139 
9140     // Avoid materializing a constant when possible by reusing a known value in
9141     // a register.  However, don't perform this optimization if the known value
9142     // is one, zero or negative one in the case of a CSEL.  We can always
9143     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
9144     // FVal, respectively.
9145     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
9146     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
9147         !RHSVal->isZero() && !RHSVal->isAllOnes()) {
9148       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9149       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
9150       // "a != C ? x : a" to avoid materializing C.
9151       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
9152         TVal = LHS;
9153       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
9154         FVal = LHS;
9155     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
9156       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
9157       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
9158       // avoid materializing C.
9159       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9160       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
9161         Opcode = AArch64ISD::CSINV;
9162         TVal = LHS;
9163         FVal = DAG.getConstant(0, dl, FVal.getValueType());
9164       }
9165     }
9166 
9167     SDValue CCVal;
9168     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
9169     EVT VT = TVal.getValueType();
9170     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
9171   }
9172 
9173   // Now we know we're dealing with FP values.
9174   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
9175          LHS.getValueType() == MVT::f64);
9176   assert(LHS.getValueType() == RHS.getValueType());
9177   EVT VT = TVal.getValueType();
9178   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
9179 
9180   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9181   // clean.  Some of them require two CSELs to implement.
9182   AArch64CC::CondCode CC1, CC2;
9183   changeFPCCToAArch64CC(CC, CC1, CC2);
9184 
9185   if (DAG.getTarget().Options.UnsafeFPMath) {
9186     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
9187     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
9188     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
9189     if (RHSVal && RHSVal->isZero()) {
9190       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
9191       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
9192 
9193       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
9194           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
9195         TVal = LHS;
9196       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
9197                CFVal && CFVal->isZero() &&
9198                FVal.getValueType() == LHS.getValueType())
9199         FVal = LHS;
9200     }
9201   }
9202 
9203   // Emit first, and possibly only, CSEL.
9204   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
9205   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
9206 
9207   // If we need a second CSEL, emit it, using the output of the first as the
9208   // RHS.  We're effectively OR'ing the two CC's together.
9209   if (CC2 != AArch64CC::AL) {
9210     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
9211     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
9212   }
9213 
9214   // Otherwise, return the output of the first CSEL.
9215   return CS1;
9216 }
9217 
9218 SDValue AArch64TargetLowering::LowerVECTOR_SPLICE(SDValue Op,
9219                                                   SelectionDAG &DAG) const {
9220   EVT Ty = Op.getValueType();
9221   auto Idx = Op.getConstantOperandAPInt(2);
9222   int64_t IdxVal = Idx.getSExtValue();
9223   assert(Ty.isScalableVector() &&
9224          "Only expect scalable vectors for custom lowering of VECTOR_SPLICE");
9225 
9226   // We can use the splice instruction for certain index values where we are
9227   // able to efficiently generate the correct predicate. The index will be
9228   // inverted and used directly as the input to the ptrue instruction, i.e.
9229   // -1 -> vl1, -2 -> vl2, etc. The predicate will then be reversed to get the
9230   // splice predicate. However, we can only do this if we can guarantee that
9231   // there are enough elements in the vector, hence we check the index <= min
9232   // number of elements.
9233   std::optional<unsigned> PredPattern;
9234   if (Ty.isScalableVector() && IdxVal < 0 &&
9235       (PredPattern = getSVEPredPatternFromNumElements(std::abs(IdxVal))) !=
9236           std::nullopt) {
9237     SDLoc DL(Op);
9238 
9239     // Create a predicate where all but the last -IdxVal elements are false.
9240     EVT PredVT = Ty.changeVectorElementType(MVT::i1);
9241     SDValue Pred = getPTrue(DAG, DL, PredVT, *PredPattern);
9242     Pred = DAG.getNode(ISD::VECTOR_REVERSE, DL, PredVT, Pred);
9243 
9244     // Now splice the two inputs together using the predicate.
9245     return DAG.getNode(AArch64ISD::SPLICE, DL, Ty, Pred, Op.getOperand(0),
9246                        Op.getOperand(1));
9247   }
9248 
9249   // This will select to an EXT instruction, which has a maximum immediate
9250   // value of 255, hence 2048-bits is the maximum value we can lower.
9251   if (IdxVal >= 0 &&
9252       IdxVal < int64_t(2048 / Ty.getVectorElementType().getSizeInBits()))
9253     return Op;
9254 
9255   return SDValue();
9256 }
9257 
9258 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
9259                                               SelectionDAG &DAG) const {
9260   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
9261   SDValue LHS = Op.getOperand(0);
9262   SDValue RHS = Op.getOperand(1);
9263   SDValue TVal = Op.getOperand(2);
9264   SDValue FVal = Op.getOperand(3);
9265   SDLoc DL(Op);
9266   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
9267 }
9268 
9269 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
9270                                            SelectionDAG &DAG) const {
9271   SDValue CCVal = Op->getOperand(0);
9272   SDValue TVal = Op->getOperand(1);
9273   SDValue FVal = Op->getOperand(2);
9274   SDLoc DL(Op);
9275 
9276   EVT Ty = Op.getValueType();
9277   if (Ty == MVT::aarch64svcount) {
9278     TVal = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i1, TVal);
9279     FVal = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i1, FVal);
9280     SDValue Sel =
9281         DAG.getNode(ISD::SELECT, DL, MVT::nxv16i1, CCVal, TVal, FVal);
9282     return DAG.getNode(ISD::BITCAST, DL, Ty, Sel);
9283   }
9284 
9285   if (Ty.isScalableVector()) {
9286     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
9287     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, CCVal);
9288     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
9289   }
9290 
9291   if (useSVEForFixedLengthVectorVT(Ty, !Subtarget->isNeonAvailable())) {
9292     // FIXME: Ideally this would be the same as above using i1 types, however
9293     // for the moment we can't deal with fixed i1 vector types properly, so
9294     // instead extend the predicate to a result type sized integer vector.
9295     MVT SplatValVT = MVT::getIntegerVT(Ty.getScalarSizeInBits());
9296     MVT PredVT = MVT::getVectorVT(SplatValVT, Ty.getVectorElementCount());
9297     SDValue SplatVal = DAG.getSExtOrTrunc(CCVal, DL, SplatValVT);
9298     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, SplatVal);
9299     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
9300   }
9301 
9302   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
9303   // instruction.
9304   if (ISD::isOverflowIntrOpRes(CCVal)) {
9305     // Only lower legal XALUO ops.
9306     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
9307       return SDValue();
9308 
9309     AArch64CC::CondCode OFCC;
9310     SDValue Value, Overflow;
9311     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
9312     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
9313 
9314     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
9315                        CCVal, Overflow);
9316   }
9317 
9318   // Lower it the same way as we would lower a SELECT_CC node.
9319   ISD::CondCode CC;
9320   SDValue LHS, RHS;
9321   if (CCVal.getOpcode() == ISD::SETCC) {
9322     LHS = CCVal.getOperand(0);
9323     RHS = CCVal.getOperand(1);
9324     CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get();
9325   } else {
9326     LHS = CCVal;
9327     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
9328     CC = ISD::SETNE;
9329   }
9330 
9331   // If we are lowering a f16 and we do not have fullf16, convert to a f32 in
9332   // order to use FCSELSrrr
9333   if ((Ty == MVT::f16 || Ty == MVT::bf16) && !Subtarget->hasFullFP16()) {
9334     TVal = DAG.getTargetInsertSubreg(AArch64::hsub, DL, MVT::f32,
9335                                      DAG.getUNDEF(MVT::f32), TVal);
9336     FVal = DAG.getTargetInsertSubreg(AArch64::hsub, DL, MVT::f32,
9337                                      DAG.getUNDEF(MVT::f32), FVal);
9338   }
9339 
9340   SDValue Res = LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
9341 
9342   if ((Ty == MVT::f16 || Ty == MVT::bf16) && !Subtarget->hasFullFP16()) {
9343     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, Ty, Res);
9344   }
9345 
9346   return Res;
9347 }
9348 
9349 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
9350                                               SelectionDAG &DAG) const {
9351   // Jump table entries as PC relative offsets. No additional tweaking
9352   // is necessary here. Just get the address of the jump table.
9353   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
9354 
9355   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
9356       !Subtarget->isTargetMachO()) {
9357     return getAddrLarge(JT, DAG);
9358   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
9359     return getAddrTiny(JT, DAG);
9360   }
9361   return getAddr(JT, DAG);
9362 }
9363 
9364 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
9365                                           SelectionDAG &DAG) const {
9366   // Jump table entries as PC relative offsets. No additional tweaking
9367   // is necessary here. Just get the address of the jump table.
9368   SDLoc DL(Op);
9369   SDValue JT = Op.getOperand(1);
9370   SDValue Entry = Op.getOperand(2);
9371   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
9372 
9373   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
9374   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
9375 
9376   SDNode *Dest =
9377       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
9378                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
9379   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
9380                      SDValue(Dest, 0));
9381 }
9382 
9383 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
9384                                                  SelectionDAG &DAG) const {
9385   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
9386 
9387   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
9388     // Use the GOT for the large code model on iOS.
9389     if (Subtarget->isTargetMachO()) {
9390       return getGOT(CP, DAG);
9391     }
9392     return getAddrLarge(CP, DAG);
9393   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
9394     return getAddrTiny(CP, DAG);
9395   } else {
9396     return getAddr(CP, DAG);
9397   }
9398 }
9399 
9400 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
9401                                                SelectionDAG &DAG) const {
9402   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
9403   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
9404       !Subtarget->isTargetMachO()) {
9405     return getAddrLarge(BA, DAG);
9406   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
9407     return getAddrTiny(BA, DAG);
9408   }
9409   return getAddr(BA, DAG);
9410 }
9411 
9412 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
9413                                                  SelectionDAG &DAG) const {
9414   AArch64FunctionInfo *FuncInfo =
9415       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
9416 
9417   SDLoc DL(Op);
9418   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
9419                                  getPointerTy(DAG.getDataLayout()));
9420   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
9421   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9422   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9423                       MachinePointerInfo(SV));
9424 }
9425 
9426 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
9427                                                   SelectionDAG &DAG) const {
9428   MachineFunction &MF = DAG.getMachineFunction();
9429   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
9430 
9431   SDLoc DL(Op);
9432   SDValue FR;
9433   if (Subtarget->isWindowsArm64EC()) {
9434     // With the Arm64EC ABI, we compute the address of the varargs save area
9435     // relative to x4. For a normal AArch64->AArch64 call, x4 == sp on entry,
9436     // but calls from an entry thunk can pass in a different address.
9437     Register VReg = MF.addLiveIn(AArch64::X4, &AArch64::GPR64RegClass);
9438     SDValue Val = DAG.getCopyFromReg(DAG.getEntryNode(), DL, VReg, MVT::i64);
9439     uint64_t StackOffset;
9440     if (FuncInfo->getVarArgsGPRSize() > 0)
9441       StackOffset = -(uint64_t)FuncInfo->getVarArgsGPRSize();
9442     else
9443       StackOffset = FuncInfo->getVarArgsStackOffset();
9444     FR = DAG.getNode(ISD::ADD, DL, MVT::i64, Val,
9445                      DAG.getConstant(StackOffset, DL, MVT::i64));
9446   } else {
9447     FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
9448                                ? FuncInfo->getVarArgsGPRIndex()
9449                                : FuncInfo->getVarArgsStackIndex(),
9450                            getPointerTy(DAG.getDataLayout()));
9451   }
9452   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9453   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9454                       MachinePointerInfo(SV));
9455 }
9456 
9457 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
9458                                                   SelectionDAG &DAG) const {
9459   // The layout of the va_list struct is specified in the AArch64 Procedure Call
9460   // Standard, section B.3.
9461   MachineFunction &MF = DAG.getMachineFunction();
9462   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
9463   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
9464   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
9465   auto PtrVT = getPointerTy(DAG.getDataLayout());
9466   SDLoc DL(Op);
9467 
9468   SDValue Chain = Op.getOperand(0);
9469   SDValue VAList = Op.getOperand(1);
9470   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9471   SmallVector<SDValue, 4> MemOps;
9472 
9473   // void *__stack at offset 0
9474   unsigned Offset = 0;
9475   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
9476   Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
9477   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
9478                                 MachinePointerInfo(SV), Align(PtrSize)));
9479 
9480   // void *__gr_top at offset 8 (4 on ILP32)
9481   Offset += PtrSize;
9482   int GPRSize = FuncInfo->getVarArgsGPRSize();
9483   if (GPRSize > 0) {
9484     SDValue GRTop, GRTopAddr;
9485 
9486     GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
9487                             DAG.getConstant(Offset, DL, PtrVT));
9488 
9489     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
9490     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
9491                         DAG.getConstant(GPRSize, DL, PtrVT));
9492     GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
9493 
9494     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
9495                                   MachinePointerInfo(SV, Offset),
9496                                   Align(PtrSize)));
9497   }
9498 
9499   // void *__vr_top at offset 16 (8 on ILP32)
9500   Offset += PtrSize;
9501   int FPRSize = FuncInfo->getVarArgsFPRSize();
9502   if (FPRSize > 0) {
9503     SDValue VRTop, VRTopAddr;
9504     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
9505                             DAG.getConstant(Offset, DL, PtrVT));
9506 
9507     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
9508     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
9509                         DAG.getConstant(FPRSize, DL, PtrVT));
9510     VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
9511 
9512     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
9513                                   MachinePointerInfo(SV, Offset),
9514                                   Align(PtrSize)));
9515   }
9516 
9517   // int __gr_offs at offset 24 (12 on ILP32)
9518   Offset += PtrSize;
9519   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
9520                                    DAG.getConstant(Offset, DL, PtrVT));
9521   MemOps.push_back(
9522       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
9523                    GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
9524 
9525   // int __vr_offs at offset 28 (16 on ILP32)
9526   Offset += 4;
9527   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
9528                                    DAG.getConstant(Offset, DL, PtrVT));
9529   MemOps.push_back(
9530       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
9531                    VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
9532 
9533   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
9534 }
9535 
9536 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
9537                                             SelectionDAG &DAG) const {
9538   MachineFunction &MF = DAG.getMachineFunction();
9539 
9540   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
9541     return LowerWin64_VASTART(Op, DAG);
9542   else if (Subtarget->isTargetDarwin())
9543     return LowerDarwin_VASTART(Op, DAG);
9544   else
9545     return LowerAAPCS_VASTART(Op, DAG);
9546 }
9547 
9548 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
9549                                            SelectionDAG &DAG) const {
9550   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
9551   // pointer.
9552   SDLoc DL(Op);
9553   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
9554   unsigned VaListSize =
9555       (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
9556           ? PtrSize
9557           : Subtarget->isTargetILP32() ? 20 : 32;
9558   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9559   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9560 
9561   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
9562                        DAG.getConstant(VaListSize, DL, MVT::i32),
9563                        Align(PtrSize), false, false, false,
9564                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
9565 }
9566 
9567 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9568   assert(Subtarget->isTargetDarwin() &&
9569          "automatic va_arg instruction only works on Darwin");
9570 
9571   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9572   EVT VT = Op.getValueType();
9573   SDLoc DL(Op);
9574   SDValue Chain = Op.getOperand(0);
9575   SDValue Addr = Op.getOperand(1);
9576   MaybeAlign Align(Op.getConstantOperandVal(3));
9577   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
9578   auto PtrVT = getPointerTy(DAG.getDataLayout());
9579   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
9580   SDValue VAList =
9581       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
9582   Chain = VAList.getValue(1);
9583   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
9584 
9585   if (VT.isScalableVector())
9586     report_fatal_error("Passing SVE types to variadic functions is "
9587                        "currently not supported");
9588 
9589   if (Align && *Align > MinSlotSize) {
9590     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
9591                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
9592     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
9593                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
9594   }
9595 
9596   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9597   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
9598 
9599   // Scalar integer and FP values smaller than 64 bits are implicitly extended
9600   // up to 64 bits.  At the very least, we have to increase the striding of the
9601   // vaargs list to match this, and for FP values we need to introduce
9602   // FP_ROUND nodes as well.
9603   if (VT.isInteger() && !VT.isVector())
9604     ArgSize = std::max(ArgSize, MinSlotSize);
9605   bool NeedFPTrunc = false;
9606   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
9607     ArgSize = 8;
9608     NeedFPTrunc = true;
9609   }
9610 
9611   // Increment the pointer, VAList, to the next vaarg
9612   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
9613                                DAG.getConstant(ArgSize, DL, PtrVT));
9614   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
9615 
9616   // Store the incremented VAList to the legalized pointer
9617   SDValue APStore =
9618       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
9619 
9620   // Load the actual argument out of the pointer VAList
9621   if (NeedFPTrunc) {
9622     // Load the value as an f64.
9623     SDValue WideFP =
9624         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
9625     // Round the value down to an f32.
9626     SDValue NarrowFP =
9627         DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
9628                     DAG.getIntPtrConstant(1, DL, /*isTarget=*/true));
9629     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
9630     // Merge the rounded value with the chain output of the load.
9631     return DAG.getMergeValues(Ops, DL);
9632   }
9633 
9634   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
9635 }
9636 
9637 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
9638                                               SelectionDAG &DAG) const {
9639   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9640   MFI.setFrameAddressIsTaken(true);
9641 
9642   EVT VT = Op.getValueType();
9643   SDLoc DL(Op);
9644   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9645   SDValue FrameAddr =
9646       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
9647   while (Depth--)
9648     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
9649                             MachinePointerInfo());
9650 
9651   if (Subtarget->isTargetILP32())
9652     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
9653                             DAG.getValueType(VT));
9654 
9655   return FrameAddr;
9656 }
9657 
9658 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
9659                                               SelectionDAG &DAG) const {
9660   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9661 
9662   EVT VT = getPointerTy(DAG.getDataLayout());
9663   SDLoc DL(Op);
9664   int FI = MFI.CreateFixedObject(4, 0, false);
9665   return DAG.getFrameIndex(FI, VT);
9666 }
9667 
9668 #define GET_REGISTER_MATCHER
9669 #include "AArch64GenAsmMatcher.inc"
9670 
9671 // FIXME? Maybe this could be a TableGen attribute on some registers and
9672 // this table could be generated automatically from RegInfo.
9673 Register AArch64TargetLowering::
9674 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
9675   Register Reg = MatchRegisterName(RegName);
9676   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
9677     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
9678     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
9679     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
9680       Reg = 0;
9681   }
9682   if (Reg)
9683     return Reg;
9684   report_fatal_error(Twine("Invalid register name \""
9685                               + StringRef(RegName)  + "\"."));
9686 }
9687 
9688 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
9689                                                      SelectionDAG &DAG) const {
9690   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
9691 
9692   EVT VT = Op.getValueType();
9693   SDLoc DL(Op);
9694 
9695   SDValue FrameAddr =
9696       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
9697   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
9698 
9699   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
9700 }
9701 
9702 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
9703                                                SelectionDAG &DAG) const {
9704   MachineFunction &MF = DAG.getMachineFunction();
9705   MachineFrameInfo &MFI = MF.getFrameInfo();
9706   MFI.setReturnAddressIsTaken(true);
9707 
9708   EVT VT = Op.getValueType();
9709   SDLoc DL(Op);
9710   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9711   SDValue ReturnAddress;
9712   if (Depth) {
9713     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9714     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
9715     ReturnAddress = DAG.getLoad(
9716         VT, DL, DAG.getEntryNode(),
9717         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
9718   } else {
9719     // Return LR, which contains the return address. Mark it an implicit
9720     // live-in.
9721     Register Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
9722     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
9723   }
9724 
9725   // The XPACLRI instruction assembles to a hint-space instruction before
9726   // Armv8.3-A therefore this instruction can be safely used for any pre
9727   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
9728   // that instead.
9729   SDNode *St;
9730   if (Subtarget->hasPAuth()) {
9731     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
9732   } else {
9733     // XPACLRI operates on LR therefore we must move the operand accordingly.
9734     SDValue Chain =
9735         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
9736     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
9737   }
9738   return SDValue(St, 0);
9739 }
9740 
9741 /// LowerShiftParts - Lower SHL_PARTS/SRA_PARTS/SRL_PARTS, which returns two
9742 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
9743 SDValue AArch64TargetLowering::LowerShiftParts(SDValue Op,
9744                                                SelectionDAG &DAG) const {
9745   SDValue Lo, Hi;
9746   expandShiftParts(Op.getNode(), Lo, Hi, DAG);
9747   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
9748 }
9749 
9750 bool AArch64TargetLowering::isOffsetFoldingLegal(
9751     const GlobalAddressSDNode *GA) const {
9752   // Offsets are folded in the DAG combine rather than here so that we can
9753   // intelligently choose an offset based on the uses.
9754   return false;
9755 }
9756 
9757 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
9758                                          bool OptForSize) const {
9759   bool IsLegal = false;
9760   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
9761   // 16-bit case when target has full fp16 support.
9762   // FIXME: We should be able to handle f128 as well with a clever lowering.
9763   const APInt ImmInt = Imm.bitcastToAPInt();
9764   if (VT == MVT::f64)
9765     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
9766   else if (VT == MVT::f32)
9767     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
9768   else if (VT == MVT::f16 || VT == MVT::bf16)
9769     IsLegal =
9770         (Subtarget->hasFullFP16() && AArch64_AM::getFP16Imm(ImmInt) != -1) ||
9771         Imm.isPosZero();
9772 
9773   // If we can not materialize in immediate field for fmov, check if the
9774   // value can be encoded as the immediate operand of a logical instruction.
9775   // The immediate value will be created with either MOVZ, MOVN, or ORR.
9776   // TODO: fmov h0, w0 is also legal, however we don't have an isel pattern to
9777   //       generate that fmov.
9778   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
9779     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
9780     // however the mov+fmov sequence is always better because of the reduced
9781     // cache pressure. The timings are still the same if you consider
9782     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
9783     // movw+movk is fused). So we limit up to 2 instrdduction at most.
9784     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
9785     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), Insn);
9786     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
9787     IsLegal = Insn.size() <= Limit;
9788   }
9789 
9790   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT
9791                     << " imm value: "; Imm.dump(););
9792   return IsLegal;
9793 }
9794 
9795 //===----------------------------------------------------------------------===//
9796 //                          AArch64 Optimization Hooks
9797 //===----------------------------------------------------------------------===//
9798 
9799 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
9800                            SDValue Operand, SelectionDAG &DAG,
9801                            int &ExtraSteps) {
9802   EVT VT = Operand.getValueType();
9803   if ((ST->hasNEON() &&
9804        (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
9805         VT == MVT::f32 || VT == MVT::v1f32 || VT == MVT::v2f32 ||
9806         VT == MVT::v4f32)) ||
9807       (ST->hasSVE() &&
9808        (VT == MVT::nxv8f16 || VT == MVT::nxv4f32 || VT == MVT::nxv2f64))) {
9809     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
9810       // For the reciprocal estimates, convergence is quadratic, so the number
9811       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
9812       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
9813       // the result for float (23 mantissa bits) is 2 and for double (52
9814       // mantissa bits) is 3.
9815       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
9816 
9817     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
9818   }
9819 
9820   return SDValue();
9821 }
9822 
9823 SDValue
9824 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
9825                                         const DenormalMode &Mode) const {
9826   SDLoc DL(Op);
9827   EVT VT = Op.getValueType();
9828   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9829   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
9830   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
9831 }
9832 
9833 SDValue
9834 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
9835                                                    SelectionDAG &DAG) const {
9836   return Op;
9837 }
9838 
9839 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
9840                                                SelectionDAG &DAG, int Enabled,
9841                                                int &ExtraSteps,
9842                                                bool &UseOneConst,
9843                                                bool Reciprocal) const {
9844   if (Enabled == ReciprocalEstimate::Enabled ||
9845       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
9846     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
9847                                        DAG, ExtraSteps)) {
9848       SDLoc DL(Operand);
9849       EVT VT = Operand.getValueType();
9850 
9851       SDNodeFlags Flags;
9852       Flags.setAllowReassociation(true);
9853 
9854       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
9855       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
9856       for (int i = ExtraSteps; i > 0; --i) {
9857         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
9858                                    Flags);
9859         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
9860         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
9861       }
9862       if (!Reciprocal)
9863         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
9864 
9865       ExtraSteps = 0;
9866       return Estimate;
9867     }
9868 
9869   return SDValue();
9870 }
9871 
9872 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
9873                                                 SelectionDAG &DAG, int Enabled,
9874                                                 int &ExtraSteps) const {
9875   if (Enabled == ReciprocalEstimate::Enabled)
9876     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
9877                                        DAG, ExtraSteps)) {
9878       SDLoc DL(Operand);
9879       EVT VT = Operand.getValueType();
9880 
9881       SDNodeFlags Flags;
9882       Flags.setAllowReassociation(true);
9883 
9884       // Newton reciprocal iteration: E * (2 - X * E)
9885       // AArch64 reciprocal iteration instruction: (2 - M * N)
9886       for (int i = ExtraSteps; i > 0; --i) {
9887         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
9888                                    Estimate, Flags);
9889         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
9890       }
9891 
9892       ExtraSteps = 0;
9893       return Estimate;
9894     }
9895 
9896   return SDValue();
9897 }
9898 
9899 //===----------------------------------------------------------------------===//
9900 //                          AArch64 Inline Assembly Support
9901 //===----------------------------------------------------------------------===//
9902 
9903 // Table of Constraints
9904 // TODO: This is the current set of constraints supported by ARM for the
9905 // compiler, not all of them may make sense.
9906 //
9907 // r - A general register
9908 // w - An FP/SIMD register of some size in the range v0-v31
9909 // x - An FP/SIMD register of some size in the range v0-v15
9910 // I - Constant that can be used with an ADD instruction
9911 // J - Constant that can be used with a SUB instruction
9912 // K - Constant that can be used with a 32-bit logical instruction
9913 // L - Constant that can be used with a 64-bit logical instruction
9914 // M - Constant that can be used as a 32-bit MOV immediate
9915 // N - Constant that can be used as a 64-bit MOV immediate
9916 // Q - A memory reference with base register and no offset
9917 // S - A symbolic address
9918 // Y - Floating point constant zero
9919 // Z - Integer constant zero
9920 //
9921 //   Note that general register operands will be output using their 64-bit x
9922 // register name, whatever the size of the variable, unless the asm operand
9923 // is prefixed by the %w modifier. Floating-point and SIMD register operands
9924 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
9925 // %q modifier.
9926 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
9927   // At this point, we have to lower this constraint to something else, so we
9928   // lower it to an "r" or "w". However, by doing this we will force the result
9929   // to be in register, while the X constraint is much more permissive.
9930   //
9931   // Although we are correct (we are free to emit anything, without
9932   // constraints), we might break use cases that would expect us to be more
9933   // efficient and emit something else.
9934   if (!Subtarget->hasFPARMv8())
9935     return "r";
9936 
9937   if (ConstraintVT.isFloatingPoint())
9938     return "w";
9939 
9940   if (ConstraintVT.isVector() &&
9941      (ConstraintVT.getSizeInBits() == 64 ||
9942       ConstraintVT.getSizeInBits() == 128))
9943     return "w";
9944 
9945   return "r";
9946 }
9947 
9948 enum PredicateConstraint {
9949   Upl,
9950   Upa,
9951   Invalid
9952 };
9953 
9954 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
9955   PredicateConstraint P = PredicateConstraint::Invalid;
9956   if (Constraint == "Upa")
9957     P = PredicateConstraint::Upa;
9958   if (Constraint == "Upl")
9959     P = PredicateConstraint::Upl;
9960   return P;
9961 }
9962 
9963 // The set of cc code supported is from
9964 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Flag-Output-Operands
9965 static AArch64CC::CondCode parseConstraintCode(llvm::StringRef Constraint) {
9966   AArch64CC::CondCode Cond = StringSwitch<AArch64CC::CondCode>(Constraint)
9967                                  .Case("{@cchi}", AArch64CC::HI)
9968                                  .Case("{@cccs}", AArch64CC::HS)
9969                                  .Case("{@cclo}", AArch64CC::LO)
9970                                  .Case("{@ccls}", AArch64CC::LS)
9971                                  .Case("{@cccc}", AArch64CC::LO)
9972                                  .Case("{@cceq}", AArch64CC::EQ)
9973                                  .Case("{@ccgt}", AArch64CC::GT)
9974                                  .Case("{@ccge}", AArch64CC::GE)
9975                                  .Case("{@cclt}", AArch64CC::LT)
9976                                  .Case("{@ccle}", AArch64CC::LE)
9977                                  .Case("{@cchs}", AArch64CC::HS)
9978                                  .Case("{@ccne}", AArch64CC::NE)
9979                                  .Case("{@ccvc}", AArch64CC::VC)
9980                                  .Case("{@ccpl}", AArch64CC::PL)
9981                                  .Case("{@ccvs}", AArch64CC::VS)
9982                                  .Case("{@ccmi}", AArch64CC::MI)
9983                                  .Default(AArch64CC::Invalid);
9984   return Cond;
9985 }
9986 
9987 /// Helper function to create 'CSET', which is equivalent to 'CSINC <Wd>, WZR,
9988 /// WZR, invert(<cond>)'.
9989 static SDValue getSETCC(AArch64CC::CondCode CC, SDValue NZCV, const SDLoc &DL,
9990                         SelectionDAG &DAG) {
9991   return DAG.getNode(
9992       AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32),
9993       DAG.getConstant(0, DL, MVT::i32),
9994       DAG.getConstant(getInvertedCondCode(CC), DL, MVT::i32), NZCV);
9995 }
9996 
9997 // Lower @cc flag output via getSETCC.
9998 SDValue AArch64TargetLowering::LowerAsmOutputForConstraint(
9999     SDValue &Chain, SDValue &Glue, const SDLoc &DL,
10000     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
10001   AArch64CC::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
10002   if (Cond == AArch64CC::Invalid)
10003     return SDValue();
10004   // The output variable should be a scalar integer.
10005   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
10006       OpInfo.ConstraintVT.getSizeInBits() < 8)
10007     report_fatal_error("Flag output operand is of invalid type");
10008 
10009   // Get NZCV register. Only update chain when copyfrom is glued.
10010   if (Glue.getNode()) {
10011     Glue = DAG.getCopyFromReg(Chain, DL, AArch64::NZCV, MVT::i32, Glue);
10012     Chain = Glue.getValue(1);
10013   } else
10014     Glue = DAG.getCopyFromReg(Chain, DL, AArch64::NZCV, MVT::i32);
10015   // Extract CC code.
10016   SDValue CC = getSETCC(Cond, Glue, DL, DAG);
10017 
10018   SDValue Result;
10019 
10020   // Truncate or ZERO_EXTEND based on value types.
10021   if (OpInfo.ConstraintVT.getSizeInBits() <= 32)
10022     Result = DAG.getNode(ISD::TRUNCATE, DL, OpInfo.ConstraintVT, CC);
10023   else
10024     Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
10025 
10026   return Result;
10027 }
10028 
10029 /// getConstraintType - Given a constraint letter, return the type of
10030 /// constraint it is for this target.
10031 AArch64TargetLowering::ConstraintType
10032 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
10033   if (Constraint.size() == 1) {
10034     switch (Constraint[0]) {
10035     default:
10036       break;
10037     case 'x':
10038     case 'w':
10039     case 'y':
10040       return C_RegisterClass;
10041     // An address with a single base register. Due to the way we
10042     // currently handle addresses it is the same as 'r'.
10043     case 'Q':
10044       return C_Memory;
10045     case 'I':
10046     case 'J':
10047     case 'K':
10048     case 'L':
10049     case 'M':
10050     case 'N':
10051     case 'Y':
10052     case 'Z':
10053       return C_Immediate;
10054     case 'z':
10055     case 'S': // A symbolic address
10056       return C_Other;
10057     }
10058   } else if (parsePredicateConstraint(Constraint) !=
10059              PredicateConstraint::Invalid)
10060       return C_RegisterClass;
10061   else if (parseConstraintCode(Constraint) != AArch64CC::Invalid)
10062     return C_Other;
10063   return TargetLowering::getConstraintType(Constraint);
10064 }
10065 
10066 /// Examine constraint type and operand type and determine a weight value.
10067 /// This object must already have been set up with the operand type
10068 /// and the current alternative constraint selected.
10069 TargetLowering::ConstraintWeight
10070 AArch64TargetLowering::getSingleConstraintMatchWeight(
10071     AsmOperandInfo &info, const char *constraint) const {
10072   ConstraintWeight weight = CW_Invalid;
10073   Value *CallOperandVal = info.CallOperandVal;
10074   // If we don't have a value, we can't do a match,
10075   // but allow it at the lowest weight.
10076   if (!CallOperandVal)
10077     return CW_Default;
10078   Type *type = CallOperandVal->getType();
10079   // Look at the constraint type.
10080   switch (*constraint) {
10081   default:
10082     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10083     break;
10084   case 'x':
10085   case 'w':
10086   case 'y':
10087     if (type->isFloatingPointTy() || type->isVectorTy())
10088       weight = CW_Register;
10089     break;
10090   case 'z':
10091     weight = CW_Constant;
10092     break;
10093   case 'U':
10094     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
10095       weight = CW_Register;
10096     break;
10097   }
10098   return weight;
10099 }
10100 
10101 std::pair<unsigned, const TargetRegisterClass *>
10102 AArch64TargetLowering::getRegForInlineAsmConstraint(
10103     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10104   if (Constraint.size() == 1) {
10105     switch (Constraint[0]) {
10106     case 'r':
10107       if (VT.isScalableVector())
10108         return std::make_pair(0U, nullptr);
10109       if (Subtarget->hasLS64() && VT.getSizeInBits() == 512)
10110         return std::make_pair(0U, &AArch64::GPR64x8ClassRegClass);
10111       if (VT.getFixedSizeInBits() == 64)
10112         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
10113       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
10114     case 'w': {
10115       if (!Subtarget->hasFPARMv8())
10116         break;
10117       if (VT.isScalableVector()) {
10118         if (VT.getVectorElementType() != MVT::i1)
10119           return std::make_pair(0U, &AArch64::ZPRRegClass);
10120         return std::make_pair(0U, nullptr);
10121       }
10122       uint64_t VTSize = VT.getFixedSizeInBits();
10123       if (VTSize == 16)
10124         return std::make_pair(0U, &AArch64::FPR16RegClass);
10125       if (VTSize == 32)
10126         return std::make_pair(0U, &AArch64::FPR32RegClass);
10127       if (VTSize == 64)
10128         return std::make_pair(0U, &AArch64::FPR64RegClass);
10129       if (VTSize == 128)
10130         return std::make_pair(0U, &AArch64::FPR128RegClass);
10131       break;
10132     }
10133     // The instructions that this constraint is designed for can
10134     // only take 128-bit registers so just use that regclass.
10135     case 'x':
10136       if (!Subtarget->hasFPARMv8())
10137         break;
10138       if (VT.isScalableVector())
10139         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
10140       if (VT.getSizeInBits() == 128)
10141         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
10142       break;
10143     case 'y':
10144       if (!Subtarget->hasFPARMv8())
10145         break;
10146       if (VT.isScalableVector())
10147         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
10148       break;
10149     }
10150   } else {
10151     PredicateConstraint PC = parsePredicateConstraint(Constraint);
10152     if (PC != PredicateConstraint::Invalid) {
10153       if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
10154         return std::make_pair(0U, nullptr);
10155       bool restricted = (PC == PredicateConstraint::Upl);
10156       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
10157                         : std::make_pair(0U, &AArch64::PPRRegClass);
10158     }
10159   }
10160   if (StringRef("{cc}").equals_insensitive(Constraint) ||
10161       parseConstraintCode(Constraint) != AArch64CC::Invalid)
10162     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
10163 
10164   // Use the default implementation in TargetLowering to convert the register
10165   // constraint into a member of a register class.
10166   std::pair<unsigned, const TargetRegisterClass *> Res;
10167   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10168 
10169   // Not found as a standard register?
10170   if (!Res.second) {
10171     unsigned Size = Constraint.size();
10172     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
10173         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
10174       int RegNo;
10175       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
10176       if (!Failed && RegNo >= 0 && RegNo <= 31) {
10177         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
10178         // By default we'll emit v0-v31 for this unless there's a modifier where
10179         // we'll emit the correct register as well.
10180         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
10181           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
10182           Res.second = &AArch64::FPR64RegClass;
10183         } else {
10184           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
10185           Res.second = &AArch64::FPR128RegClass;
10186         }
10187       }
10188     }
10189   }
10190 
10191   if (Res.second && !Subtarget->hasFPARMv8() &&
10192       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
10193       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
10194     return std::make_pair(0U, nullptr);
10195 
10196   return Res;
10197 }
10198 
10199 EVT AArch64TargetLowering::getAsmOperandValueType(const DataLayout &DL,
10200                                                   llvm::Type *Ty,
10201                                                   bool AllowUnknown) const {
10202   if (Subtarget->hasLS64() && Ty->isIntegerTy(512))
10203     return EVT(MVT::i64x8);
10204 
10205   return TargetLowering::getAsmOperandValueType(DL, Ty, AllowUnknown);
10206 }
10207 
10208 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10209 /// vector.  If it is invalid, don't add anything to Ops.
10210 void AArch64TargetLowering::LowerAsmOperandForConstraint(
10211     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10212     SelectionDAG &DAG) const {
10213   SDValue Result;
10214 
10215   // Currently only support length 1 constraints.
10216   if (Constraint.length() != 1)
10217     return;
10218 
10219   char ConstraintLetter = Constraint[0];
10220   switch (ConstraintLetter) {
10221   default:
10222     break;
10223 
10224   // This set of constraints deal with valid constants for various instructions.
10225   // Validate and return a target constant for them if we can.
10226   case 'z': {
10227     // 'z' maps to xzr or wzr so it needs an input of 0.
10228     if (!isNullConstant(Op))
10229       return;
10230 
10231     if (Op.getValueType() == MVT::i64)
10232       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
10233     else
10234       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
10235     break;
10236   }
10237   case 'S': {
10238     // An absolute symbolic address or label reference.
10239     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10240       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10241                                           GA->getValueType(0));
10242     } else if (const BlockAddressSDNode *BA =
10243                    dyn_cast<BlockAddressSDNode>(Op)) {
10244       Result =
10245           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
10246     } else
10247       return;
10248     break;
10249   }
10250 
10251   case 'I':
10252   case 'J':
10253   case 'K':
10254   case 'L':
10255   case 'M':
10256   case 'N':
10257     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10258     if (!C)
10259       return;
10260 
10261     // Grab the value and do some validation.
10262     uint64_t CVal = C->getZExtValue();
10263     switch (ConstraintLetter) {
10264     // The I constraint applies only to simple ADD or SUB immediate operands:
10265     // i.e. 0 to 4095 with optional shift by 12
10266     // The J constraint applies only to ADD or SUB immediates that would be
10267     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
10268     // instruction [or vice versa], in other words -1 to -4095 with optional
10269     // left shift by 12.
10270     case 'I':
10271       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
10272         break;
10273       return;
10274     case 'J': {
10275       uint64_t NVal = -C->getSExtValue();
10276       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
10277         CVal = C->getSExtValue();
10278         break;
10279       }
10280       return;
10281     }
10282     // The K and L constraints apply *only* to logical immediates, including
10283     // what used to be the MOVI alias for ORR (though the MOVI alias has now
10284     // been removed and MOV should be used). So these constraints have to
10285     // distinguish between bit patterns that are valid 32-bit or 64-bit
10286     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
10287     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
10288     // versa.
10289     case 'K':
10290       if (AArch64_AM::isLogicalImmediate(CVal, 32))
10291         break;
10292       return;
10293     case 'L':
10294       if (AArch64_AM::isLogicalImmediate(CVal, 64))
10295         break;
10296       return;
10297     // The M and N constraints are a superset of K and L respectively, for use
10298     // with the MOV (immediate) alias. As well as the logical immediates they
10299     // also match 32 or 64-bit immediates that can be loaded either using a
10300     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
10301     // (M) or 64-bit 0x1234000000000000 (N) etc.
10302     // As a note some of this code is liberally stolen from the asm parser.
10303     case 'M': {
10304       if (!isUInt<32>(CVal))
10305         return;
10306       if (AArch64_AM::isLogicalImmediate(CVal, 32))
10307         break;
10308       if ((CVal & 0xFFFF) == CVal)
10309         break;
10310       if ((CVal & 0xFFFF0000ULL) == CVal)
10311         break;
10312       uint64_t NCVal = ~(uint32_t)CVal;
10313       if ((NCVal & 0xFFFFULL) == NCVal)
10314         break;
10315       if ((NCVal & 0xFFFF0000ULL) == NCVal)
10316         break;
10317       return;
10318     }
10319     case 'N': {
10320       if (AArch64_AM::isLogicalImmediate(CVal, 64))
10321         break;
10322       if ((CVal & 0xFFFFULL) == CVal)
10323         break;
10324       if ((CVal & 0xFFFF0000ULL) == CVal)
10325         break;
10326       if ((CVal & 0xFFFF00000000ULL) == CVal)
10327         break;
10328       if ((CVal & 0xFFFF000000000000ULL) == CVal)
10329         break;
10330       uint64_t NCVal = ~CVal;
10331       if ((NCVal & 0xFFFFULL) == NCVal)
10332         break;
10333       if ((NCVal & 0xFFFF0000ULL) == NCVal)
10334         break;
10335       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
10336         break;
10337       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
10338         break;
10339       return;
10340     }
10341     default:
10342       return;
10343     }
10344 
10345     // All assembler immediates are 64-bit integers.
10346     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
10347     break;
10348   }
10349 
10350   if (Result.getNode()) {
10351     Ops.push_back(Result);
10352     return;
10353   }
10354 
10355   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10356 }
10357 
10358 //===----------------------------------------------------------------------===//
10359 //                     AArch64 Advanced SIMD Support
10360 //===----------------------------------------------------------------------===//
10361 
10362 /// WidenVector - Given a value in the V64 register class, produce the
10363 /// equivalent value in the V128 register class.
10364 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
10365   EVT VT = V64Reg.getValueType();
10366   unsigned NarrowSize = VT.getVectorNumElements();
10367   MVT EltTy = VT.getVectorElementType().getSimpleVT();
10368   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
10369   SDLoc DL(V64Reg);
10370 
10371   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
10372                      V64Reg, DAG.getConstant(0, DL, MVT::i64));
10373 }
10374 
10375 /// getExtFactor - Determine the adjustment factor for the position when
10376 /// generating an "extract from vector registers" instruction.
10377 static unsigned getExtFactor(SDValue &V) {
10378   EVT EltType = V.getValueType().getVectorElementType();
10379   return EltType.getSizeInBits() / 8;
10380 }
10381 
10382 // Check if a vector is built from one vector via extracted elements of
10383 // another together with an AND mask, ensuring that all elements fit
10384 // within range. This can be reconstructed using AND and NEON's TBL1.
10385 SDValue ReconstructShuffleWithRuntimeMask(SDValue Op, SelectionDAG &DAG) {
10386   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
10387   SDLoc dl(Op);
10388   EVT VT = Op.getValueType();
10389   assert(!VT.isScalableVector() &&
10390          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
10391 
10392   // Can only recreate a shuffle with 16xi8 or 8xi8 elements, as they map
10393   // directly to TBL1.
10394   if (VT != MVT::v16i8 && VT != MVT::v8i8)
10395     return SDValue();
10396 
10397   unsigned NumElts = VT.getVectorNumElements();
10398   assert((NumElts == 8 || NumElts == 16) &&
10399          "Need to have exactly 8 or 16 elements in vector.");
10400 
10401   SDValue SourceVec;
10402   SDValue MaskSourceVec;
10403   SmallVector<SDValue, 16> AndMaskConstants;
10404 
10405   for (unsigned i = 0; i < NumElts; ++i) {
10406     SDValue V = Op.getOperand(i);
10407     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10408       return SDValue();
10409 
10410     SDValue OperandSourceVec = V.getOperand(0);
10411     if (!SourceVec)
10412       SourceVec = OperandSourceVec;
10413     else if (SourceVec != OperandSourceVec)
10414       return SDValue();
10415 
10416     // This only looks at shuffles with elements that are
10417     // a) truncated by a constant AND mask extracted from a mask vector, or
10418     // b) extracted directly from a mask vector.
10419     SDValue MaskSource = V.getOperand(1);
10420     if (MaskSource.getOpcode() == ISD::AND) {
10421       if (!isa<ConstantSDNode>(MaskSource.getOperand(1)))
10422         return SDValue();
10423 
10424       AndMaskConstants.push_back(MaskSource.getOperand(1));
10425       MaskSource = MaskSource->getOperand(0);
10426     } else if (!AndMaskConstants.empty()) {
10427       // Either all or no operands should have an AND mask.
10428       return SDValue();
10429     }
10430 
10431     // An ANY_EXTEND may be inserted between the AND and the source vector
10432     // extraction. We don't care about that, so we can just skip it.
10433     if (MaskSource.getOpcode() == ISD::ANY_EXTEND)
10434       MaskSource = MaskSource.getOperand(0);
10435 
10436     if (MaskSource.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10437       return SDValue();
10438 
10439     SDValue MaskIdx = MaskSource.getOperand(1);
10440     if (!isa<ConstantSDNode>(MaskIdx) ||
10441         !cast<ConstantSDNode>(MaskIdx)->getConstantIntValue()->equalsInt(i))
10442       return SDValue();
10443 
10444     // We only apply this if all elements come from the same vector with the
10445     // same vector type.
10446     if (!MaskSourceVec) {
10447       MaskSourceVec = MaskSource->getOperand(0);
10448       if (MaskSourceVec.getValueType() != VT)
10449         return SDValue();
10450     } else if (MaskSourceVec != MaskSource->getOperand(0)) {
10451       return SDValue();
10452     }
10453   }
10454 
10455   // We need a v16i8 for TBL, so we extend the source with a placeholder vector
10456   // for v8i8 to get a v16i8. As the pattern we are replacing is extract +
10457   // insert, we know that the index in the mask must be smaller than the number
10458   // of elements in the source, or we would have an out-of-bounds access.
10459   if (NumElts == 8)
10460     SourceVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, SourceVec,
10461                             DAG.getUNDEF(VT));
10462 
10463   // Preconditions met, so we can use a vector (AND +) TBL to build this vector.
10464   if (!AndMaskConstants.empty())
10465     MaskSourceVec = DAG.getNode(ISD::AND, dl, VT, MaskSourceVec,
10466                                 DAG.getBuildVector(VT, dl, AndMaskConstants));
10467 
10468   return DAG.getNode(
10469       ISD::INTRINSIC_WO_CHAIN, dl, VT,
10470       DAG.getConstant(Intrinsic::aarch64_neon_tbl1, dl, MVT::i32), SourceVec,
10471       MaskSourceVec);
10472 }
10473 
10474 // Gather data to see if the operation can be modelled as a
10475 // shuffle in combination with VEXTs.
10476 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
10477                                                   SelectionDAG &DAG) const {
10478   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
10479   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
10480   SDLoc dl(Op);
10481   EVT VT = Op.getValueType();
10482   assert(!VT.isScalableVector() &&
10483          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
10484   unsigned NumElts = VT.getVectorNumElements();
10485 
10486   struct ShuffleSourceInfo {
10487     SDValue Vec;
10488     unsigned MinElt;
10489     unsigned MaxElt;
10490 
10491     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
10492     // be compatible with the shuffle we intend to construct. As a result
10493     // ShuffleVec will be some sliding window into the original Vec.
10494     SDValue ShuffleVec;
10495 
10496     // Code should guarantee that element i in Vec starts at element "WindowBase
10497     // + i * WindowScale in ShuffleVec".
10498     int WindowBase;
10499     int WindowScale;
10500 
10501     ShuffleSourceInfo(SDValue Vec)
10502       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
10503           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
10504 
10505     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
10506   };
10507 
10508   // First gather all vectors used as an immediate source for this BUILD_VECTOR
10509   // node.
10510   SmallVector<ShuffleSourceInfo, 2> Sources;
10511   for (unsigned i = 0; i < NumElts; ++i) {
10512     SDValue V = Op.getOperand(i);
10513     if (V.isUndef())
10514       continue;
10515     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10516              !isa<ConstantSDNode>(V.getOperand(1)) ||
10517              V.getOperand(0).getValueType().isScalableVector()) {
10518       LLVM_DEBUG(
10519           dbgs() << "Reshuffle failed: "
10520                     "a shuffle can only come from building a vector from "
10521                     "various elements of other fixed-width vectors, provided "
10522                     "their indices are constant\n");
10523       return SDValue();
10524     }
10525 
10526     // Add this element source to the list if it's not already there.
10527     SDValue SourceVec = V.getOperand(0);
10528     auto Source = find(Sources, SourceVec);
10529     if (Source == Sources.end())
10530       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
10531 
10532     // Update the minimum and maximum lane number seen.
10533     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
10534     Source->MinElt = std::min(Source->MinElt, EltNo);
10535     Source->MaxElt = std::max(Source->MaxElt, EltNo);
10536   }
10537 
10538   // If we have 3 or 4 sources, try to generate a TBL, which will at least be
10539   // better than moving to/from gpr registers for larger vectors.
10540   if ((Sources.size() == 3 || Sources.size() == 4) && NumElts > 4) {
10541     // Construct a mask for the tbl. We may need to adjust the index for types
10542     // larger than i8.
10543     SmallVector<unsigned, 16> Mask;
10544     unsigned OutputFactor = VT.getScalarSizeInBits() / 8;
10545     for (unsigned I = 0; I < NumElts; ++I) {
10546       SDValue V = Op.getOperand(I);
10547       if (V.isUndef()) {
10548         for (unsigned OF = 0; OF < OutputFactor; OF++)
10549           Mask.push_back(-1);
10550         continue;
10551       }
10552       // Set the Mask lanes adjusted for the size of the input and output
10553       // lanes. The Mask is always i8, so it will set OutputFactor lanes per
10554       // output element, adjusted in their positions per input and output types.
10555       unsigned Lane = V.getConstantOperandVal(1);
10556       for (unsigned S = 0; S < Sources.size(); S++) {
10557         if (V.getOperand(0) == Sources[S].Vec) {
10558           unsigned InputSize = Sources[S].Vec.getScalarValueSizeInBits();
10559           unsigned InputBase = 16 * S + Lane * InputSize / 8;
10560           for (unsigned OF = 0; OF < OutputFactor; OF++)
10561             Mask.push_back(InputBase + OF);
10562           break;
10563         }
10564       }
10565     }
10566 
10567     // Construct the tbl3/tbl4 out of an intrinsic, the sources converted to
10568     // v16i8, and the TBLMask
10569     SmallVector<SDValue, 16> TBLOperands;
10570     TBLOperands.push_back(DAG.getConstant(Sources.size() == 3
10571                                               ? Intrinsic::aarch64_neon_tbl3
10572                                               : Intrinsic::aarch64_neon_tbl4,
10573                                           dl, MVT::i32));
10574     for (unsigned i = 0; i < Sources.size(); i++) {
10575       SDValue Src = Sources[i].Vec;
10576       EVT SrcVT = Src.getValueType();
10577       Src = DAG.getBitcast(SrcVT.is64BitVector() ? MVT::v8i8 : MVT::v16i8, Src);
10578       assert((SrcVT.is64BitVector() || SrcVT.is128BitVector()) &&
10579              "Expected a legally typed vector");
10580       if (SrcVT.is64BitVector())
10581         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, Src,
10582                           DAG.getUNDEF(MVT::v8i8));
10583       TBLOperands.push_back(Src);
10584     }
10585 
10586     SmallVector<SDValue, 16> TBLMask;
10587     for (unsigned i = 0; i < Mask.size(); i++)
10588       TBLMask.push_back(DAG.getConstant(Mask[i], dl, MVT::i32));
10589     assert((Mask.size() == 8 || Mask.size() == 16) &&
10590            "Expected a v8i8 or v16i8 Mask");
10591     TBLOperands.push_back(
10592         DAG.getBuildVector(Mask.size() == 8 ? MVT::v8i8 : MVT::v16i8, dl, TBLMask));
10593 
10594     SDValue Shuffle =
10595         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10596                     Mask.size() == 8 ? MVT::v8i8 : MVT::v16i8, TBLOperands);
10597     return DAG.getBitcast(VT, Shuffle);
10598   }
10599 
10600   if (Sources.size() > 2) {
10601     LLVM_DEBUG(dbgs() << "Reshuffle failed: currently only do something "
10602                       << "sensible when at most two source vectors are "
10603                       << "involved\n");
10604     return SDValue();
10605   }
10606 
10607   // Find out the smallest element size among result and two sources, and use
10608   // it as element size to build the shuffle_vector.
10609   EVT SmallestEltTy = VT.getVectorElementType();
10610   for (auto &Source : Sources) {
10611     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
10612     if (SrcEltTy.bitsLT(SmallestEltTy)) {
10613       SmallestEltTy = SrcEltTy;
10614     }
10615   }
10616   unsigned ResMultiplier =
10617       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
10618   uint64_t VTSize = VT.getFixedSizeInBits();
10619   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
10620   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
10621 
10622   // If the source vector is too wide or too narrow, we may nevertheless be able
10623   // to construct a compatible shuffle either by concatenating it with UNDEF or
10624   // extracting a suitable range of elements.
10625   for (auto &Src : Sources) {
10626     EVT SrcVT = Src.ShuffleVec.getValueType();
10627 
10628     TypeSize SrcVTSize = SrcVT.getSizeInBits();
10629     if (SrcVTSize == TypeSize::Fixed(VTSize))
10630       continue;
10631 
10632     // This stage of the search produces a source with the same element type as
10633     // the original, but with a total width matching the BUILD_VECTOR output.
10634     EVT EltVT = SrcVT.getVectorElementType();
10635     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
10636     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
10637 
10638     if (SrcVTSize.getFixedValue() < VTSize) {
10639       assert(2 * SrcVTSize == VTSize);
10640       // We can pad out the smaller vector for free, so if it's part of a
10641       // shuffle...
10642       Src.ShuffleVec =
10643           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
10644                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
10645       continue;
10646     }
10647 
10648     if (SrcVTSize.getFixedValue() != 2 * VTSize) {
10649       LLVM_DEBUG(
10650           dbgs() << "Reshuffle failed: result vector too small to extract\n");
10651       return SDValue();
10652     }
10653 
10654     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
10655       LLVM_DEBUG(
10656           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
10657       return SDValue();
10658     }
10659 
10660     if (Src.MinElt >= NumSrcElts) {
10661       // The extraction can just take the second half
10662       Src.ShuffleVec =
10663           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
10664                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
10665       Src.WindowBase = -NumSrcElts;
10666     } else if (Src.MaxElt < NumSrcElts) {
10667       // The extraction can just take the first half
10668       Src.ShuffleVec =
10669           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
10670                       DAG.getConstant(0, dl, MVT::i64));
10671     } else {
10672       // An actual VEXT is needed
10673       SDValue VEXTSrc1 =
10674           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
10675                       DAG.getConstant(0, dl, MVT::i64));
10676       SDValue VEXTSrc2 =
10677           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
10678                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
10679       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
10680 
10681       if (!SrcVT.is64BitVector()) {
10682         LLVM_DEBUG(
10683           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
10684                     "for SVE vectors.");
10685         return SDValue();
10686       }
10687 
10688       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
10689                                    VEXTSrc2,
10690                                    DAG.getConstant(Imm, dl, MVT::i32));
10691       Src.WindowBase = -Src.MinElt;
10692     }
10693   }
10694 
10695   // Another possible incompatibility occurs from the vector element types. We
10696   // can fix this by bitcasting the source vectors to the same type we intend
10697   // for the shuffle.
10698   for (auto &Src : Sources) {
10699     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
10700     if (SrcEltTy == SmallestEltTy)
10701       continue;
10702     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
10703     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
10704     Src.WindowScale =
10705         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
10706     Src.WindowBase *= Src.WindowScale;
10707   }
10708 
10709   // Final check before we try to actually produce a shuffle.
10710   LLVM_DEBUG(for (auto Src
10711                   : Sources)
10712                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
10713 
10714   // The stars all align, our next step is to produce the mask for the shuffle.
10715   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
10716   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
10717   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
10718     SDValue Entry = Op.getOperand(i);
10719     if (Entry.isUndef())
10720       continue;
10721 
10722     auto Src = find(Sources, Entry.getOperand(0));
10723     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
10724 
10725     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
10726     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
10727     // segment.
10728     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
10729     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
10730                                VT.getScalarSizeInBits());
10731     int LanesDefined = BitsDefined / BitsPerShuffleLane;
10732 
10733     // This source is expected to fill ResMultiplier lanes of the final shuffle,
10734     // starting at the appropriate offset.
10735     int *LaneMask = &Mask[i * ResMultiplier];
10736 
10737     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
10738     ExtractBase += NumElts * (Src - Sources.begin());
10739     for (int j = 0; j < LanesDefined; ++j)
10740       LaneMask[j] = ExtractBase + j;
10741   }
10742 
10743   // Final check before we try to produce nonsense...
10744   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
10745     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
10746     return SDValue();
10747   }
10748 
10749   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
10750   for (unsigned i = 0; i < Sources.size(); ++i)
10751     ShuffleOps[i] = Sources[i].ShuffleVec;
10752 
10753   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
10754                                          ShuffleOps[1], Mask);
10755   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
10756 
10757   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
10758              dbgs() << "Reshuffle, creating node: "; V.dump(););
10759 
10760   return V;
10761 }
10762 
10763 // check if an EXT instruction can handle the shuffle mask when the
10764 // vector sources of the shuffle are the same.
10765 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
10766   unsigned NumElts = VT.getVectorNumElements();
10767 
10768   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
10769   if (M[0] < 0)
10770     return false;
10771 
10772   Imm = M[0];
10773 
10774   // If this is a VEXT shuffle, the immediate value is the index of the first
10775   // element.  The other shuffle indices must be the successive elements after
10776   // the first one.
10777   unsigned ExpectedElt = Imm;
10778   for (unsigned i = 1; i < NumElts; ++i) {
10779     // Increment the expected index.  If it wraps around, just follow it
10780     // back to index zero and keep going.
10781     ++ExpectedElt;
10782     if (ExpectedElt == NumElts)
10783       ExpectedElt = 0;
10784 
10785     if (M[i] < 0)
10786       continue; // ignore UNDEF indices
10787     if (ExpectedElt != static_cast<unsigned>(M[i]))
10788       return false;
10789   }
10790 
10791   return true;
10792 }
10793 
10794 // Detect patterns of a0,a1,a2,a3,b0,b1,b2,b3,c0,c1,c2,c3,d0,d1,d2,d3 from
10795 // v4i32s. This is really a truncate, which we can construct out of (legal)
10796 // concats and truncate nodes.
10797 static SDValue ReconstructTruncateFromBuildVector(SDValue V, SelectionDAG &DAG) {
10798   if (V.getValueType() != MVT::v16i8)
10799     return SDValue();
10800   assert(V.getNumOperands() == 16 && "Expected 16 operands on the BUILDVECTOR");
10801 
10802   for (unsigned X = 0; X < 4; X++) {
10803     // Check the first item in each group is an extract from lane 0 of a v4i32
10804     // or v4i16.
10805     SDValue BaseExt = V.getOperand(X * 4);
10806     if (BaseExt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10807         (BaseExt.getOperand(0).getValueType() != MVT::v4i16 &&
10808          BaseExt.getOperand(0).getValueType() != MVT::v4i32) ||
10809         !isa<ConstantSDNode>(BaseExt.getOperand(1)) ||
10810         BaseExt.getConstantOperandVal(1) != 0)
10811       return SDValue();
10812     SDValue Base = BaseExt.getOperand(0);
10813     // And check the other items are extracts from the same vector.
10814     for (unsigned Y = 1; Y < 4; Y++) {
10815       SDValue Ext = V.getOperand(X * 4 + Y);
10816       if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10817           Ext.getOperand(0) != Base ||
10818           !isa<ConstantSDNode>(Ext.getOperand(1)) ||
10819           Ext.getConstantOperandVal(1) != Y)
10820         return SDValue();
10821     }
10822   }
10823 
10824   // Turn the buildvector into a series of truncates and concates, which will
10825   // become uzip1's. Any v4i32s we found get truncated to v4i16, which are
10826   // concat together to produce 2 v8i16. These are both truncated and concat
10827   // together.
10828   SDLoc DL(V);
10829   SDValue Trunc[4] = {
10830       V.getOperand(0).getOperand(0), V.getOperand(4).getOperand(0),
10831       V.getOperand(8).getOperand(0), V.getOperand(12).getOperand(0)};
10832   for (SDValue &V : Trunc)
10833     if (V.getValueType() == MVT::v4i32)
10834       V = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i16, V);
10835   SDValue Concat0 =
10836       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, Trunc[0], Trunc[1]);
10837   SDValue Concat1 =
10838       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, Trunc[2], Trunc[3]);
10839   SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, Concat0);
10840   SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, Concat1);
10841   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Trunc0, Trunc1);
10842 }
10843 
10844 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
10845 /// element width than the vector lane type. If that is the case the function
10846 /// returns true and writes the value of the DUP instruction lane operand into
10847 /// DupLaneOp
10848 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
10849                           unsigned &DupLaneOp) {
10850   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
10851          "Only possible block sizes for wide DUP are: 16, 32, 64");
10852 
10853   if (BlockSize <= VT.getScalarSizeInBits())
10854     return false;
10855   if (BlockSize % VT.getScalarSizeInBits() != 0)
10856     return false;
10857   if (VT.getSizeInBits() % BlockSize != 0)
10858     return false;
10859 
10860   size_t SingleVecNumElements = VT.getVectorNumElements();
10861   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
10862   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
10863 
10864   // We are looking for masks like
10865   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
10866   // might be replaced by 'undefined'. BlockIndices will eventually contain
10867   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
10868   // for the above examples)
10869   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
10870   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
10871     for (size_t I = 0; I < NumEltsPerBlock; I++) {
10872       int Elt = M[BlockIndex * NumEltsPerBlock + I];
10873       if (Elt < 0)
10874         continue;
10875       // For now we don't support shuffles that use the second operand
10876       if ((unsigned)Elt >= SingleVecNumElements)
10877         return false;
10878       if (BlockElts[I] < 0)
10879         BlockElts[I] = Elt;
10880       else if (BlockElts[I] != Elt)
10881         return false;
10882     }
10883 
10884   // We found a candidate block (possibly with some undefs). It must be a
10885   // sequence of consecutive integers starting with a value divisible by
10886   // NumEltsPerBlock with some values possibly replaced by undef-s.
10887 
10888   // Find first non-undef element
10889   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
10890   assert(FirstRealEltIter != BlockElts.end() &&
10891          "Shuffle with all-undefs must have been caught by previous cases, "
10892          "e.g. isSplat()");
10893   if (FirstRealEltIter == BlockElts.end()) {
10894     DupLaneOp = 0;
10895     return true;
10896   }
10897 
10898   // Index of FirstRealElt in BlockElts
10899   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
10900 
10901   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
10902     return false;
10903   // BlockElts[0] must have the following value if it isn't undef:
10904   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
10905 
10906   // Check the first element
10907   if (Elt0 % NumEltsPerBlock != 0)
10908     return false;
10909   // Check that the sequence indeed consists of consecutive integers (modulo
10910   // undefs)
10911   for (size_t I = 0; I < NumEltsPerBlock; I++)
10912     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
10913       return false;
10914 
10915   DupLaneOp = Elt0 / NumEltsPerBlock;
10916   return true;
10917 }
10918 
10919 // check if an EXT instruction can handle the shuffle mask when the
10920 // vector sources of the shuffle are different.
10921 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
10922                       unsigned &Imm) {
10923   // Look for the first non-undef element.
10924   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
10925 
10926   // Benefit form APInt to handle overflow when calculating expected element.
10927   unsigned NumElts = VT.getVectorNumElements();
10928   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
10929   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
10930   // The following shuffle indices must be the successive elements after the
10931   // first real element.
10932   bool FoundWrongElt = std::any_of(FirstRealElt + 1, M.end(), [&](int Elt) {
10933     return Elt != ExpectedElt++ && Elt != -1;
10934   });
10935   if (FoundWrongElt)
10936     return false;
10937 
10938   // The index of an EXT is the first element if it is not UNDEF.
10939   // Watch out for the beginning UNDEFs. The EXT index should be the expected
10940   // value of the first element.  E.g.
10941   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
10942   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
10943   // ExpectedElt is the last mask index plus 1.
10944   Imm = ExpectedElt.getZExtValue();
10945 
10946   // There are two difference cases requiring to reverse input vectors.
10947   // For example, for vector <4 x i32> we have the following cases,
10948   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
10949   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
10950   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
10951   // to reverse two input vectors.
10952   if (Imm < NumElts)
10953     ReverseEXT = true;
10954   else
10955     Imm -= NumElts;
10956 
10957   return true;
10958 }
10959 
10960 /// isREVMask - Check if a vector shuffle corresponds to a REV
10961 /// instruction with the specified blocksize.  (The order of the elements
10962 /// within each block of the vector is reversed.)
10963 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
10964   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64 ||
10965           BlockSize == 128) &&
10966          "Only possible block sizes for REV are: 16, 32, 64, 128");
10967 
10968   unsigned EltSz = VT.getScalarSizeInBits();
10969   unsigned NumElts = VT.getVectorNumElements();
10970   unsigned BlockElts = M[0] + 1;
10971   // If the first shuffle index is UNDEF, be optimistic.
10972   if (M[0] < 0)
10973     BlockElts = BlockSize / EltSz;
10974 
10975   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
10976     return false;
10977 
10978   for (unsigned i = 0; i < NumElts; ++i) {
10979     if (M[i] < 0)
10980       continue; // ignore UNDEF indices
10981     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
10982       return false;
10983   }
10984 
10985   return true;
10986 }
10987 
10988 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
10989   unsigned NumElts = VT.getVectorNumElements();
10990   if (NumElts % 2 != 0)
10991     return false;
10992   WhichResult = (M[0] == 0 ? 0 : 1);
10993   unsigned Idx = WhichResult * NumElts / 2;
10994   for (unsigned i = 0; i != NumElts; i += 2) {
10995     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
10996         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
10997       return false;
10998     Idx += 1;
10999   }
11000 
11001   return true;
11002 }
11003 
11004 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
11005   unsigned NumElts = VT.getVectorNumElements();
11006   WhichResult = (M[0] == 0 ? 0 : 1);
11007   for (unsigned i = 0; i != NumElts; ++i) {
11008     if (M[i] < 0)
11009       continue; // ignore UNDEF indices
11010     if ((unsigned)M[i] != 2 * i + WhichResult)
11011       return false;
11012   }
11013 
11014   return true;
11015 }
11016 
11017 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
11018   unsigned NumElts = VT.getVectorNumElements();
11019   if (NumElts % 2 != 0)
11020     return false;
11021   WhichResult = (M[0] == 0 ? 0 : 1);
11022   for (unsigned i = 0; i < NumElts; i += 2) {
11023     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
11024         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
11025       return false;
11026   }
11027   return true;
11028 }
11029 
11030 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
11031 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
11032 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
11033 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
11034   unsigned NumElts = VT.getVectorNumElements();
11035   if (NumElts % 2 != 0)
11036     return false;
11037   WhichResult = (M[0] == 0 ? 0 : 1);
11038   unsigned Idx = WhichResult * NumElts / 2;
11039   for (unsigned i = 0; i != NumElts; i += 2) {
11040     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
11041         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
11042       return false;
11043     Idx += 1;
11044   }
11045 
11046   return true;
11047 }
11048 
11049 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
11050 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
11051 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
11052 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
11053   unsigned Half = VT.getVectorNumElements() / 2;
11054   WhichResult = (M[0] == 0 ? 0 : 1);
11055   for (unsigned j = 0; j != 2; ++j) {
11056     unsigned Idx = WhichResult;
11057     for (unsigned i = 0; i != Half; ++i) {
11058       int MIdx = M[i + j * Half];
11059       if (MIdx >= 0 && (unsigned)MIdx != Idx)
11060         return false;
11061       Idx += 2;
11062     }
11063   }
11064 
11065   return true;
11066 }
11067 
11068 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
11069 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
11070 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
11071 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
11072   unsigned NumElts = VT.getVectorNumElements();
11073   if (NumElts % 2 != 0)
11074     return false;
11075   WhichResult = (M[0] == 0 ? 0 : 1);
11076   for (unsigned i = 0; i < NumElts; i += 2) {
11077     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
11078         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
11079       return false;
11080   }
11081   return true;
11082 }
11083 
11084 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
11085                       bool &DstIsLeft, int &Anomaly) {
11086   if (M.size() != static_cast<size_t>(NumInputElements))
11087     return false;
11088 
11089   int NumLHSMatch = 0, NumRHSMatch = 0;
11090   int LastLHSMismatch = -1, LastRHSMismatch = -1;
11091 
11092   for (int i = 0; i < NumInputElements; ++i) {
11093     if (M[i] == -1) {
11094       ++NumLHSMatch;
11095       ++NumRHSMatch;
11096       continue;
11097     }
11098 
11099     if (M[i] == i)
11100       ++NumLHSMatch;
11101     else
11102       LastLHSMismatch = i;
11103 
11104     if (M[i] == i + NumInputElements)
11105       ++NumRHSMatch;
11106     else
11107       LastRHSMismatch = i;
11108   }
11109 
11110   if (NumLHSMatch == NumInputElements - 1) {
11111     DstIsLeft = true;
11112     Anomaly = LastLHSMismatch;
11113     return true;
11114   } else if (NumRHSMatch == NumInputElements - 1) {
11115     DstIsLeft = false;
11116     Anomaly = LastRHSMismatch;
11117     return true;
11118   }
11119 
11120   return false;
11121 }
11122 
11123 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
11124   if (VT.getSizeInBits() != 128)
11125     return false;
11126 
11127   unsigned NumElts = VT.getVectorNumElements();
11128 
11129   for (int I = 0, E = NumElts / 2; I != E; I++) {
11130     if (Mask[I] != I)
11131       return false;
11132   }
11133 
11134   int Offset = NumElts / 2;
11135   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
11136     if (Mask[I] != I + SplitLHS * Offset)
11137       return false;
11138   }
11139 
11140   return true;
11141 }
11142 
11143 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
11144   SDLoc DL(Op);
11145   EVT VT = Op.getValueType();
11146   SDValue V0 = Op.getOperand(0);
11147   SDValue V1 = Op.getOperand(1);
11148   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
11149 
11150   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
11151       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
11152     return SDValue();
11153 
11154   bool SplitV0 = V0.getValueSizeInBits() == 128;
11155 
11156   if (!isConcatMask(Mask, VT, SplitV0))
11157     return SDValue();
11158 
11159   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11160   if (SplitV0) {
11161     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
11162                      DAG.getConstant(0, DL, MVT::i64));
11163   }
11164   if (V1.getValueSizeInBits() == 128) {
11165     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
11166                      DAG.getConstant(0, DL, MVT::i64));
11167   }
11168   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
11169 }
11170 
11171 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
11172 /// the specified operations to build the shuffle. ID is the perfect-shuffle
11173 //ID, V1 and V2 are the original shuffle inputs. PFEntry is the Perfect shuffle
11174 //table entry and LHS/RHS are the immediate inputs for this stage of the
11175 //shuffle.
11176 static SDValue GeneratePerfectShuffle(unsigned ID, SDValue V1,
11177                                       SDValue V2, unsigned PFEntry, SDValue LHS,
11178                                       SDValue RHS, SelectionDAG &DAG,
11179                                       const SDLoc &dl) {
11180   unsigned OpNum = (PFEntry >> 26) & 0x0F;
11181   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
11182   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
11183 
11184   enum {
11185     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
11186     OP_VREV,
11187     OP_VDUP0,
11188     OP_VDUP1,
11189     OP_VDUP2,
11190     OP_VDUP3,
11191     OP_VEXT1,
11192     OP_VEXT2,
11193     OP_VEXT3,
11194     OP_VUZPL,  // VUZP, left result
11195     OP_VUZPR,  // VUZP, right result
11196     OP_VZIPL,  // VZIP, left result
11197     OP_VZIPR,  // VZIP, right result
11198     OP_VTRNL,  // VTRN, left result
11199     OP_VTRNR,  // VTRN, right result
11200     OP_MOVLANE // Move lane. RHSID is the lane to move into
11201   };
11202 
11203   if (OpNum == OP_COPY) {
11204     if (LHSID == (1 * 9 + 2) * 9 + 3)
11205       return LHS;
11206     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
11207     return RHS;
11208   }
11209 
11210   if (OpNum == OP_MOVLANE) {
11211     // Decompose a PerfectShuffle ID to get the Mask for lane Elt
11212     auto getPFIDLane = [](unsigned ID, int Elt) -> int {
11213       assert(Elt < 4 && "Expected Perfect Lanes to be less than 4");
11214       Elt = 3 - Elt;
11215       while (Elt > 0) {
11216         ID /= 9;
11217         Elt--;
11218       }
11219       return (ID % 9 == 8) ? -1 : ID % 9;
11220     };
11221 
11222     // For OP_MOVLANE shuffles, the RHSID represents the lane to move into. We
11223     // get the lane to move from from the PFID, which is always from the
11224     // original vectors (V1 or V2).
11225     SDValue OpLHS = GeneratePerfectShuffle(
11226         LHSID, V1, V2, PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
11227     EVT VT = OpLHS.getValueType();
11228     assert(RHSID < 8 && "Expected a lane index for RHSID!");
11229     unsigned ExtLane = 0;
11230     SDValue Input;
11231 
11232     // OP_MOVLANE are either D movs (if bit 0x4 is set) or S movs. D movs
11233     // convert into a higher type.
11234     if (RHSID & 0x4) {
11235       int MaskElt = getPFIDLane(ID, (RHSID & 0x01) << 1) >> 1;
11236       if (MaskElt == -1)
11237         MaskElt = (getPFIDLane(ID, ((RHSID & 0x01) << 1) + 1) - 1) >> 1;
11238       assert(MaskElt >= 0 && "Didn't expect an undef movlane index!");
11239       ExtLane = MaskElt < 2 ? MaskElt : (MaskElt - 2);
11240       Input = MaskElt < 2 ? V1 : V2;
11241       if (VT.getScalarSizeInBits() == 16) {
11242         Input = DAG.getBitcast(MVT::v2f32, Input);
11243         OpLHS = DAG.getBitcast(MVT::v2f32, OpLHS);
11244       } else {
11245         assert(VT.getScalarSizeInBits() == 32 &&
11246                "Expected 16 or 32 bit shuffle elemements");
11247         Input = DAG.getBitcast(MVT::v2f64, Input);
11248         OpLHS = DAG.getBitcast(MVT::v2f64, OpLHS);
11249       }
11250     } else {
11251       int MaskElt = getPFIDLane(ID, RHSID);
11252       assert(MaskElt >= 0 && "Didn't expect an undef movlane index!");
11253       ExtLane = MaskElt < 4 ? MaskElt : (MaskElt - 4);
11254       Input = MaskElt < 4 ? V1 : V2;
11255       // Be careful about creating illegal types. Use f16 instead of i16.
11256       if (VT == MVT::v4i16) {
11257         Input = DAG.getBitcast(MVT::v4f16, Input);
11258         OpLHS = DAG.getBitcast(MVT::v4f16, OpLHS);
11259       }
11260     }
11261     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11262                               Input.getValueType().getVectorElementType(),
11263                               Input, DAG.getVectorIdxConstant(ExtLane, dl));
11264     SDValue Ins =
11265         DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Input.getValueType(), OpLHS,
11266                     Ext, DAG.getVectorIdxConstant(RHSID & 0x3, dl));
11267     return DAG.getBitcast(VT, Ins);
11268   }
11269 
11270   SDValue OpLHS, OpRHS;
11271   OpLHS = GeneratePerfectShuffle(LHSID, V1, V2, PerfectShuffleTable[LHSID], LHS,
11272                                  RHS, DAG, dl);
11273   OpRHS = GeneratePerfectShuffle(RHSID, V1, V2, PerfectShuffleTable[RHSID], LHS,
11274                                  RHS, DAG, dl);
11275   EVT VT = OpLHS.getValueType();
11276 
11277   switch (OpNum) {
11278   default:
11279     llvm_unreachable("Unknown shuffle opcode!");
11280   case OP_VREV:
11281     // VREV divides the vector in half and swaps within the half.
11282     if (VT.getVectorElementType() == MVT::i32 ||
11283         VT.getVectorElementType() == MVT::f32)
11284       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
11285     // vrev <4 x i16> -> REV32
11286     if (VT.getVectorElementType() == MVT::i16 ||
11287         VT.getVectorElementType() == MVT::f16 ||
11288         VT.getVectorElementType() == MVT::bf16)
11289       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
11290     // vrev <4 x i8> -> REV16
11291     assert(VT.getVectorElementType() == MVT::i8);
11292     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
11293   case OP_VDUP0:
11294   case OP_VDUP1:
11295   case OP_VDUP2:
11296   case OP_VDUP3: {
11297     EVT EltTy = VT.getVectorElementType();
11298     unsigned Opcode;
11299     if (EltTy == MVT::i8)
11300       Opcode = AArch64ISD::DUPLANE8;
11301     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
11302       Opcode = AArch64ISD::DUPLANE16;
11303     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
11304       Opcode = AArch64ISD::DUPLANE32;
11305     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
11306       Opcode = AArch64ISD::DUPLANE64;
11307     else
11308       llvm_unreachable("Invalid vector element type?");
11309 
11310     if (VT.getSizeInBits() == 64)
11311       OpLHS = WidenVector(OpLHS, DAG);
11312     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
11313     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
11314   }
11315   case OP_VEXT1:
11316   case OP_VEXT2:
11317   case OP_VEXT3: {
11318     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
11319     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
11320                        DAG.getConstant(Imm, dl, MVT::i32));
11321   }
11322   case OP_VUZPL:
11323     return DAG.getNode(AArch64ISD::UZP1, dl, VT, OpLHS, OpRHS);
11324   case OP_VUZPR:
11325     return DAG.getNode(AArch64ISD::UZP2, dl, VT, OpLHS, OpRHS);
11326   case OP_VZIPL:
11327     return DAG.getNode(AArch64ISD::ZIP1, dl, VT, OpLHS, OpRHS);
11328   case OP_VZIPR:
11329     return DAG.getNode(AArch64ISD::ZIP2, dl, VT, OpLHS, OpRHS);
11330   case OP_VTRNL:
11331     return DAG.getNode(AArch64ISD::TRN1, dl, VT, OpLHS, OpRHS);
11332   case OP_VTRNR:
11333     return DAG.getNode(AArch64ISD::TRN2, dl, VT, OpLHS, OpRHS);
11334   }
11335 }
11336 
11337 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
11338                            SelectionDAG &DAG) {
11339   // Check to see if we can use the TBL instruction.
11340   SDValue V1 = Op.getOperand(0);
11341   SDValue V2 = Op.getOperand(1);
11342   SDLoc DL(Op);
11343 
11344   EVT EltVT = Op.getValueType().getVectorElementType();
11345   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
11346 
11347   bool Swap = false;
11348   if (V1.isUndef() || isZerosVector(V1.getNode())) {
11349     std::swap(V1, V2);
11350     Swap = true;
11351   }
11352 
11353   // If the V2 source is undef or zero then we can use a tbl1, as tbl1 will fill
11354   // out of range values with 0s. We do need to make sure that any out-of-range
11355   // values are really out-of-range for a v16i8 vector.
11356   bool IsUndefOrZero = V2.isUndef() || isZerosVector(V2.getNode());
11357   MVT IndexVT = MVT::v8i8;
11358   unsigned IndexLen = 8;
11359   if (Op.getValueSizeInBits() == 128) {
11360     IndexVT = MVT::v16i8;
11361     IndexLen = 16;
11362   }
11363 
11364   SmallVector<SDValue, 8> TBLMask;
11365   for (int Val : ShuffleMask) {
11366     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
11367       unsigned Offset = Byte + Val * BytesPerElt;
11368       if (Swap)
11369         Offset = Offset < IndexLen ? Offset + IndexLen : Offset - IndexLen;
11370       if (IsUndefOrZero && Offset >= IndexLen)
11371         Offset = 255;
11372       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
11373     }
11374   }
11375 
11376   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
11377   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
11378 
11379   SDValue Shuffle;
11380   if (IsUndefOrZero) {
11381     if (IndexLen == 8)
11382       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
11383     Shuffle = DAG.getNode(
11384         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
11385         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
11386         DAG.getBuildVector(IndexVT, DL, ArrayRef(TBLMask.data(), IndexLen)));
11387   } else {
11388     if (IndexLen == 8) {
11389       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
11390       Shuffle = DAG.getNode(
11391           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
11392           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
11393           DAG.getBuildVector(IndexVT, DL, ArrayRef(TBLMask.data(), IndexLen)));
11394     } else {
11395       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
11396       // cannot currently represent the register constraints on the input
11397       // table registers.
11398       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
11399       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
11400       //                   IndexLen));
11401       Shuffle = DAG.getNode(
11402           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
11403           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
11404           V2Cst,
11405           DAG.getBuildVector(IndexVT, DL, ArrayRef(TBLMask.data(), IndexLen)));
11406     }
11407   }
11408   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
11409 }
11410 
11411 static unsigned getDUPLANEOp(EVT EltType) {
11412   if (EltType == MVT::i8)
11413     return AArch64ISD::DUPLANE8;
11414   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
11415     return AArch64ISD::DUPLANE16;
11416   if (EltType == MVT::i32 || EltType == MVT::f32)
11417     return AArch64ISD::DUPLANE32;
11418   if (EltType == MVT::i64 || EltType == MVT::f64)
11419     return AArch64ISD::DUPLANE64;
11420 
11421   llvm_unreachable("Invalid vector element type?");
11422 }
11423 
11424 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
11425                             unsigned Opcode, SelectionDAG &DAG) {
11426   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
11427   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
11428     // Match: dup (bitcast (extract_subv X, C)), LaneC
11429     if (BitCast.getOpcode() != ISD::BITCAST ||
11430         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
11431       return false;
11432 
11433     // The extract index must align in the destination type. That may not
11434     // happen if the bitcast is from narrow to wide type.
11435     SDValue Extract = BitCast.getOperand(0);
11436     unsigned ExtIdx = Extract.getConstantOperandVal(1);
11437     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
11438     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
11439     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
11440     if (ExtIdxInBits % CastedEltBitWidth != 0)
11441       return false;
11442 
11443     // Can't handle cases where vector size is not 128-bit
11444     if (!Extract.getOperand(0).getValueType().is128BitVector())
11445       return false;
11446 
11447     // Update the lane value by offsetting with the scaled extract index.
11448     LaneC += ExtIdxInBits / CastedEltBitWidth;
11449 
11450     // Determine the casted vector type of the wide vector input.
11451     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
11452     // Examples:
11453     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
11454     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
11455     unsigned SrcVecNumElts =
11456         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
11457     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
11458                               SrcVecNumElts);
11459     return true;
11460   };
11461   MVT CastVT;
11462   if (getScaledOffsetDup(V, Lane, CastVT)) {
11463     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
11464   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11465              V.getOperand(0).getValueType().is128BitVector()) {
11466     // The lane is incremented by the index of the extract.
11467     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
11468     Lane += V.getConstantOperandVal(1);
11469     V = V.getOperand(0);
11470   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
11471     // The lane is decremented if we are splatting from the 2nd operand.
11472     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
11473     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
11474     Lane -= Idx * VT.getVectorNumElements() / 2;
11475     V = WidenVector(V.getOperand(Idx), DAG);
11476   } else if (VT.getSizeInBits() == 64) {
11477     // Widen the operand to 128-bit register with undef.
11478     V = WidenVector(V, DAG);
11479   }
11480   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
11481 }
11482 
11483 // Return true if we can get a new shuffle mask by checking the parameter mask
11484 // array to test whether every two adjacent mask values are continuous and
11485 // starting from an even number.
11486 static bool isWideTypeMask(ArrayRef<int> M, EVT VT,
11487                            SmallVectorImpl<int> &NewMask) {
11488   unsigned NumElts = VT.getVectorNumElements();
11489   if (NumElts % 2 != 0)
11490     return false;
11491 
11492   NewMask.clear();
11493   for (unsigned i = 0; i < NumElts; i += 2) {
11494     int M0 = M[i];
11495     int M1 = M[i + 1];
11496 
11497     // If both elements are undef, new mask is undef too.
11498     if (M0 == -1 && M1 == -1) {
11499       NewMask.push_back(-1);
11500       continue;
11501     }
11502 
11503     if (M0 == -1 && M1 != -1 && (M1 % 2) == 1) {
11504       NewMask.push_back(M1 / 2);
11505       continue;
11506     }
11507 
11508     if (M0 != -1 && (M0 % 2) == 0 && ((M0 + 1) == M1 || M1 == -1)) {
11509       NewMask.push_back(M0 / 2);
11510       continue;
11511     }
11512 
11513     NewMask.clear();
11514     return false;
11515   }
11516 
11517   assert(NewMask.size() == NumElts / 2 && "Incorrect size for mask!");
11518   return true;
11519 }
11520 
11521 // Try to widen element type to get a new mask value for a better permutation
11522 // sequence, so that we can use NEON shuffle instructions, such as zip1/2,
11523 // UZP1/2, TRN1/2, REV, INS, etc.
11524 // For example:
11525 //  shufflevector <4 x i32> %a, <4 x i32> %b,
11526 //                <4 x i32> <i32 6, i32 7, i32 2, i32 3>
11527 // is equivalent to:
11528 //  shufflevector <2 x i64> %a, <2 x i64> %b, <2 x i32> <i32 3, i32 1>
11529 // Finally, we can get:
11530 //  mov     v0.d[0], v1.d[1]
11531 static SDValue tryWidenMaskForShuffle(SDValue Op, SelectionDAG &DAG) {
11532   SDLoc DL(Op);
11533   EVT VT = Op.getValueType();
11534   EVT ScalarVT = VT.getVectorElementType();
11535   unsigned ElementSize = ScalarVT.getFixedSizeInBits();
11536   SDValue V0 = Op.getOperand(0);
11537   SDValue V1 = Op.getOperand(1);
11538   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
11539 
11540   // If combining adjacent elements, like two i16's -> i32, two i32's -> i64 ...
11541   // We need to make sure the wider element type is legal. Thus, ElementSize
11542   // should be not larger than 32 bits, and i1 type should also be excluded.
11543   if (ElementSize > 32 || ElementSize == 1)
11544     return SDValue();
11545 
11546   SmallVector<int, 8> NewMask;
11547   if (isWideTypeMask(Mask, VT, NewMask)) {
11548     MVT NewEltVT = VT.isFloatingPoint()
11549                        ? MVT::getFloatingPointVT(ElementSize * 2)
11550                        : MVT::getIntegerVT(ElementSize * 2);
11551     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11552     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11553       V0 = DAG.getBitcast(NewVT, V0);
11554       V1 = DAG.getBitcast(NewVT, V1);
11555       return DAG.getBitcast(VT,
11556                             DAG.getVectorShuffle(NewVT, DL, V0, V1, NewMask));
11557     }
11558   }
11559 
11560   return SDValue();
11561 }
11562 
11563 // Try to fold shuffle (tbl2, tbl2) into a single tbl4.
11564 static SDValue tryToConvertShuffleOfTbl2ToTbl4(SDValue Op,
11565                                                ArrayRef<int> ShuffleMask,
11566                                                SelectionDAG &DAG) {
11567   SDValue Tbl1 = Op->getOperand(0);
11568   SDValue Tbl2 = Op->getOperand(1);
11569   SDLoc dl(Op);
11570   SDValue Tbl2ID =
11571       DAG.getTargetConstant(Intrinsic::aarch64_neon_tbl2, dl, MVT::i64);
11572 
11573   EVT VT = Op.getValueType();
11574   if (Tbl1->getOpcode() != ISD::INTRINSIC_WO_CHAIN ||
11575       Tbl1->getOperand(0) != Tbl2ID ||
11576       Tbl2->getOpcode() != ISD::INTRINSIC_WO_CHAIN ||
11577       Tbl2->getOperand(0) != Tbl2ID)
11578     return SDValue();
11579 
11580   if (Tbl1->getValueType(0) != MVT::v16i8 ||
11581       Tbl2->getValueType(0) != MVT::v16i8)
11582     return SDValue();
11583 
11584   SDValue Mask1 = Tbl1->getOperand(3);
11585   SDValue Mask2 = Tbl2->getOperand(3);
11586   SmallVector<SDValue, 16> TBLMaskParts(16, SDValue());
11587   for (unsigned I = 0; I < 16; I++) {
11588     if (ShuffleMask[I] < 16)
11589       TBLMaskParts[I] = Mask1->getOperand(ShuffleMask[I]);
11590     else {
11591       auto *C =
11592           dyn_cast<ConstantSDNode>(Mask2->getOperand(ShuffleMask[I] - 16));
11593       if (!C)
11594         return SDValue();
11595       TBLMaskParts[I] = DAG.getConstant(C->getSExtValue() + 32, dl, MVT::i32);
11596     }
11597   }
11598 
11599   SDValue TBLMask = DAG.getBuildVector(VT, dl, TBLMaskParts);
11600   SDValue ID =
11601       DAG.getTargetConstant(Intrinsic::aarch64_neon_tbl4, dl, MVT::i64);
11602 
11603   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v16i8,
11604                      {ID, Tbl1->getOperand(1), Tbl1->getOperand(2),
11605                       Tbl2->getOperand(1), Tbl2->getOperand(2), TBLMask});
11606 }
11607 
11608 // Baseline legalization for ZERO_EXTEND_VECTOR_INREG will blend-in zeros,
11609 // but we don't have an appropriate instruction,
11610 // so custom-lower it as ZIP1-with-zeros.
11611 SDValue
11612 AArch64TargetLowering::LowerZERO_EXTEND_VECTOR_INREG(SDValue Op,
11613                                                      SelectionDAG &DAG) const {
11614   SDLoc dl(Op);
11615   EVT VT = Op.getValueType();
11616   SDValue SrcOp = Op.getOperand(0);
11617   EVT SrcVT = SrcOp.getValueType();
11618   assert(VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits() == 0 &&
11619          "Unexpected extension factor.");
11620   unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
11621   // FIXME: support multi-step zipping?
11622   if (Scale != 2)
11623     return SDValue();
11624   SDValue Zeros = DAG.getConstant(0, dl, SrcVT);
11625   return DAG.getBitcast(VT,
11626                         DAG.getNode(AArch64ISD::ZIP1, dl, SrcVT, SrcOp, Zeros));
11627 }
11628 
11629 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
11630                                                    SelectionDAG &DAG) const {
11631   SDLoc dl(Op);
11632   EVT VT = Op.getValueType();
11633 
11634   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
11635 
11636   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
11637     return LowerFixedLengthVECTOR_SHUFFLEToSVE(Op, DAG);
11638 
11639   // Convert shuffles that are directly supported on NEON to target-specific
11640   // DAG nodes, instead of keeping them as shuffles and matching them again
11641   // during code selection.  This is more efficient and avoids the possibility
11642   // of inconsistencies between legalization and selection.
11643   ArrayRef<int> ShuffleMask = SVN->getMask();
11644 
11645   SDValue V1 = Op.getOperand(0);
11646   SDValue V2 = Op.getOperand(1);
11647 
11648   assert(V1.getValueType() == VT && "Unexpected VECTOR_SHUFFLE type!");
11649   assert(ShuffleMask.size() == VT.getVectorNumElements() &&
11650          "Unexpected VECTOR_SHUFFLE mask size!");
11651 
11652   if (SDValue Res = tryToConvertShuffleOfTbl2ToTbl4(Op, ShuffleMask, DAG))
11653     return Res;
11654 
11655   if (SVN->isSplat()) {
11656     int Lane = SVN->getSplatIndex();
11657     // If this is undef splat, generate it via "just" vdup, if possible.
11658     if (Lane == -1)
11659       Lane = 0;
11660 
11661     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
11662       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
11663                          V1.getOperand(0));
11664     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
11665     // constant. If so, we can just reference the lane's definition directly.
11666     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
11667         !isa<ConstantSDNode>(V1.getOperand(Lane)))
11668       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
11669 
11670     // Otherwise, duplicate from the lane of the input vector.
11671     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
11672     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
11673   }
11674 
11675   // Check if the mask matches a DUP for a wider element
11676   for (unsigned LaneSize : {64U, 32U, 16U}) {
11677     unsigned Lane = 0;
11678     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
11679       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
11680                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
11681                                                         : AArch64ISD::DUPLANE16;
11682       // Cast V1 to an integer vector with required lane size
11683       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
11684       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
11685       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
11686       V1 = DAG.getBitcast(NewVecTy, V1);
11687       // Constuct the DUP instruction
11688       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
11689       // Cast back to the original type
11690       return DAG.getBitcast(VT, V1);
11691     }
11692   }
11693 
11694   if (isREVMask(ShuffleMask, VT, 64))
11695     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
11696   if (isREVMask(ShuffleMask, VT, 32))
11697     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
11698   if (isREVMask(ShuffleMask, VT, 16))
11699     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
11700 
11701   if (((VT.getVectorNumElements() == 8 && VT.getScalarSizeInBits() == 16) ||
11702        (VT.getVectorNumElements() == 16 && VT.getScalarSizeInBits() == 8)) &&
11703       ShuffleVectorInst::isReverseMask(ShuffleMask)) {
11704     SDValue Rev = DAG.getNode(AArch64ISD::REV64, dl, VT, V1);
11705     return DAG.getNode(AArch64ISD::EXT, dl, VT, Rev, Rev,
11706                        DAG.getConstant(8, dl, MVT::i32));
11707   }
11708 
11709   bool ReverseEXT = false;
11710   unsigned Imm;
11711   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
11712     if (ReverseEXT)
11713       std::swap(V1, V2);
11714     Imm *= getExtFactor(V1);
11715     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
11716                        DAG.getConstant(Imm, dl, MVT::i32));
11717   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
11718     Imm *= getExtFactor(V1);
11719     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
11720                        DAG.getConstant(Imm, dl, MVT::i32));
11721   }
11722 
11723   unsigned WhichResult;
11724   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
11725     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
11726     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
11727   }
11728   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
11729     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
11730     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
11731   }
11732   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
11733     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
11734     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
11735   }
11736 
11737   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
11738     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
11739     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
11740   }
11741   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
11742     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
11743     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
11744   }
11745   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
11746     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
11747     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
11748   }
11749 
11750   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
11751     return Concat;
11752 
11753   bool DstIsLeft;
11754   int Anomaly;
11755   int NumInputElements = V1.getValueType().getVectorNumElements();
11756   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
11757     SDValue DstVec = DstIsLeft ? V1 : V2;
11758     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
11759 
11760     SDValue SrcVec = V1;
11761     int SrcLane = ShuffleMask[Anomaly];
11762     if (SrcLane >= NumInputElements) {
11763       SrcVec = V2;
11764       SrcLane -= VT.getVectorNumElements();
11765     }
11766     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
11767 
11768     EVT ScalarVT = VT.getVectorElementType();
11769 
11770     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
11771       ScalarVT = MVT::i32;
11772 
11773     return DAG.getNode(
11774         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
11775         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
11776         DstLaneV);
11777   }
11778 
11779   if (SDValue NewSD = tryWidenMaskForShuffle(Op, DAG))
11780     return NewSD;
11781 
11782   // If the shuffle is not directly supported and it has 4 elements, use
11783   // the PerfectShuffle-generated table to synthesize it from other shuffles.
11784   unsigned NumElts = VT.getVectorNumElements();
11785   if (NumElts == 4) {
11786     unsigned PFIndexes[4];
11787     for (unsigned i = 0; i != 4; ++i) {
11788       if (ShuffleMask[i] < 0)
11789         PFIndexes[i] = 8;
11790       else
11791         PFIndexes[i] = ShuffleMask[i];
11792     }
11793 
11794     // Compute the index in the perfect shuffle table.
11795     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
11796                             PFIndexes[2] * 9 + PFIndexes[3];
11797     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
11798     return GeneratePerfectShuffle(PFTableIndex, V1, V2, PFEntry, V1, V2, DAG,
11799                                   dl);
11800   }
11801 
11802   return GenerateTBL(Op, ShuffleMask, DAG);
11803 }
11804 
11805 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
11806                                                  SelectionDAG &DAG) const {
11807   EVT VT = Op.getValueType();
11808 
11809   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
11810     return LowerToScalableOp(Op, DAG);
11811 
11812   assert(VT.isScalableVector() && VT.getVectorElementType() == MVT::i1 &&
11813          "Unexpected vector type!");
11814 
11815   // We can handle the constant cases during isel.
11816   if (isa<ConstantSDNode>(Op.getOperand(0)))
11817     return Op;
11818 
11819   // There isn't a natural way to handle the general i1 case, so we use some
11820   // trickery with whilelo.
11821   SDLoc DL(Op);
11822   SDValue SplatVal = DAG.getAnyExtOrTrunc(Op.getOperand(0), DL, MVT::i64);
11823   SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, SplatVal,
11824                          DAG.getValueType(MVT::i1));
11825   SDValue ID =
11826       DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, DL, MVT::i64);
11827   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11828   if (VT == MVT::nxv1i1)
11829     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::nxv1i1,
11830                        DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::nxv2i1, ID,
11831                                    Zero, SplatVal),
11832                        Zero);
11833   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, ID, Zero, SplatVal);
11834 }
11835 
11836 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
11837                                              SelectionDAG &DAG) const {
11838   SDLoc DL(Op);
11839 
11840   EVT VT = Op.getValueType();
11841   if (!isTypeLegal(VT) || !VT.isScalableVector())
11842     return SDValue();
11843 
11844   // Current lowering only supports the SVE-ACLE types.
11845   if (VT.getSizeInBits().getKnownMinValue() != AArch64::SVEBitsPerBlock)
11846     return SDValue();
11847 
11848   // The DUPQ operation is indepedent of element type so normalise to i64s.
11849   SDValue Idx128 = Op.getOperand(2);
11850 
11851   // DUPQ can be used when idx is in range.
11852   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
11853   if (CIdx && (CIdx->getZExtValue() <= 3)) {
11854     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
11855     return DAG.getNode(AArch64ISD::DUPLANE128, DL, VT, Op.getOperand(1), CI);
11856   }
11857 
11858   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
11859 
11860   // The ACLE says this must produce the same result as:
11861   //   svtbl(data, svadd_x(svptrue_b64(),
11862   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
11863   //                       index * 2))
11864   SDValue One = DAG.getConstant(1, DL, MVT::i64);
11865   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
11866 
11867   // create the vector 0,1,0,1,...
11868   SDValue SV = DAG.getStepVector(DL, MVT::nxv2i64);
11869   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
11870 
11871   // create the vector idx64,idx64+1,idx64,idx64+1,...
11872   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
11873   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
11874   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
11875 
11876   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
11877   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
11878   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
11879 }
11880 
11881 
11882 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
11883                                APInt &UndefBits) {
11884   EVT VT = BVN->getValueType(0);
11885   APInt SplatBits, SplatUndef;
11886   unsigned SplatBitSize;
11887   bool HasAnyUndefs;
11888   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11889     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
11890 
11891     for (unsigned i = 0; i < NumSplats; ++i) {
11892       CnstBits <<= SplatBitSize;
11893       UndefBits <<= SplatBitSize;
11894       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
11895       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
11896     }
11897 
11898     return true;
11899   }
11900 
11901   return false;
11902 }
11903 
11904 // Try 64-bit splatted SIMD immediate.
11905 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
11906                                  const APInt &Bits) {
11907   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
11908     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
11909     EVT VT = Op.getValueType();
11910     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
11911 
11912     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
11913       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
11914 
11915       SDLoc dl(Op);
11916       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
11917                                 DAG.getConstant(Value, dl, MVT::i32));
11918       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
11919     }
11920   }
11921 
11922   return SDValue();
11923 }
11924 
11925 // Try 32-bit splatted SIMD immediate.
11926 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
11927                                   const APInt &Bits,
11928                                   const SDValue *LHS = nullptr) {
11929   EVT VT = Op.getValueType();
11930   if (VT.isFixedLengthVector() &&
11931       !DAG.getSubtarget<AArch64Subtarget>().isNeonAvailable())
11932     return SDValue();
11933 
11934   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
11935     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
11936     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
11937     bool isAdvSIMDModImm = false;
11938     uint64_t Shift;
11939 
11940     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
11941       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
11942       Shift = 0;
11943     }
11944     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
11945       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
11946       Shift = 8;
11947     }
11948     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
11949       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
11950       Shift = 16;
11951     }
11952     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
11953       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
11954       Shift = 24;
11955     }
11956 
11957     if (isAdvSIMDModImm) {
11958       SDLoc dl(Op);
11959       SDValue Mov;
11960 
11961       if (LHS)
11962         Mov = DAG.getNode(NewOp, dl, MovTy,
11963                           DAG.getNode(AArch64ISD::NVCAST, dl, MovTy, *LHS),
11964                           DAG.getConstant(Value, dl, MVT::i32),
11965                           DAG.getConstant(Shift, dl, MVT::i32));
11966       else
11967         Mov = DAG.getNode(NewOp, dl, MovTy,
11968                           DAG.getConstant(Value, dl, MVT::i32),
11969                           DAG.getConstant(Shift, dl, MVT::i32));
11970 
11971       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
11972     }
11973   }
11974 
11975   return SDValue();
11976 }
11977 
11978 // Try 16-bit splatted SIMD immediate.
11979 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
11980                                   const APInt &Bits,
11981                                   const SDValue *LHS = nullptr) {
11982   EVT VT = Op.getValueType();
11983   if (VT.isFixedLengthVector() &&
11984       !DAG.getSubtarget<AArch64Subtarget>().isNeonAvailable())
11985     return SDValue();
11986 
11987   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
11988     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
11989     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
11990     bool isAdvSIMDModImm = false;
11991     uint64_t Shift;
11992 
11993     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
11994       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
11995       Shift = 0;
11996     }
11997     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
11998       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
11999       Shift = 8;
12000     }
12001 
12002     if (isAdvSIMDModImm) {
12003       SDLoc dl(Op);
12004       SDValue Mov;
12005 
12006       if (LHS)
12007         Mov = DAG.getNode(NewOp, dl, MovTy,
12008                           DAG.getNode(AArch64ISD::NVCAST, dl, MovTy, *LHS),
12009                           DAG.getConstant(Value, dl, MVT::i32),
12010                           DAG.getConstant(Shift, dl, MVT::i32));
12011       else
12012         Mov = DAG.getNode(NewOp, dl, MovTy,
12013                           DAG.getConstant(Value, dl, MVT::i32),
12014                           DAG.getConstant(Shift, dl, MVT::i32));
12015 
12016       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
12017     }
12018   }
12019 
12020   return SDValue();
12021 }
12022 
12023 // Try 32-bit splatted SIMD immediate with shifted ones.
12024 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
12025                                     SelectionDAG &DAG, const APInt &Bits) {
12026   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
12027     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
12028     EVT VT = Op.getValueType();
12029     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
12030     bool isAdvSIMDModImm = false;
12031     uint64_t Shift;
12032 
12033     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
12034       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
12035       Shift = 264;
12036     }
12037     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
12038       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
12039       Shift = 272;
12040     }
12041 
12042     if (isAdvSIMDModImm) {
12043       SDLoc dl(Op);
12044       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
12045                                 DAG.getConstant(Value, dl, MVT::i32),
12046                                 DAG.getConstant(Shift, dl, MVT::i32));
12047       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
12048     }
12049   }
12050 
12051   return SDValue();
12052 }
12053 
12054 // Try 8-bit splatted SIMD immediate.
12055 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
12056                                  const APInt &Bits) {
12057   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
12058     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
12059     EVT VT = Op.getValueType();
12060     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
12061 
12062     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
12063       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
12064 
12065       SDLoc dl(Op);
12066       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
12067                                 DAG.getConstant(Value, dl, MVT::i32));
12068       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
12069     }
12070   }
12071 
12072   return SDValue();
12073 }
12074 
12075 // Try FP splatted SIMD immediate.
12076 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
12077                                   const APInt &Bits) {
12078   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
12079     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
12080     EVT VT = Op.getValueType();
12081     bool isWide = (VT.getSizeInBits() == 128);
12082     MVT MovTy;
12083     bool isAdvSIMDModImm = false;
12084 
12085     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
12086       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
12087       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
12088     }
12089     else if (isWide &&
12090              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
12091       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
12092       MovTy = MVT::v2f64;
12093     }
12094 
12095     if (isAdvSIMDModImm) {
12096       SDLoc dl(Op);
12097       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
12098                                 DAG.getConstant(Value, dl, MVT::i32));
12099       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
12100     }
12101   }
12102 
12103   return SDValue();
12104 }
12105 
12106 // Specialized code to quickly find if PotentialBVec is a BuildVector that
12107 // consists of only the same constant int value, returned in reference arg
12108 // ConstVal
12109 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
12110                                      uint64_t &ConstVal) {
12111   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
12112   if (!Bvec)
12113     return false;
12114   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
12115   if (!FirstElt)
12116     return false;
12117   EVT VT = Bvec->getValueType(0);
12118   unsigned NumElts = VT.getVectorNumElements();
12119   for (unsigned i = 1; i < NumElts; ++i)
12120     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
12121       return false;
12122   ConstVal = FirstElt->getZExtValue();
12123   return true;
12124 }
12125 
12126 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
12127 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
12128 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
12129 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
12130 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
12131 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
12132 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
12133   EVT VT = N->getValueType(0);
12134 
12135   if (!VT.isVector())
12136     return SDValue();
12137 
12138   SDLoc DL(N);
12139 
12140   SDValue And;
12141   SDValue Shift;
12142 
12143   SDValue FirstOp = N->getOperand(0);
12144   unsigned FirstOpc = FirstOp.getOpcode();
12145   SDValue SecondOp = N->getOperand(1);
12146   unsigned SecondOpc = SecondOp.getOpcode();
12147 
12148   // Is one of the operands an AND or a BICi? The AND may have been optimised to
12149   // a BICi in order to use an immediate instead of a register.
12150   // Is the other operand an shl or lshr? This will have been turned into:
12151   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
12152   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
12153       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
12154     And = FirstOp;
12155     Shift = SecondOp;
12156 
12157   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
12158              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
12159     And = SecondOp;
12160     Shift = FirstOp;
12161   } else
12162     return SDValue();
12163 
12164   bool IsAnd = And.getOpcode() == ISD::AND;
12165   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
12166 
12167   // Is the shift amount constant?
12168   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
12169   if (!C2node)
12170     return SDValue();
12171 
12172   uint64_t C1;
12173   if (IsAnd) {
12174     // Is the and mask vector all constant?
12175     if (!isAllConstantBuildVector(And.getOperand(1), C1))
12176       return SDValue();
12177   } else {
12178     // Reconstruct the corresponding AND immediate from the two BICi immediates.
12179     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
12180     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
12181     assert(C1nodeImm && C1nodeShift);
12182     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
12183   }
12184 
12185   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
12186   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
12187   // how much one can shift elements of a particular size?
12188   uint64_t C2 = C2node->getZExtValue();
12189   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
12190   if (C2 > ElemSizeInBits)
12191     return SDValue();
12192 
12193   APInt C1AsAPInt(ElemSizeInBits, C1);
12194   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
12195                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
12196   if (C1AsAPInt != RequiredC1)
12197     return SDValue();
12198 
12199   SDValue X = And.getOperand(0);
12200   SDValue Y = Shift.getOperand(0);
12201 
12202   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
12203   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
12204 
12205   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
12206   LLVM_DEBUG(N->dump(&DAG));
12207   LLVM_DEBUG(dbgs() << "into: \n");
12208   LLVM_DEBUG(ResultSLI->dump(&DAG));
12209 
12210   ++NumShiftInserts;
12211   return ResultSLI;
12212 }
12213 
12214 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
12215                                              SelectionDAG &DAG) const {
12216   if (useSVEForFixedLengthVectorVT(Op.getValueType(),
12217                                    !Subtarget->isNeonAvailable()))
12218     return LowerToScalableOp(Op, DAG);
12219 
12220   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
12221   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
12222     return Res;
12223 
12224   EVT VT = Op.getValueType();
12225 
12226   SDValue LHS = Op.getOperand(0);
12227   BuildVectorSDNode *BVN =
12228       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
12229   if (!BVN) {
12230     // OR commutes, so try swapping the operands.
12231     LHS = Op.getOperand(1);
12232     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
12233   }
12234   if (!BVN)
12235     return Op;
12236 
12237   APInt DefBits(VT.getSizeInBits(), 0);
12238   APInt UndefBits(VT.getSizeInBits(), 0);
12239   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
12240     SDValue NewOp;
12241 
12242     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
12243                                     DefBits, &LHS)) ||
12244         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
12245                                     DefBits, &LHS)))
12246       return NewOp;
12247 
12248     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
12249                                     UndefBits, &LHS)) ||
12250         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
12251                                     UndefBits, &LHS)))
12252       return NewOp;
12253   }
12254 
12255   // We can always fall back to a non-immediate OR.
12256   return Op;
12257 }
12258 
12259 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
12260 // be truncated to fit element width.
12261 static SDValue NormalizeBuildVector(SDValue Op,
12262                                     SelectionDAG &DAG) {
12263   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
12264   SDLoc dl(Op);
12265   EVT VT = Op.getValueType();
12266   EVT EltTy= VT.getVectorElementType();
12267 
12268   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
12269     return Op;
12270 
12271   SmallVector<SDValue, 16> Ops;
12272   for (SDValue Lane : Op->ops()) {
12273     // For integer vectors, type legalization would have promoted the
12274     // operands already. Otherwise, if Op is a floating-point splat
12275     // (with operands cast to integers), then the only possibilities
12276     // are constants and UNDEFs.
12277     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
12278       APInt LowBits(EltTy.getSizeInBits(),
12279                     CstLane->getZExtValue());
12280       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
12281     } else if (Lane.getNode()->isUndef()) {
12282       Lane = DAG.getUNDEF(MVT::i32);
12283     } else {
12284       assert(Lane.getValueType() == MVT::i32 &&
12285              "Unexpected BUILD_VECTOR operand type");
12286     }
12287     Ops.push_back(Lane);
12288   }
12289   return DAG.getBuildVector(VT, dl, Ops);
12290 }
12291 
12292 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
12293   EVT VT = Op.getValueType();
12294 
12295   APInt DefBits(VT.getSizeInBits(), 0);
12296   APInt UndefBits(VT.getSizeInBits(), 0);
12297   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
12298   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
12299     SDValue NewOp;
12300     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
12301         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
12302         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
12303         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
12304         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
12305         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
12306       return NewOp;
12307 
12308     DefBits = ~DefBits;
12309     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
12310         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
12311         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
12312       return NewOp;
12313 
12314     DefBits = UndefBits;
12315     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
12316         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
12317         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
12318         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
12319         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
12320         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
12321       return NewOp;
12322 
12323     DefBits = ~UndefBits;
12324     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
12325         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
12326         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
12327       return NewOp;
12328   }
12329 
12330   return SDValue();
12331 }
12332 
12333 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
12334                                                  SelectionDAG &DAG) const {
12335   EVT VT = Op.getValueType();
12336 
12337   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable())) {
12338     if (auto SeqInfo = cast<BuildVectorSDNode>(Op)->isConstantSequence()) {
12339       SDLoc DL(Op);
12340       EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
12341       SDValue Start = DAG.getConstant(SeqInfo->first, DL, ContainerVT);
12342       SDValue Steps = DAG.getStepVector(DL, ContainerVT, SeqInfo->second);
12343       SDValue Seq = DAG.getNode(ISD::ADD, DL, ContainerVT, Start, Steps);
12344       return convertFromScalableVector(DAG, Op.getValueType(), Seq);
12345     }
12346 
12347     // Revert to common legalisation for all other variants.
12348     return SDValue();
12349   }
12350 
12351   // Try to build a simple constant vector.
12352   Op = NormalizeBuildVector(Op, DAG);
12353   // Thought this might return a non-BUILD_VECTOR (e.g. CONCAT_VECTORS), if so,
12354   // abort.
12355   if (Op.getOpcode() != ISD::BUILD_VECTOR)
12356     return SDValue();
12357 
12358   // Certain vector constants, used to express things like logical NOT and
12359   // arithmetic NEG, are passed through unmodified.  This allows special
12360   // patterns for these operations to match, which will lower these constants
12361   // to whatever is proven necessary.
12362   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
12363   if (BVN->isConstant()) {
12364     if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
12365       unsigned BitSize = VT.getVectorElementType().getSizeInBits();
12366       APInt Val(BitSize,
12367                 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
12368       if (Val.isZero() || (VT.isInteger() && Val.isAllOnes()))
12369         return Op;
12370     }
12371     if (ConstantFPSDNode *Const = BVN->getConstantFPSplatNode())
12372       if (Const->isZero() && !Const->isNegative())
12373         return Op;
12374   }
12375 
12376   if (SDValue V = ConstantBuildVector(Op, DAG))
12377     return V;
12378 
12379   // Scan through the operands to find some interesting properties we can
12380   // exploit:
12381   //   1) If only one value is used, we can use a DUP, or
12382   //   2) if only the low element is not undef, we can just insert that, or
12383   //   3) if only one constant value is used (w/ some non-constant lanes),
12384   //      we can splat the constant value into the whole vector then fill
12385   //      in the non-constant lanes.
12386   //   4) FIXME: If different constant values are used, but we can intelligently
12387   //             select the values we'll be overwriting for the non-constant
12388   //             lanes such that we can directly materialize the vector
12389   //             some other way (MOVI, e.g.), we can be sneaky.
12390   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
12391   SDLoc dl(Op);
12392   unsigned NumElts = VT.getVectorNumElements();
12393   bool isOnlyLowElement = true;
12394   bool usesOnlyOneValue = true;
12395   bool usesOnlyOneConstantValue = true;
12396   bool isConstant = true;
12397   bool AllLanesExtractElt = true;
12398   unsigned NumConstantLanes = 0;
12399   unsigned NumDifferentLanes = 0;
12400   unsigned NumUndefLanes = 0;
12401   SDValue Value;
12402   SDValue ConstantValue;
12403   SmallMapVector<SDValue, unsigned, 16> DifferentValueMap;
12404   unsigned ConsecutiveValCount = 0;
12405   SDValue PrevVal;
12406   for (unsigned i = 0; i < NumElts; ++i) {
12407     SDValue V = Op.getOperand(i);
12408     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12409       AllLanesExtractElt = false;
12410     if (V.isUndef()) {
12411       ++NumUndefLanes;
12412       continue;
12413     }
12414     if (i > 0)
12415       isOnlyLowElement = false;
12416     if (!isIntOrFPConstant(V))
12417       isConstant = false;
12418 
12419     if (isIntOrFPConstant(V)) {
12420       ++NumConstantLanes;
12421       if (!ConstantValue.getNode())
12422         ConstantValue = V;
12423       else if (ConstantValue != V)
12424         usesOnlyOneConstantValue = false;
12425     }
12426 
12427     if (!Value.getNode())
12428       Value = V;
12429     else if (V != Value) {
12430       usesOnlyOneValue = false;
12431       ++NumDifferentLanes;
12432     }
12433 
12434     if (PrevVal != V) {
12435       ConsecutiveValCount = 0;
12436       PrevVal = V;
12437     }
12438 
12439     // Keep different values and its last consecutive count. For example,
12440     //
12441     //  t22: v16i8 = build_vector t23, t23, t23, t23, t23, t23, t23, t23,
12442     //                            t24, t24, t24, t24, t24, t24, t24, t24
12443     //  t23 = consecutive count 8
12444     //  t24 = consecutive count 8
12445     // ------------------------------------------------------------------
12446     //  t22: v16i8 = build_vector t24, t24, t23, t23, t23, t23, t23, t24,
12447     //                            t24, t24, t24, t24, t24, t24, t24, t24
12448     //  t23 = consecutive count 5
12449     //  t24 = consecutive count 9
12450     DifferentValueMap[V] = ++ConsecutiveValCount;
12451   }
12452 
12453   if (!Value.getNode()) {
12454     LLVM_DEBUG(
12455         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
12456     return DAG.getUNDEF(VT);
12457   }
12458 
12459   // Convert BUILD_VECTOR where all elements but the lowest are undef into
12460   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
12461   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
12462   if (isOnlyLowElement && !(NumElts == 1 && isIntOrFPConstant(Value))) {
12463     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
12464                          "SCALAR_TO_VECTOR node\n");
12465     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
12466   }
12467 
12468   if (AllLanesExtractElt) {
12469     SDNode *Vector = nullptr;
12470     bool Even = false;
12471     bool Odd = false;
12472     // Check whether the extract elements match the Even pattern <0,2,4,...> or
12473     // the Odd pattern <1,3,5,...>.
12474     for (unsigned i = 0; i < NumElts; ++i) {
12475       SDValue V = Op.getOperand(i);
12476       const SDNode *N = V.getNode();
12477       if (!isa<ConstantSDNode>(N->getOperand(1))) {
12478         Even = false;
12479         Odd = false;
12480         break;
12481       }
12482       SDValue N0 = N->getOperand(0);
12483 
12484       // All elements are extracted from the same vector.
12485       if (!Vector) {
12486         Vector = N0.getNode();
12487         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
12488         // BUILD_VECTOR.
12489         if (VT.getVectorElementType() !=
12490             N0.getValueType().getVectorElementType())
12491           break;
12492       } else if (Vector != N0.getNode()) {
12493         Odd = false;
12494         Even = false;
12495         break;
12496       }
12497 
12498       // Extracted values are either at Even indices <0,2,4,...> or at Odd
12499       // indices <1,3,5,...>.
12500       uint64_t Val = N->getConstantOperandVal(1);
12501       if (Val == 2 * i) {
12502         Even = true;
12503         continue;
12504       }
12505       if (Val - 1 == 2 * i) {
12506         Odd = true;
12507         continue;
12508       }
12509 
12510       // Something does not match: abort.
12511       Odd = false;
12512       Even = false;
12513       break;
12514     }
12515     if (Even || Odd) {
12516       SDValue LHS =
12517           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
12518                       DAG.getConstant(0, dl, MVT::i64));
12519       SDValue RHS =
12520           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
12521                       DAG.getConstant(NumElts, dl, MVT::i64));
12522 
12523       if (Even && !Odd)
12524         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
12525                            RHS);
12526       if (Odd && !Even)
12527         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
12528                            RHS);
12529     }
12530   }
12531 
12532   // Use DUP for non-constant splats. For f32 constant splats, reduce to
12533   // i32 and try again.
12534   if (usesOnlyOneValue) {
12535     if (!isConstant) {
12536       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12537           Value.getValueType() != VT) {
12538         LLVM_DEBUG(
12539             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
12540         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
12541       }
12542 
12543       // This is actually a DUPLANExx operation, which keeps everything vectory.
12544 
12545       SDValue Lane = Value.getOperand(1);
12546       Value = Value.getOperand(0);
12547       if (Value.getValueSizeInBits() == 64) {
12548         LLVM_DEBUG(
12549             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
12550                       "widening it\n");
12551         Value = WidenVector(Value, DAG);
12552       }
12553 
12554       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
12555       return DAG.getNode(Opcode, dl, VT, Value, Lane);
12556     }
12557 
12558     if (VT.getVectorElementType().isFloatingPoint()) {
12559       SmallVector<SDValue, 8> Ops;
12560       EVT EltTy = VT.getVectorElementType();
12561       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
12562                EltTy == MVT::f64) && "Unsupported floating-point vector type");
12563       LLVM_DEBUG(
12564           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
12565                     "BITCASTS, and try again\n");
12566       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
12567       for (unsigned i = 0; i < NumElts; ++i)
12568         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
12569       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
12570       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
12571       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
12572                  Val.dump(););
12573       Val = LowerBUILD_VECTOR(Val, DAG);
12574       if (Val.getNode())
12575         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
12576     }
12577   }
12578 
12579   // If we need to insert a small number of different non-constant elements and
12580   // the vector width is sufficiently large, prefer using DUP with the common
12581   // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
12582   // skip the constant lane handling below.
12583   bool PreferDUPAndInsert =
12584       !isConstant && NumDifferentLanes >= 1 &&
12585       NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
12586       NumDifferentLanes >= NumConstantLanes;
12587 
12588   // If there was only one constant value used and for more than one lane,
12589   // start by splatting that value, then replace the non-constant lanes. This
12590   // is better than the default, which will perform a separate initialization
12591   // for each lane.
12592   if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
12593     // Firstly, try to materialize the splat constant.
12594     SDValue Val = DAG.getSplatBuildVector(VT, dl, ConstantValue);
12595     unsigned BitSize = VT.getScalarSizeInBits();
12596     APInt ConstantValueAPInt(1, 0);
12597     if (auto *C = dyn_cast<ConstantSDNode>(ConstantValue))
12598       ConstantValueAPInt = C->getAPIntValue().zextOrTrunc(BitSize);
12599     if (!isNullConstant(ConstantValue) && !isNullFPConstant(ConstantValue) &&
12600         !ConstantValueAPInt.isAllOnes()) {
12601       Val = ConstantBuildVector(Val, DAG);
12602       if (!Val)
12603         // Otherwise, materialize the constant and splat it.
12604         Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
12605     }
12606 
12607     // Now insert the non-constant lanes.
12608     for (unsigned i = 0; i < NumElts; ++i) {
12609       SDValue V = Op.getOperand(i);
12610       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
12611       if (!isIntOrFPConstant(V))
12612         // Note that type legalization likely mucked about with the VT of the
12613         // source operand, so we may have to convert it here before inserting.
12614         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
12615     }
12616     return Val;
12617   }
12618 
12619   // This will generate a load from the constant pool.
12620   if (isConstant) {
12621     LLVM_DEBUG(
12622         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
12623                   "expansion\n");
12624     return SDValue();
12625   }
12626 
12627   // Detect patterns of a0,a1,a2,a3,b0,b1,b2,b3,c0,c1,c2,c3,d0,d1,d2,d3 from
12628   // v4i32s. This is really a truncate, which we can construct out of (legal)
12629   // concats and truncate nodes.
12630   if (SDValue M = ReconstructTruncateFromBuildVector(Op, DAG))
12631     return M;
12632 
12633   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
12634   if (NumElts >= 4) {
12635     if (SDValue Shuffle = ReconstructShuffle(Op, DAG))
12636       return Shuffle;
12637 
12638     if (SDValue Shuffle = ReconstructShuffleWithRuntimeMask(Op, DAG))
12639       return Shuffle;
12640   }
12641 
12642   if (PreferDUPAndInsert) {
12643     // First, build a constant vector with the common element.
12644     SmallVector<SDValue, 8> Ops(NumElts, Value);
12645     SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
12646     // Next, insert the elements that do not match the common value.
12647     for (unsigned I = 0; I < NumElts; ++I)
12648       if (Op.getOperand(I) != Value)
12649         NewVector =
12650             DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
12651                         Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
12652 
12653     return NewVector;
12654   }
12655 
12656   // If vector consists of two different values, try to generate two DUPs and
12657   // (CONCAT_VECTORS or VECTOR_SHUFFLE).
12658   if (DifferentValueMap.size() == 2 && NumUndefLanes == 0) {
12659     SmallVector<SDValue, 2> Vals;
12660     // Check the consecutive count of the value is the half number of vector
12661     // elements. In this case, we can use CONCAT_VECTORS. For example,
12662     //
12663     // canUseVECTOR_CONCAT = true;
12664     //  t22: v16i8 = build_vector t23, t23, t23, t23, t23, t23, t23, t23,
12665     //                            t24, t24, t24, t24, t24, t24, t24, t24
12666     //
12667     // canUseVECTOR_CONCAT = false;
12668     //  t22: v16i8 = build_vector t23, t23, t23, t23, t23, t24, t24, t24,
12669     //                            t24, t24, t24, t24, t24, t24, t24, t24
12670     bool canUseVECTOR_CONCAT = true;
12671     for (auto Pair : DifferentValueMap) {
12672       // Check different values have same length which is NumElts / 2.
12673       if (Pair.second != NumElts / 2)
12674         canUseVECTOR_CONCAT = false;
12675       Vals.push_back(Pair.first);
12676     }
12677 
12678     // If canUseVECTOR_CONCAT is true, we can generate two DUPs and
12679     // CONCAT_VECTORs. For example,
12680     //
12681     //  t22: v16i8 = BUILD_VECTOR t23, t23, t23, t23, t23, t23, t23, t23,
12682     //                            t24, t24, t24, t24, t24, t24, t24, t24
12683     // ==>
12684     //    t26: v8i8 = AArch64ISD::DUP t23
12685     //    t28: v8i8 = AArch64ISD::DUP t24
12686     //  t29: v16i8 = concat_vectors t26, t28
12687     if (canUseVECTOR_CONCAT) {
12688       EVT SubVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
12689       if (isTypeLegal(SubVT) && SubVT.isVector() &&
12690           SubVT.getVectorNumElements() >= 2) {
12691         SmallVector<SDValue, 8> Ops1(NumElts / 2, Vals[0]);
12692         SmallVector<SDValue, 8> Ops2(NumElts / 2, Vals[1]);
12693         SDValue DUP1 =
12694             LowerBUILD_VECTOR(DAG.getBuildVector(SubVT, dl, Ops1), DAG);
12695         SDValue DUP2 =
12696             LowerBUILD_VECTOR(DAG.getBuildVector(SubVT, dl, Ops2), DAG);
12697         SDValue CONCAT_VECTORS =
12698             DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, DUP1, DUP2);
12699         return CONCAT_VECTORS;
12700       }
12701     }
12702 
12703     // Let's try to generate VECTOR_SHUFFLE. For example,
12704     //
12705     //  t24: v8i8 = BUILD_VECTOR t25, t25, t25, t25, t26, t26, t26, t26
12706     //  ==>
12707     //    t27: v8i8 = BUILD_VECTOR t26, t26, t26, t26, t26, t26, t26, t26
12708     //    t28: v8i8 = BUILD_VECTOR t25, t25, t25, t25, t25, t25, t25, t25
12709     //  t29: v8i8 = vector_shuffle<0,1,2,3,12,13,14,15> t27, t28
12710     if (NumElts >= 8) {
12711       SmallVector<int, 16> MaskVec;
12712       // Build mask for VECTOR_SHUFLLE.
12713       SDValue FirstLaneVal = Op.getOperand(0);
12714       for (unsigned i = 0; i < NumElts; ++i) {
12715         SDValue Val = Op.getOperand(i);
12716         if (FirstLaneVal == Val)
12717           MaskVec.push_back(i);
12718         else
12719           MaskVec.push_back(i + NumElts);
12720       }
12721 
12722       SmallVector<SDValue, 8> Ops1(NumElts, Vals[0]);
12723       SmallVector<SDValue, 8> Ops2(NumElts, Vals[1]);
12724       SDValue VEC1 = DAG.getBuildVector(VT, dl, Ops1);
12725       SDValue VEC2 = DAG.getBuildVector(VT, dl, Ops2);
12726       SDValue VECTOR_SHUFFLE =
12727           DAG.getVectorShuffle(VT, dl, VEC1, VEC2, MaskVec);
12728       return VECTOR_SHUFFLE;
12729     }
12730   }
12731 
12732   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
12733   // know the default expansion would otherwise fall back on something even
12734   // worse. For a vector with one or two non-undef values, that's
12735   // scalar_to_vector for the elements followed by a shuffle (provided the
12736   // shuffle is valid for the target) and materialization element by element
12737   // on the stack followed by a load for everything else.
12738   if (!isConstant && !usesOnlyOneValue) {
12739     LLVM_DEBUG(
12740         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
12741                   "of INSERT_VECTOR_ELT\n");
12742 
12743     SDValue Vec = DAG.getUNDEF(VT);
12744     SDValue Op0 = Op.getOperand(0);
12745     unsigned i = 0;
12746 
12747     // Use SCALAR_TO_VECTOR for lane zero to
12748     // a) Avoid a RMW dependency on the full vector register, and
12749     // b) Allow the register coalescer to fold away the copy if the
12750     //    value is already in an S or D register, and we're forced to emit an
12751     //    INSERT_SUBREG that we can't fold anywhere.
12752     //
12753     // We also allow types like i8 and i16 which are illegal scalar but legal
12754     // vector element types. After type-legalization the inserted value is
12755     // extended (i32) and it is safe to cast them to the vector type by ignoring
12756     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
12757     if (!Op0.isUndef()) {
12758       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
12759       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
12760       ++i;
12761     }
12762     LLVM_DEBUG(if (i < NumElts) dbgs()
12763                    << "Creating nodes for the other vector elements:\n";);
12764     for (; i < NumElts; ++i) {
12765       SDValue V = Op.getOperand(i);
12766       if (V.isUndef())
12767         continue;
12768       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
12769       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
12770     }
12771     return Vec;
12772   }
12773 
12774   LLVM_DEBUG(
12775       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
12776                 "better alternative\n");
12777   return SDValue();
12778 }
12779 
12780 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
12781                                                    SelectionDAG &DAG) const {
12782   if (useSVEForFixedLengthVectorVT(Op.getValueType(),
12783                                    !Subtarget->isNeonAvailable()))
12784     return LowerFixedLengthConcatVectorsToSVE(Op, DAG);
12785 
12786   assert(Op.getValueType().isScalableVector() &&
12787          isTypeLegal(Op.getValueType()) &&
12788          "Expected legal scalable vector type!");
12789 
12790   if (isTypeLegal(Op.getOperand(0).getValueType())) {
12791     unsigned NumOperands = Op->getNumOperands();
12792     assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
12793            "Unexpected number of operands in CONCAT_VECTORS");
12794 
12795     if (NumOperands == 2)
12796       return Op;
12797 
12798     // Concat each pair of subvectors and pack into the lower half of the array.
12799     SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
12800     while (ConcatOps.size() > 1) {
12801       for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
12802         SDValue V1 = ConcatOps[I];
12803         SDValue V2 = ConcatOps[I + 1];
12804         EVT SubVT = V1.getValueType();
12805         EVT PairVT = SubVT.getDoubleNumVectorElementsVT(*DAG.getContext());
12806         ConcatOps[I / 2] =
12807             DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), PairVT, V1, V2);
12808       }
12809       ConcatOps.resize(ConcatOps.size() / 2);
12810     }
12811     return ConcatOps[0];
12812   }
12813 
12814   return SDValue();
12815 }
12816 
12817 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12818                                                       SelectionDAG &DAG) const {
12819   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
12820 
12821   if (useSVEForFixedLengthVectorVT(Op.getValueType(),
12822                                    !Subtarget->isNeonAvailable()))
12823     return LowerFixedLengthInsertVectorElt(Op, DAG);
12824 
12825   EVT VT = Op.getOperand(0).getValueType();
12826 
12827   if (VT.getScalarType() == MVT::i1) {
12828     EVT VectorVT = getPromotedVTForPredicate(VT);
12829     SDLoc DL(Op);
12830     SDValue ExtendedVector =
12831         DAG.getAnyExtOrTrunc(Op.getOperand(0), DL, VectorVT);
12832     SDValue ExtendedValue =
12833         DAG.getAnyExtOrTrunc(Op.getOperand(1), DL,
12834                              VectorVT.getScalarType().getSizeInBits() < 32
12835                                  ? MVT::i32
12836                                  : VectorVT.getScalarType());
12837     ExtendedVector =
12838         DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VectorVT, ExtendedVector,
12839                     ExtendedValue, Op.getOperand(2));
12840     return DAG.getAnyExtOrTrunc(ExtendedVector, DL, VT);
12841   }
12842 
12843   // Check for non-constant or out of range lane.
12844   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
12845   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
12846     return SDValue();
12847 
12848   return Op;
12849 }
12850 
12851 SDValue
12852 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12853                                                SelectionDAG &DAG) const {
12854   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
12855   EVT VT = Op.getOperand(0).getValueType();
12856 
12857   if (VT.getScalarType() == MVT::i1) {
12858     // We can't directly extract from an SVE predicate; extend it first.
12859     // (This isn't the only possible lowering, but it's straightforward.)
12860     EVT VectorVT = getPromotedVTForPredicate(VT);
12861     SDLoc DL(Op);
12862     SDValue Extend =
12863         DAG.getNode(ISD::ANY_EXTEND, DL, VectorVT, Op.getOperand(0));
12864     MVT ExtractTy = VectorVT == MVT::nxv2i64 ? MVT::i64 : MVT::i32;
12865     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractTy,
12866                                   Extend, Op.getOperand(1));
12867     return DAG.getAnyExtOrTrunc(Extract, DL, Op.getValueType());
12868   }
12869 
12870   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
12871     return LowerFixedLengthExtractVectorElt(Op, DAG);
12872 
12873   // Check for non-constant or out of range lane.
12874   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12875   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
12876     return SDValue();
12877 
12878   // Insertion/extraction are legal for V128 types.
12879   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
12880       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
12881       VT == MVT::v8f16 || VT == MVT::v8bf16)
12882     return Op;
12883 
12884   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
12885       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
12886       VT != MVT::v4bf16)
12887     return SDValue();
12888 
12889   // For V64 types, we perform extraction by expanding the value
12890   // to a V128 type and perform the extraction on that.
12891   SDLoc DL(Op);
12892   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
12893   EVT WideTy = WideVec.getValueType();
12894 
12895   EVT ExtrTy = WideTy.getVectorElementType();
12896   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
12897     ExtrTy = MVT::i32;
12898 
12899   // For extractions, we just return the result directly.
12900   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
12901                      Op.getOperand(1));
12902 }
12903 
12904 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
12905                                                       SelectionDAG &DAG) const {
12906   assert(Op.getValueType().isFixedLengthVector() &&
12907          "Only cases that extract a fixed length vector are supported!");
12908 
12909   EVT InVT = Op.getOperand(0).getValueType();
12910   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12911   unsigned Size = Op.getValueSizeInBits();
12912 
12913   // If we don't have legal types yet, do nothing
12914   if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
12915     return SDValue();
12916 
12917   if (InVT.isScalableVector()) {
12918     // This will be matched by custom code during ISelDAGToDAG.
12919     if (Idx == 0 && isPackedVectorType(InVT, DAG))
12920       return Op;
12921 
12922     return SDValue();
12923   }
12924 
12925   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
12926   if (Idx == 0 && InVT.getSizeInBits() <= 128)
12927     return Op;
12928 
12929   // If this is extracting the upper 64-bits of a 128-bit vector, we match
12930   // that directly.
12931   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
12932       InVT.getSizeInBits() == 128 && Subtarget->isNeonAvailable())
12933     return Op;
12934 
12935   if (useSVEForFixedLengthVectorVT(InVT, !Subtarget->isNeonAvailable())) {
12936     SDLoc DL(Op);
12937 
12938     EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
12939     SDValue NewInVec =
12940         convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
12941 
12942     SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ContainerVT, NewInVec,
12943                                  NewInVec, DAG.getConstant(Idx, DL, MVT::i64));
12944     return convertFromScalableVector(DAG, Op.getValueType(), Splice);
12945   }
12946 
12947   return SDValue();
12948 }
12949 
12950 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
12951                                                      SelectionDAG &DAG) const {
12952   assert(Op.getValueType().isScalableVector() &&
12953          "Only expect to lower inserts into scalable vectors!");
12954 
12955   EVT InVT = Op.getOperand(1).getValueType();
12956   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12957 
12958   SDValue Vec0 = Op.getOperand(0);
12959   SDValue Vec1 = Op.getOperand(1);
12960   SDLoc DL(Op);
12961   EVT VT = Op.getValueType();
12962 
12963   if (InVT.isScalableVector()) {
12964     if (!isTypeLegal(VT))
12965       return SDValue();
12966 
12967     // Break down insert_subvector into simpler parts.
12968     if (VT.getVectorElementType() == MVT::i1) {
12969       unsigned NumElts = VT.getVectorMinNumElements();
12970       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
12971 
12972       SDValue Lo, Hi;
12973       Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Vec0,
12974                        DAG.getVectorIdxConstant(0, DL));
12975       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Vec0,
12976                        DAG.getVectorIdxConstant(NumElts / 2, DL));
12977       if (Idx < (NumElts / 2)) {
12978         SDValue NewLo = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, HalfVT, Lo, Vec1,
12979                                     DAG.getVectorIdxConstant(Idx, DL));
12980         return DAG.getNode(AArch64ISD::UZP1, DL, VT, NewLo, Hi);
12981       } else {
12982         SDValue NewHi =
12983             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, HalfVT, Hi, Vec1,
12984                         DAG.getVectorIdxConstant(Idx - (NumElts / 2), DL));
12985         return DAG.getNode(AArch64ISD::UZP1, DL, VT, Lo, NewHi);
12986       }
12987     }
12988 
12989     // Ensure the subvector is half the size of the main vector.
12990     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
12991       return SDValue();
12992 
12993     // Here narrow and wide refers to the vector element types. After "casting"
12994     // both vectors must have the same bit length and so because the subvector
12995     // has fewer elements, those elements need to be bigger.
12996     EVT NarrowVT = getPackedSVEVectorVT(VT.getVectorElementCount());
12997     EVT WideVT = getPackedSVEVectorVT(InVT.getVectorElementCount());
12998 
12999     // NOP cast operands to the largest legal vector of the same element count.
13000     if (VT.isFloatingPoint()) {
13001       Vec0 = getSVESafeBitCast(NarrowVT, Vec0, DAG);
13002       Vec1 = getSVESafeBitCast(WideVT, Vec1, DAG);
13003     } else {
13004       // Legal integer vectors are already their largest so Vec0 is fine as is.
13005       Vec1 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
13006     }
13007 
13008     // To replace the top/bottom half of vector V with vector SubV we widen the
13009     // preserved half of V, concatenate this to SubV (the order depending on the
13010     // half being replaced) and then narrow the result.
13011     SDValue Narrow;
13012     if (Idx == 0) {
13013       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
13014       Narrow = DAG.getNode(AArch64ISD::UZP1, DL, NarrowVT, Vec1, HiVec0);
13015     } else {
13016       assert(Idx == InVT.getVectorMinNumElements() &&
13017              "Invalid subvector index!");
13018       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
13019       Narrow = DAG.getNode(AArch64ISD::UZP1, DL, NarrowVT, LoVec0, Vec1);
13020     }
13021 
13022     return getSVESafeBitCast(VT, Narrow, DAG);
13023   }
13024 
13025   if (Idx == 0 && isPackedVectorType(VT, DAG)) {
13026     // This will be matched by custom code during ISelDAGToDAG.
13027     if (Vec0.isUndef())
13028       return Op;
13029 
13030     std::optional<unsigned> PredPattern =
13031         getSVEPredPatternFromNumElements(InVT.getVectorNumElements());
13032     auto PredTy = VT.changeVectorElementType(MVT::i1);
13033     SDValue PTrue = getPTrue(DAG, DL, PredTy, *PredPattern);
13034     SDValue ScalableVec1 = convertToScalableVector(DAG, VT, Vec1);
13035     return DAG.getNode(ISD::VSELECT, DL, VT, PTrue, ScalableVec1, Vec0);
13036   }
13037 
13038   return SDValue();
13039 }
13040 
13041 static bool isPow2Splat(SDValue Op, uint64_t &SplatVal, bool &Negated) {
13042   if (Op.getOpcode() != AArch64ISD::DUP &&
13043       Op.getOpcode() != ISD::SPLAT_VECTOR &&
13044       Op.getOpcode() != ISD::BUILD_VECTOR)
13045     return false;
13046 
13047   if (Op.getOpcode() == ISD::BUILD_VECTOR &&
13048       !isAllConstantBuildVector(Op, SplatVal))
13049     return false;
13050 
13051   if (Op.getOpcode() != ISD::BUILD_VECTOR &&
13052       !isa<ConstantSDNode>(Op->getOperand(0)))
13053     return false;
13054 
13055   SplatVal = Op->getConstantOperandVal(0);
13056   if (Op.getValueType().getVectorElementType() != MVT::i64)
13057     SplatVal = (int32_t)SplatVal;
13058 
13059   Negated = false;
13060   if (isPowerOf2_64(SplatVal))
13061     return true;
13062 
13063   Negated = true;
13064   if (isPowerOf2_64(-SplatVal)) {
13065     SplatVal = -SplatVal;
13066     return true;
13067   }
13068 
13069   return false;
13070 }
13071 
13072 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
13073   EVT VT = Op.getValueType();
13074   SDLoc dl(Op);
13075 
13076   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
13077     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
13078 
13079   assert(VT.isScalableVector() && "Expected a scalable vector.");
13080 
13081   bool Signed = Op.getOpcode() == ISD::SDIV;
13082   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
13083 
13084   bool Negated;
13085   uint64_t SplatVal;
13086   if (Signed && isPow2Splat(Op.getOperand(1), SplatVal, Negated)) {
13087     SDValue Pg = getPredicateForScalableVector(DAG, dl, VT);
13088     SDValue Res =
13089         DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, dl, VT, Pg, Op->getOperand(0),
13090                     DAG.getTargetConstant(Log2_64(SplatVal), dl, MVT::i32));
13091     if (Negated)
13092       Res = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), Res);
13093 
13094     return Res;
13095   }
13096 
13097   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
13098     return LowerToPredicatedOp(Op, DAG, PredOpcode);
13099 
13100   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
13101   // operations, and truncate the result.
13102   EVT WidenedVT;
13103   if (VT == MVT::nxv16i8)
13104     WidenedVT = MVT::nxv8i16;
13105   else if (VT == MVT::nxv8i16)
13106     WidenedVT = MVT::nxv4i32;
13107   else
13108     llvm_unreachable("Unexpected Custom DIV operation");
13109 
13110   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
13111   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
13112   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
13113   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
13114   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
13115   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
13116   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
13117   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
13118   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
13119 }
13120 
13121 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
13122   // Currently no fixed length shuffles that require SVE are legal.
13123   if (useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
13124     return false;
13125 
13126   if (VT.getVectorNumElements() == 4 &&
13127       (VT.is128BitVector() || VT.is64BitVector())) {
13128     unsigned Cost = getPerfectShuffleCost(M);
13129     if (Cost <= 1)
13130       return true;
13131   }
13132 
13133   bool DummyBool;
13134   int DummyInt;
13135   unsigned DummyUnsigned;
13136 
13137   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
13138           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
13139           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
13140           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
13141           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
13142           isZIPMask(M, VT, DummyUnsigned) ||
13143           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
13144           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
13145           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
13146           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
13147           isConcatMask(M, VT, VT.getSizeInBits() == 128));
13148 }
13149 
13150 bool AArch64TargetLowering::isVectorClearMaskLegal(ArrayRef<int> M,
13151                                                    EVT VT) const {
13152   // Just delegate to the generic legality, clear masks aren't special.
13153   return isShuffleMaskLegal(M, VT);
13154 }
13155 
13156 /// getVShiftImm - Check if this is a valid build_vector for the immediate
13157 /// operand of a vector shift operation, where all the elements of the
13158 /// build_vector must have the same constant integer value.
13159 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
13160   // Ignore bit_converts.
13161   while (Op.getOpcode() == ISD::BITCAST)
13162     Op = Op.getOperand(0);
13163   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
13164   APInt SplatBits, SplatUndef;
13165   unsigned SplatBitSize;
13166   bool HasAnyUndefs;
13167   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
13168                                     HasAnyUndefs, ElementBits) ||
13169       SplatBitSize > ElementBits)
13170     return false;
13171   Cnt = SplatBits.getSExtValue();
13172   return true;
13173 }
13174 
13175 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
13176 /// operand of a vector shift left operation.  That value must be in the range:
13177 ///   0 <= Value < ElementBits for a left shift; or
13178 ///   0 <= Value <= ElementBits for a long left shift.
13179 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
13180   assert(VT.isVector() && "vector shift count is not a vector type");
13181   int64_t ElementBits = VT.getScalarSizeInBits();
13182   if (!getVShiftImm(Op, ElementBits, Cnt))
13183     return false;
13184   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
13185 }
13186 
13187 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
13188 /// operand of a vector shift right operation. The value must be in the range:
13189 ///   1 <= Value <= ElementBits for a right shift; or
13190 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
13191   assert(VT.isVector() && "vector shift count is not a vector type");
13192   int64_t ElementBits = VT.getScalarSizeInBits();
13193   if (!getVShiftImm(Op, ElementBits, Cnt))
13194     return false;
13195   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
13196 }
13197 
13198 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
13199                                              SelectionDAG &DAG) const {
13200   EVT VT = Op.getValueType();
13201 
13202   if (VT.getScalarType() == MVT::i1) {
13203     // Lower i1 truncate to `(x & 1) != 0`.
13204     SDLoc dl(Op);
13205     EVT OpVT = Op.getOperand(0).getValueType();
13206     SDValue Zero = DAG.getConstant(0, dl, OpVT);
13207     SDValue One = DAG.getConstant(1, dl, OpVT);
13208     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
13209     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
13210   }
13211 
13212   if (!VT.isVector() || VT.isScalableVector())
13213     return SDValue();
13214 
13215   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType(),
13216                                    !Subtarget->isNeonAvailable()))
13217     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
13218 
13219   return SDValue();
13220 }
13221 
13222 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
13223                                                       SelectionDAG &DAG) const {
13224   EVT VT = Op.getValueType();
13225   SDLoc DL(Op);
13226   int64_t Cnt;
13227 
13228   if (!Op.getOperand(1).getValueType().isVector())
13229     return Op;
13230   unsigned EltSize = VT.getScalarSizeInBits();
13231 
13232   switch (Op.getOpcode()) {
13233   case ISD::SHL:
13234     if (VT.isScalableVector() ||
13235         useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable()))
13236       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
13237 
13238     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
13239       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
13240                          DAG.getConstant(Cnt, DL, MVT::i32));
13241     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13242                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
13243                                        MVT::i32),
13244                        Op.getOperand(0), Op.getOperand(1));
13245   case ISD::SRA:
13246   case ISD::SRL:
13247     if (VT.isScalableVector() ||
13248         useSVEForFixedLengthVectorVT(VT, !Subtarget->isNeonAvailable())) {
13249       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
13250                                                 : AArch64ISD::SRL_PRED;
13251       return LowerToPredicatedOp(Op, DAG, Opc);
13252     }
13253 
13254     // Right shift immediate
13255     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
13256       unsigned Opc =
13257           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
13258       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
13259                          DAG.getConstant(Cnt, DL, MVT::i32));
13260     }
13261 
13262     // Right shift register.  Note, there is not a shift right register
13263     // instruction, but the shift left register instruction takes a signed
13264     // value, where negative numbers specify a right shift.
13265     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
13266                                                 : Intrinsic::aarch64_neon_ushl;
13267     // negate the shift amount
13268     SDValue NegShift = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
13269                                    Op.getOperand(1));
13270     SDValue NegShiftLeft =
13271         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13272                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
13273                     NegShift);
13274     return NegShiftLeft;
13275   }
13276 
13277   llvm_unreachable("unexpected shift opcode");
13278 }
13279 
13280 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
13281                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
13282                                     const SDLoc &dl, SelectionDAG &DAG) {
13283   EVT SrcVT = LHS.getValueType();
13284   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
13285          "function only supposed to emit natural comparisons");
13286 
13287   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
13288   APInt CnstBits(VT.getSizeInBits(), 0);
13289   APInt UndefBits(VT.getSizeInBits(), 0);
13290   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
13291   bool IsZero = IsCnst && (CnstBits == 0);
13292 
13293   if (SrcVT.getVectorElementType().isFloatingPoint()) {
13294     switch (CC) {
13295     default:
13296       return SDValue();
13297     case AArch64CC::NE: {
13298       SDValue Fcmeq;
13299       if (IsZero)
13300         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
13301       else
13302         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
13303       return DAG.getNOT(dl, Fcmeq, VT);
13304     }
13305     case AArch64CC::EQ:
13306       if (IsZero)
13307         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
13308       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
13309     case AArch64CC::GE:
13310       if (IsZero)
13311         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
13312       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
13313     case AArch64CC::GT:
13314       if (IsZero)
13315         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
13316       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
13317     case AArch64CC::LE:
13318       if (!NoNans)
13319         return SDValue();
13320       // If we ignore NaNs then we can use to the LS implementation.
13321       [[fallthrough]];
13322     case AArch64CC::LS:
13323       if (IsZero)
13324         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
13325       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
13326     case AArch64CC::LT:
13327       if (!NoNans)
13328         return SDValue();
13329       // If we ignore NaNs then we can use to the MI implementation.
13330       [[fallthrough]];
13331     case AArch64CC::MI:
13332       if (IsZero)
13333         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
13334       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
13335     }
13336   }
13337 
13338   switch (CC) {
13339   default:
13340     return SDValue();
13341   case AArch64CC::NE: {
13342     SDValue Cmeq;
13343     if (IsZero)
13344       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
13345     else
13346       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
13347     return DAG.getNOT(dl, Cmeq, VT);
13348   }
13349   case AArch64CC::EQ:
13350     if (IsZero)
13351       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
13352     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
13353   case AArch64CC::GE:
13354     if (IsZero)
13355       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
13356     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
13357   case AArch64CC::GT:
13358     if (IsZero)
13359       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
13360     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
13361   case AArch64CC::LE:
13362     if (IsZero)
13363       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
13364     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
13365   case AArch64CC::LS:
13366     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
13367   case AArch64CC::LO:
13368     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
13369   case AArch64CC::LT:
13370     if (IsZero)
13371       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
13372     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
13373   case AArch64CC::HI:
13374     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
13375   case AArch64CC::HS:
13376     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
13377   }
13378 }
13379 
13380 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
13381                                            SelectionDAG &DAG) const {
13382   if (Op.getValueType().isScalableVector())
13383     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
13384 
13385   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType(),
13386                                    !Subtarget->isNeonAvailable()))
13387     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
13388 
13389   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13390   SDValue LHS = Op.getOperand(0);
13391   SDValue RHS = Op.getOperand(1);
13392   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
13393   SDLoc dl(Op);
13394 
13395   if (LHS.getValueType().getVectorElementType().isInteger()) {
13396     assert(LHS.getValueType() == RHS.getValueType());
13397     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
13398     SDValue Cmp =
13399         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
13400     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
13401   }
13402 
13403   const bool FullFP16 = DAG.getSubtarget<AArch64Subtarget>().hasFullFP16();
13404 
13405   // Make v4f16 (only) fcmp operations utilise vector instructions
13406   // v8f16 support will be a litle more complicated
13407   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
13408     if (LHS.getValueType().getVectorNumElements() == 4) {
13409       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
13410       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
13411       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
13412       DAG.ReplaceAllUsesWith(Op, NewSetcc);
13413       CmpVT = MVT::v4i32;
13414     } else
13415       return SDValue();
13416   }
13417 
13418   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
13419           LHS.getValueType().getVectorElementType() != MVT::f128);
13420 
13421   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
13422   // clean.  Some of them require two branches to implement.
13423   AArch64CC::CondCode CC1, CC2;
13424   bool ShouldInvert;
13425   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
13426 
13427   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs();
13428   SDValue Cmp =
13429       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
13430   if (!Cmp.getNode())
13431     return SDValue();
13432 
13433   if (CC2 != AArch64CC::AL) {
13434     SDValue Cmp2 =
13435         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
13436     if (!Cmp2.getNode())
13437       return SDValue();
13438 
13439     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
13440   }
13441 
13442   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
13443 
13444   if (ShouldInvert)
13445     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
13446 
13447   return Cmp;
13448 }
13449 
13450 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
13451                                   SelectionDAG &DAG) {
13452   SDValue VecOp = ScalarOp.getOperand(0);
13453   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
13454   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
13455                      DAG.getConstant(0, DL, MVT::i64));
13456 }
13457 
13458 static SDValue getVectorBitwiseReduce(unsigned Opcode, SDValue Vec, EVT VT,
13459                                       SDLoc DL, SelectionDAG &DAG) {
13460   unsigned ScalarOpcode;
13461   switch (Opcode) {
13462   case ISD::VECREDUCE_AND:
13463     ScalarOpcode = ISD::AND;
13464     break;
13465   case ISD::VECREDUCE_OR:
13466     ScalarOpcode = ISD::OR;
13467     break;
13468   case ISD::VECREDUCE_XOR:
13469     ScalarOpcode = ISD::XOR;
13470     break;
13471   default:
13472     llvm_unreachable("Expected bitwise vector reduction");
13473     return SDValue();
13474   }
13475 
13476   EVT VecVT = Vec.getValueType();
13477   assert(VecVT.isFixedLengthVector() && VecVT.isPow2VectorType() &&
13478          "Expected power-of-2 length vector");
13479 
13480   EVT ElemVT = VecVT.getVectorElementType();
13481 
13482   SDValue Result;
13483   unsigned NumElems = VecVT.getVectorNumElements();
13484 
13485   // Special case for boolean reductions
13486   if (ElemVT == MVT::i1) {
13487     // Split large vectors into smaller ones
13488     if (NumElems > 16) {
13489       SDValue Lo, Hi;
13490       std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
13491       EVT HalfVT = Lo.getValueType();
13492       SDValue HalfVec = DAG.getNode(ScalarOpcode, DL, HalfVT, Lo, Hi);
13493       return getVectorBitwiseReduce(Opcode, HalfVec, VT, DL, DAG);
13494     }
13495 
13496     // Vectors that are less than 64 bits get widened to neatly fit a 64 bit
13497     // register, so e.g. <4 x i1> gets lowered to <4 x i16>. Sign extending to
13498     // this element size leads to the best codegen, since e.g. setcc results
13499     // might need to be truncated otherwise.
13500     EVT ExtendedVT = MVT::getIntegerVT(std::max(64u / NumElems, 8u));
13501 
13502     // any_ext doesn't work with umin/umax, so only use it for uadd.
13503     unsigned ExtendOp =
13504         ScalarOpcode == ISD::XOR ? ISD::ANY_EXTEND : ISD::SIGN_EXTEND;
13505     SDValue Extended = DAG.getNode(
13506         ExtendOp, DL, VecVT.changeVectorElementType(ExtendedVT), Vec);
13507     switch (ScalarOpcode) {
13508     case ISD::AND:
13509       Result = DAG.getNode(ISD::VECREDUCE_UMIN, DL, ExtendedVT, Extended);
13510       break;
13511     case ISD::OR:
13512       Result = DAG.getNode(ISD::VECREDUCE_UMAX, DL, ExtendedVT, Extended);
13513       break;
13514     case ISD::XOR:
13515       Result = DAG.getNode(ISD::VECREDUCE_ADD, DL, ExtendedVT, Extended);
13516       break;
13517     default:
13518       llvm_unreachable("Unexpected Opcode");
13519     }
13520 
13521     Result = DAG.getAnyExtOrTrunc(Result, DL, MVT::i1);
13522   } else {
13523     // Iteratively split the vector in half and combine using the bitwise
13524     // operation until it fits in a 64 bit register.
13525     while (VecVT.getSizeInBits() > 64) {
13526       SDValue Lo, Hi;
13527       std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
13528       VecVT = Lo.getValueType();
13529       NumElems = VecVT.getVectorNumElements();
13530       Vec = DAG.getNode(ScalarOpcode, DL, VecVT, Lo, Hi);
13531     }
13532 
13533     EVT ScalarVT = EVT::getIntegerVT(*DAG.getContext(), VecVT.getSizeInBits());
13534 
13535     // Do the remaining work on a scalar since it allows the code generator to
13536     // combine the shift and bitwise operation into one instruction and since
13537     // integer instructions can have higher throughput than vector instructions.
13538     SDValue Scalar = DAG.getBitcast(ScalarVT, Vec);
13539 
13540     // Iteratively combine the lower and upper halves of the scalar using the
13541     // bitwise operation, halving the relevant region of the scalar in each
13542     // iteration, until the relevant region is just one element of the original
13543     // vector.
13544     for (unsigned Shift = NumElems / 2; Shift > 0; Shift /= 2) {
13545       SDValue ShiftAmount =
13546           DAG.getConstant(Shift * ElemVT.getSizeInBits(), DL, MVT::i64);
13547       SDValue Shifted =
13548           DAG.getNode(ISD::SRL, DL, ScalarVT, Scalar, ShiftAmount);
13549       Scalar = DAG.getNode(ScalarOpcode, DL, ScalarVT, Scalar, Shifted);
13550     }
13551 
13552     Result = DAG.getAnyExtOrTrunc(Scalar, DL, ElemVT);
13553   }
13554 
13555   return DAG.getAnyExtOrTrunc(Result, DL, VT);
13556 }
13557 
13558 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
13559                                               SelectionDAG &DAG) const {
13560   SDValue Src = Op.getOperand(0);
13561 
13562   // Try to lower fixed length reductions to SVE.
13563   EVT SrcVT = Src.getValueType();
13564   bool OverrideNEON = !Subtarget->isNeonAvailable() ||
13565                       Op.getOpcode() == ISD::VECREDUCE_AND ||
13566                       Op.getOpcode() == ISD::VECREDUCE_OR ||
13567                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
13568                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
13569                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
13570                        SrcVT.getVectorElementType() == MVT::i64);
13571   if (SrcVT.isScalableVector() ||
13572       useSVEForFixedLengthVectorVT(
13573           SrcVT, OverrideNEON && Subtarget->useSVEForFixedLengthVectors())) {
13574 
13575     if (SrcVT.getVectorElementType() == MVT::i1)
13576       return LowerPredReductionToSVE(Op, DAG);
13577 
13578     switch (Op.getOpcode()) {
13579     case ISD::VECREDUCE_ADD:
13580       return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
13581     case ISD::VECREDUCE_AND:
13582       return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
13583     case ISD::VECREDUCE_OR:
13584       return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
13585     case ISD::VECREDUCE_SMAX:
13586       return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
13587     case ISD::VECREDUCE_SMIN:
13588       return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
13589     case ISD::VECREDUCE_UMAX:
13590       return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
13591     case ISD::VECREDUCE_UMIN:
13592       return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
13593     case ISD::VECREDUCE_XOR:
13594       return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
13595     case ISD::VECREDUCE_FADD:
13596       return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
13597     case ISD::VECREDUCE_FMAX:
13598       return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
13599     case ISD::VECREDUCE_FMIN:
13600       return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
13601     case ISD::VECREDUCE_FMAXIMUM:
13602       return LowerReductionToSVE(AArch64ISD::FMAXV_PRED, Op, DAG);
13603     case ISD::VECREDUCE_FMINIMUM:
13604       return LowerReductionToSVE(AArch64ISD::FMINV_PRED, Op, DAG);
13605     default:
13606       llvm_unreachable("Unhandled fixed length reduction");
13607     }
13608   }
13609 
13610   // Lower NEON reductions.
13611   SDLoc dl(Op);
13612   switch (Op.getOpcode()) {
13613   case ISD::VECREDUCE_AND:
13614   case ISD::VECREDUCE_OR:
13615   case ISD::VECREDUCE_XOR:
13616     return getVectorBitwiseReduce(Op.getOpcode(), Op.getOperand(0),
13617                                   Op.getValueType(), dl, DAG);
13618   case ISD::VECREDUCE_ADD:
13619     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
13620   case ISD::VECREDUCE_SMAX:
13621     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
13622   case ISD::VECREDUCE_SMIN:
13623     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
13624   case ISD::VECREDUCE_UMAX:
13625     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
13626   case ISD::VECREDUCE_UMIN:
13627     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
13628   default:
13629     llvm_unreachable("Unhandled reduction");
13630   }
13631 }
13632 
13633 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
13634                                                     SelectionDAG &DAG) const {
13635   auto &Subtarget = DAG.getSubtarget<AArch64Subtarget>();
13636   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
13637     return SDValue();
13638 
13639   // LSE has an atomic load-add instruction, but not a load-sub.
13640   SDLoc dl(Op);
13641   MVT VT = Op.getSimpleValueType();
13642   SDValue RHS = Op.getOperand(2);
13643   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
13644   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
13645   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
13646                        Op.getOperand(0), Op.getOperand(1), RHS,
13647                        AN->getMemOperand());
13648 }
13649 
13650 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
13651                                                     SelectionDAG &DAG) const {
13652   auto &Subtarget = DAG.getSubtarget<AArch64Subtarget>();
13653   // No point replacing if we don't have the relevant instruction/libcall anyway
13654   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
13655     return SDValue();
13656 
13657   // LSE has an atomic load-clear instruction, but not a load-and.
13658   SDLoc dl(Op);
13659   MVT VT = Op.getSimpleValueType();
13660   assert(VT != MVT::i128 && "Handled elsewhere, code replicated.");
13661   SDValue RHS = Op.getOperand(2);
13662   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
13663   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
13664   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
13665                        Op.getOperand(0), Op.getOperand(1), RHS,
13666                        AN->getMemOperand());
13667 }
13668 
13669 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
13670     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
13671   SDLoc dl(Op);
13672   EVT PtrVT = getPointerTy(DAG.getDataLayout());
13673   SDValue Callee = DAG.getTargetExternalSymbol(Subtarget->getChkStkName(),
13674                                                PtrVT, 0);
13675 
13676   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13677   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
13678   if (Subtarget->hasCustomCallingConv())
13679     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
13680 
13681   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
13682                      DAG.getConstant(4, dl, MVT::i64));
13683   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
13684   Chain =
13685       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
13686                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
13687                   DAG.getRegisterMask(Mask), Chain.getValue(1));
13688   // To match the actual intent better, we should read the output from X15 here
13689   // again (instead of potentially spilling it to the stack), but rereading Size
13690   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
13691   // here.
13692 
13693   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
13694                      DAG.getConstant(4, dl, MVT::i64));
13695   return Chain;
13696 }
13697 
13698 // When x and y are extended, lower:
13699 //   avgfloor(x, y) -> (x + y) >> 1
13700 //   avgceil(x, y)  -> (x + y + 1) >> 1
13701 
13702 // Otherwise, lower to:
13703 //   avgfloor(x, y) -> (x >> 1) + (y >> 1) + (x & y & 1)
13704 //   avgceil(x, y)  -> (x >> 1) + (y >> 1) + ((x || y) & 1)
13705 SDValue AArch64TargetLowering::LowerAVG(SDValue Op, SelectionDAG &DAG,
13706                                         unsigned NewOp) const {
13707   if (Subtarget->hasSVE2())
13708     return LowerToPredicatedOp(Op, DAG, NewOp);
13709 
13710   SDLoc dl(Op);
13711   SDValue OpA = Op->getOperand(0);
13712   SDValue OpB = Op->getOperand(1);
13713   EVT VT = Op.getValueType();
13714   bool IsCeil =
13715       (Op->getOpcode() == ISD::AVGCEILS || Op->getOpcode() == ISD::AVGCEILU);
13716   bool IsSigned =
13717       (Op->getOpcode() == ISD::AVGFLOORS || Op->getOpcode() == ISD::AVGCEILS);
13718   unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
13719 
13720   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
13721 
13722   auto IsZeroExtended = [&DAG](SDValue &Node) {
13723     KnownBits Known = DAG.computeKnownBits(Node, 0);
13724     return Known.Zero.isSignBitSet();
13725   };
13726 
13727   auto IsSignExtended = [&DAG](SDValue &Node) {
13728     return (DAG.ComputeNumSignBits(Node, 0) > 1);
13729   };
13730 
13731   SDValue ConstantOne = DAG.getConstant(1, dl, VT);
13732   if ((!IsSigned && IsZeroExtended(OpA) && IsZeroExtended(OpB)) ||
13733       (IsSigned && IsSignExtended(OpA) && IsSignExtended(OpB))) {
13734     SDValue Add = DAG.getNode(ISD::ADD, dl, VT, OpA, OpB);
13735     if (IsCeil)
13736       Add = DAG.getNode(ISD::ADD, dl, VT, Add, ConstantOne);
13737     return DAG.getNode(ShiftOpc, dl, VT, Add, ConstantOne);
13738   }
13739 
13740   SDValue ShiftOpA = DAG.getNode(ShiftOpc, dl, VT, OpA, ConstantOne);
13741   SDValue ShiftOpB = DAG.getNode(ShiftOpc, dl, VT, OpB, ConstantOne);
13742 
13743   SDValue tmp = DAG.getNode(IsCeil ? ISD::OR : ISD::AND, dl, VT, OpA, OpB);
13744   tmp = DAG.getNode(ISD::AND, dl, VT, tmp, ConstantOne);
13745   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, ShiftOpA, ShiftOpB);
13746   return DAG.getNode(ISD::ADD, dl, VT, Add, tmp);
13747 }
13748 
13749 SDValue
13750 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13751                                                SelectionDAG &DAG) const {
13752   assert(Subtarget->isTargetWindows() &&
13753          "Only Windows alloca probing supported");
13754   SDLoc dl(Op);
13755   // Get the inputs.
13756   SDNode *Node = Op.getNode();
13757   SDValue Chain = Op.getOperand(0);
13758   SDValue Size = Op.getOperand(1);
13759   MaybeAlign Align =
13760       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
13761   EVT VT = Node->getValueType(0);
13762 
13763   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
13764           "no-stack-arg-probe")) {
13765     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
13766     Chain = SP.getValue(1);
13767     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
13768     if (Align)
13769       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13770                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
13771     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
13772     SDValue Ops[2] = {SP, Chain};
13773     return DAG.getMergeValues(Ops, dl);
13774   }
13775 
13776   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
13777 
13778   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
13779 
13780   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
13781   Chain = SP.getValue(1);
13782   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
13783   if (Align)
13784     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13785                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
13786   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
13787 
13788   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
13789 
13790   SDValue Ops[2] = {SP, Chain};
13791   return DAG.getMergeValues(Ops, dl);
13792 }
13793 
13794 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
13795                                            SelectionDAG &DAG) const {
13796   EVT VT = Op.getValueType();
13797   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
13798 
13799   SDLoc DL(Op);
13800   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
13801   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sext(64)), DL,
13802                             VT);
13803 }
13804 
13805 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
13806 template <unsigned NumVecs>
13807 static bool
13808 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
13809               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
13810   Info.opc = ISD::INTRINSIC_VOID;
13811   // Retrieve EC from first vector argument.
13812   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
13813   ElementCount EC = VT.getVectorElementCount();
13814 #ifndef NDEBUG
13815   // Check the assumption that all input vectors are the same type.
13816   for (unsigned I = 0; I < NumVecs; ++I)
13817     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
13818            "Invalid type.");
13819 #endif
13820   // memVT is `NumVecs * VT`.
13821   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
13822                                 EC * NumVecs);
13823   Info.ptrVal = CI.getArgOperand(CI.arg_size() - 1);
13824   Info.offset = 0;
13825   Info.align.reset();
13826   Info.flags = MachineMemOperand::MOStore;
13827   return true;
13828 }
13829 
13830 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13831 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13832 /// specified in the intrinsic calls.
13833 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13834                                                const CallInst &I,
13835                                                MachineFunction &MF,
13836                                                unsigned Intrinsic) const {
13837   auto &DL = I.getModule()->getDataLayout();
13838   switch (Intrinsic) {
13839   case Intrinsic::aarch64_sve_st2:
13840     return setInfoSVEStN<2>(*this, DL, Info, I);
13841   case Intrinsic::aarch64_sve_st3:
13842     return setInfoSVEStN<3>(*this, DL, Info, I);
13843   case Intrinsic::aarch64_sve_st4:
13844     return setInfoSVEStN<4>(*this, DL, Info, I);
13845   case Intrinsic::aarch64_neon_ld2:
13846   case Intrinsic::aarch64_neon_ld3:
13847   case Intrinsic::aarch64_neon_ld4:
13848   case Intrinsic::aarch64_neon_ld1x2:
13849   case Intrinsic::aarch64_neon_ld1x3:
13850   case Intrinsic::aarch64_neon_ld1x4: {
13851     Info.opc = ISD::INTRINSIC_W_CHAIN;
13852     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13853     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13854     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
13855     Info.offset = 0;
13856     Info.align.reset();
13857     // volatile loads with NEON intrinsics not supported
13858     Info.flags = MachineMemOperand::MOLoad;
13859     return true;
13860   }
13861   case Intrinsic::aarch64_neon_ld2lane:
13862   case Intrinsic::aarch64_neon_ld3lane:
13863   case Intrinsic::aarch64_neon_ld4lane:
13864   case Intrinsic::aarch64_neon_ld2r:
13865   case Intrinsic::aarch64_neon_ld3r:
13866   case Intrinsic::aarch64_neon_ld4r: {
13867     Info.opc = ISD::INTRINSIC_W_CHAIN;
13868     // ldx return struct with the same vec type
13869     Type *RetTy = I.getType();
13870     auto *StructTy = cast<StructType>(RetTy);
13871     unsigned NumElts = StructTy->getNumElements();
13872     Type *VecTy = StructTy->getElementType(0);
13873     MVT EleVT = MVT::getVT(VecTy).getVectorElementType();
13874     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), EleVT, NumElts);
13875     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
13876     Info.offset = 0;
13877     Info.align.reset();
13878     // volatile loads with NEON intrinsics not supported
13879     Info.flags = MachineMemOperand::MOLoad;
13880     return true;
13881   }
13882   case Intrinsic::aarch64_neon_st2:
13883   case Intrinsic::aarch64_neon_st3:
13884   case Intrinsic::aarch64_neon_st4:
13885   case Intrinsic::aarch64_neon_st1x2:
13886   case Intrinsic::aarch64_neon_st1x3:
13887   case Intrinsic::aarch64_neon_st1x4: {
13888     Info.opc = ISD::INTRINSIC_VOID;
13889     unsigned NumElts = 0;
13890     for (const Value *Arg : I.args()) {
13891       Type *ArgTy = Arg->getType();
13892       if (!ArgTy->isVectorTy())
13893         break;
13894       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13895     }
13896     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13897     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
13898     Info.offset = 0;
13899     Info.align.reset();
13900     // volatile stores with NEON intrinsics not supported
13901     Info.flags = MachineMemOperand::MOStore;
13902     return true;
13903   }
13904   case Intrinsic::aarch64_neon_st2lane:
13905   case Intrinsic::aarch64_neon_st3lane:
13906   case Intrinsic::aarch64_neon_st4lane: {
13907     Info.opc = ISD::INTRINSIC_VOID;
13908     unsigned NumElts = 0;
13909     // all the vector type is same
13910     Type *VecTy = I.getArgOperand(0)->getType();
13911     MVT EleVT = MVT::getVT(VecTy).getVectorElementType();
13912 
13913     for (const Value *Arg : I.args()) {
13914       Type *ArgTy = Arg->getType();
13915       if (!ArgTy->isVectorTy())
13916         break;
13917       NumElts += 1;
13918     }
13919 
13920     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), EleVT, NumElts);
13921     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
13922     Info.offset = 0;
13923     Info.align.reset();
13924     // volatile stores with NEON intrinsics not supported
13925     Info.flags = MachineMemOperand::MOStore;
13926     return true;
13927   }
13928   case Intrinsic::aarch64_ldaxr:
13929   case Intrinsic::aarch64_ldxr: {
13930     Type *ValTy = I.getParamElementType(0);
13931     Info.opc = ISD::INTRINSIC_W_CHAIN;
13932     Info.memVT = MVT::getVT(ValTy);
13933     Info.ptrVal = I.getArgOperand(0);
13934     Info.offset = 0;
13935     Info.align = DL.getABITypeAlign(ValTy);
13936     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13937     return true;
13938   }
13939   case Intrinsic::aarch64_stlxr:
13940   case Intrinsic::aarch64_stxr: {
13941     Type *ValTy = I.getParamElementType(1);
13942     Info.opc = ISD::INTRINSIC_W_CHAIN;
13943     Info.memVT = MVT::getVT(ValTy);
13944     Info.ptrVal = I.getArgOperand(1);
13945     Info.offset = 0;
13946     Info.align = DL.getABITypeAlign(ValTy);
13947     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13948     return true;
13949   }
13950   case Intrinsic::aarch64_ldaxp:
13951   case Intrinsic::aarch64_ldxp:
13952     Info.opc = ISD::INTRINSIC_W_CHAIN;
13953     Info.memVT = MVT::i128;
13954     Info.ptrVal = I.getArgOperand(0);
13955     Info.offset = 0;
13956     Info.align = Align(16);
13957     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13958     return true;
13959   case Intrinsic::aarch64_stlxp:
13960   case Intrinsic::aarch64_stxp:
13961     Info.opc = ISD::INTRINSIC_W_CHAIN;
13962     Info.memVT = MVT::i128;
13963     Info.ptrVal = I.getArgOperand(2);
13964     Info.offset = 0;
13965     Info.align = Align(16);
13966     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13967     return true;
13968   case Intrinsic::aarch64_sve_ldnt1: {
13969     Type *ElTy = cast<VectorType>(I.getType())->getElementType();
13970     Info.opc = ISD::INTRINSIC_W_CHAIN;
13971     Info.memVT = MVT::getVT(I.getType());
13972     Info.ptrVal = I.getArgOperand(1);
13973     Info.offset = 0;
13974     Info.align = DL.getABITypeAlign(ElTy);
13975     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
13976     return true;
13977   }
13978   case Intrinsic::aarch64_sve_stnt1: {
13979     Type *ElTy =
13980         cast<VectorType>(I.getArgOperand(0)->getType())->getElementType();
13981     Info.opc = ISD::INTRINSIC_W_CHAIN;
13982     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
13983     Info.ptrVal = I.getArgOperand(2);
13984     Info.offset = 0;
13985     Info.align = DL.getABITypeAlign(ElTy);
13986     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
13987     return true;
13988   }
13989   case Intrinsic::aarch64_mops_memset_tag: {
13990     Value *Dst = I.getArgOperand(0);
13991     Value *Val = I.getArgOperand(1);
13992     Info.opc = ISD::INTRINSIC_W_CHAIN;
13993     Info.memVT = MVT::getVT(Val->getType());
13994     Info.ptrVal = Dst;
13995     Info.offset = 0;
13996     Info.align = I.getParamAlign(0).valueOrOne();
13997     Info.flags = MachineMemOperand::MOStore;
13998     // The size of the memory being operated on is unknown at this point
13999     Info.size = MemoryLocation::UnknownSize;
14000     return true;
14001   }
14002   default:
14003     break;
14004   }
14005 
14006   return false;
14007 }
14008 
14009 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
14010                                                   ISD::LoadExtType ExtTy,
14011                                                   EVT NewVT) const {
14012   // TODO: This may be worth removing. Check regression tests for diffs.
14013   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
14014     return false;
14015 
14016   // If we're reducing the load width in order to avoid having to use an extra
14017   // instruction to do extension then it's probably a good idea.
14018   if (ExtTy != ISD::NON_EXTLOAD)
14019     return true;
14020   // Don't reduce load width if it would prevent us from combining a shift into
14021   // the offset.
14022   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
14023   assert(Mem);
14024   const SDValue &Base = Mem->getBasePtr();
14025   if (Base.getOpcode() == ISD::ADD &&
14026       Base.getOperand(1).getOpcode() == ISD::SHL &&
14027       Base.getOperand(1).hasOneUse() &&
14028       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
14029     // It's unknown whether a scalable vector has a power-of-2 bitwidth.
14030     if (Mem->getMemoryVT().isScalableVector())
14031       return false;
14032     // The shift can be combined if it matches the size of the value being
14033     // loaded (and so reducing the width would make it not match).
14034     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
14035     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
14036     if (ShiftAmount == Log2_32(LoadBytes))
14037       return false;
14038   }
14039   // We have no reason to disallow reducing the load width, so allow it.
14040   return true;
14041 }
14042 
14043 // Treat a sext_inreg(extract(..)) as free if it has multiple uses.
14044 bool AArch64TargetLowering::shouldRemoveRedundantExtend(SDValue Extend) const {
14045   EVT VT = Extend.getValueType();
14046   if ((VT == MVT::i64 || VT == MVT::i32) && Extend->use_size()) {
14047     SDValue Extract = Extend.getOperand(0);
14048     if (Extract.getOpcode() == ISD::ANY_EXTEND && Extract.hasOneUse())
14049       Extract = Extract.getOperand(0);
14050     if (Extract.getOpcode() == ISD::EXTRACT_VECTOR_ELT && Extract.hasOneUse()) {
14051       EVT VecVT = Extract.getOperand(0).getValueType();
14052       if (VecVT.getScalarType() == MVT::i8 || VecVT.getScalarType() == MVT::i16)
14053         return false;
14054     }
14055   }
14056   return true;
14057 }
14058 
14059 // Truncations from 64-bit GPR to 32-bit GPR is free.
14060 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14061   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14062     return false;
14063   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedValue();
14064   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedValue();
14065   return NumBits1 > NumBits2;
14066 }
14067 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14068   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
14069     return false;
14070   uint64_t NumBits1 = VT1.getFixedSizeInBits();
14071   uint64_t NumBits2 = VT2.getFixedSizeInBits();
14072   return NumBits1 > NumBits2;
14073 }
14074 
14075 /// Check if it is profitable to hoist instruction in then/else to if.
14076 /// Not profitable if I and it's user can form a FMA instruction
14077 /// because we prefer FMSUB/FMADD.
14078 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
14079   if (I->getOpcode() != Instruction::FMul)
14080     return true;
14081 
14082   if (!I->hasOneUse())
14083     return true;
14084 
14085   Instruction *User = I->user_back();
14086 
14087   if (!(User->getOpcode() == Instruction::FSub ||
14088         User->getOpcode() == Instruction::FAdd))
14089     return true;
14090 
14091   const TargetOptions &Options = getTargetMachine().Options;
14092   const Function *F = I->getFunction();
14093   const DataLayout &DL = F->getParent()->getDataLayout();
14094   Type *Ty = User->getOperand(0)->getType();
14095 
14096   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
14097            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
14098            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
14099             Options.UnsafeFPMath));
14100 }
14101 
14102 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
14103 // 64-bit GPR.
14104 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14105   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14106     return false;
14107   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14108   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14109   return NumBits1 == 32 && NumBits2 == 64;
14110 }
14111 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14112   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
14113     return false;
14114   unsigned NumBits1 = VT1.getSizeInBits();
14115   unsigned NumBits2 = VT2.getSizeInBits();
14116   return NumBits1 == 32 && NumBits2 == 64;
14117 }
14118 
14119 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14120   EVT VT1 = Val.getValueType();
14121   if (isZExtFree(VT1, VT2)) {
14122     return true;
14123   }
14124 
14125   if (Val.getOpcode() != ISD::LOAD)
14126     return false;
14127 
14128   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
14129   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
14130           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
14131           VT1.getSizeInBits() <= 32);
14132 }
14133 
14134 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
14135   if (isa<FPExtInst>(Ext))
14136     return false;
14137 
14138   // Vector types are not free.
14139   if (Ext->getType()->isVectorTy())
14140     return false;
14141 
14142   for (const Use &U : Ext->uses()) {
14143     // The extension is free if we can fold it with a left shift in an
14144     // addressing mode or an arithmetic operation: add, sub, and cmp.
14145 
14146     // Is there a shift?
14147     const Instruction *Instr = cast<Instruction>(U.getUser());
14148 
14149     // Is this a constant shift?
14150     switch (Instr->getOpcode()) {
14151     case Instruction::Shl:
14152       if (!isa<ConstantInt>(Instr->getOperand(1)))
14153         return false;
14154       break;
14155     case Instruction::GetElementPtr: {
14156       gep_type_iterator GTI = gep_type_begin(Instr);
14157       auto &DL = Ext->getModule()->getDataLayout();
14158       std::advance(GTI, U.getOperandNo()-1);
14159       Type *IdxTy = GTI.getIndexedType();
14160       // This extension will end up with a shift because of the scaling factor.
14161       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
14162       // Get the shift amount based on the scaling factor:
14163       // log2(sizeof(IdxTy)) - log2(8).
14164       if (IdxTy->isScalableTy())
14165         return false;
14166       uint64_t ShiftAmt =
14167           llvm::countr_zero(DL.getTypeStoreSizeInBits(IdxTy).getFixedValue()) -
14168           3;
14169       // Is the constant foldable in the shift of the addressing mode?
14170       // I.e., shift amount is between 1 and 4 inclusive.
14171       if (ShiftAmt == 0 || ShiftAmt > 4)
14172         return false;
14173       break;
14174     }
14175     case Instruction::Trunc:
14176       // Check if this is a noop.
14177       // trunc(sext ty1 to ty2) to ty1.
14178       if (Instr->getType() == Ext->getOperand(0)->getType())
14179         continue;
14180       [[fallthrough]];
14181     default:
14182       return false;
14183     }
14184 
14185     // At this point we can use the bfm family, so this extension is free
14186     // for that use.
14187   }
14188   return true;
14189 }
14190 
14191 static bool isSplatShuffle(Value *V) {
14192   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V))
14193     return all_equal(Shuf->getShuffleMask());
14194   return false;
14195 }
14196 
14197 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
14198 /// or upper half of the vector elements.
14199 static bool areExtractShuffleVectors(Value *Op1, Value *Op2,
14200                                      bool AllowSplat = false) {
14201   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
14202     auto *FullTy = FullV->getType();
14203     auto *HalfTy = HalfV->getType();
14204     return FullTy->getPrimitiveSizeInBits().getFixedValue() ==
14205            2 * HalfTy->getPrimitiveSizeInBits().getFixedValue();
14206   };
14207 
14208   auto extractHalf = [](Value *FullV, Value *HalfV) {
14209     auto *FullVT = cast<FixedVectorType>(FullV->getType());
14210     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
14211     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
14212   };
14213 
14214   ArrayRef<int> M1, M2;
14215   Value *S1Op1 = nullptr, *S2Op1 = nullptr;
14216   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
14217       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
14218     return false;
14219 
14220   // If we allow splats, set S1Op1/S2Op1 to nullptr for the relavant arg so that
14221   // it is not checked as an extract below.
14222   if (AllowSplat && isSplatShuffle(Op1))
14223     S1Op1 = nullptr;
14224   if (AllowSplat && isSplatShuffle(Op2))
14225     S2Op1 = nullptr;
14226 
14227   // Check that the operands are half as wide as the result and we extract
14228   // half of the elements of the input vectors.
14229   if ((S1Op1 && (!areTypesHalfed(S1Op1, Op1) || !extractHalf(S1Op1, Op1))) ||
14230       (S2Op1 && (!areTypesHalfed(S2Op1, Op2) || !extractHalf(S2Op1, Op2))))
14231     return false;
14232 
14233   // Check the mask extracts either the lower or upper half of vector
14234   // elements.
14235   int M1Start = 0;
14236   int M2Start = 0;
14237   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
14238   if ((S1Op1 &&
14239        !ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start)) ||
14240       (S2Op1 &&
14241        !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start)))
14242     return false;
14243 
14244   if ((M1Start != 0 && M1Start != (NumElements / 2)) ||
14245       (M2Start != 0 && M2Start != (NumElements / 2)))
14246     return false;
14247   if (S1Op1 && S2Op1 && M1Start != M2Start)
14248     return false;
14249 
14250   return true;
14251 }
14252 
14253 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14254 /// of the vector elements.
14255 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14256   auto areExtDoubled = [](Instruction *Ext) {
14257     return Ext->getType()->getScalarSizeInBits() ==
14258            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14259   };
14260 
14261   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14262       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14263       !areExtDoubled(cast<Instruction>(Ext1)) ||
14264       !areExtDoubled(cast<Instruction>(Ext2)))
14265     return false;
14266 
14267   return true;
14268 }
14269 
14270 /// Check if Op could be used with vmull_high_p64 intrinsic.
14271 static bool isOperandOfVmullHighP64(Value *Op) {
14272   Value *VectorOperand = nullptr;
14273   ConstantInt *ElementIndex = nullptr;
14274   return match(Op, m_ExtractElt(m_Value(VectorOperand),
14275                                 m_ConstantInt(ElementIndex))) &&
14276          ElementIndex->getValue() == 1 &&
14277          isa<FixedVectorType>(VectorOperand->getType()) &&
14278          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
14279 }
14280 
14281 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
14282 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
14283   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
14284 }
14285 
14286 /// Check if sinking \p I's operands to I's basic block is profitable, because
14287 /// the operands can be folded into a target instruction, e.g.
14288 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
14289 bool AArch64TargetLowering::shouldSinkOperands(
14290     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
14291   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
14292     switch (II->getIntrinsicID()) {
14293     case Intrinsic::aarch64_neon_smull:
14294     case Intrinsic::aarch64_neon_umull:
14295       if (areExtractShuffleVectors(II->getOperand(0), II->getOperand(1),
14296                                    /*AllowSplat=*/true)) {
14297         Ops.push_back(&II->getOperandUse(0));
14298         Ops.push_back(&II->getOperandUse(1));
14299         return true;
14300       }
14301       [[fallthrough]];
14302 
14303     case Intrinsic::fma:
14304       if (isa<VectorType>(I->getType()) &&
14305           cast<VectorType>(I->getType())->getElementType()->isHalfTy() &&
14306           !Subtarget->hasFullFP16())
14307         return false;
14308       [[fallthrough]];
14309     case Intrinsic::aarch64_neon_sqdmull:
14310     case Intrinsic::aarch64_neon_sqdmulh:
14311     case Intrinsic::aarch64_neon_sqrdmulh:
14312       // Sink splats for index lane variants
14313       if (isSplatShuffle(II->getOperand(0)))
14314         Ops.push_back(&II->getOperandUse(0));
14315       if (isSplatShuffle(II->getOperand(1)))
14316         Ops.push_back(&II->getOperandUse(1));
14317       return !Ops.empty();
14318     case Intrinsic::aarch64_sve_ptest_first:
14319     case Intrinsic::aarch64_sve_ptest_last:
14320       if (auto *IIOp = dyn_cast<IntrinsicInst>(II->getOperand(0)))
14321         if (IIOp->getIntrinsicID() == Intrinsic::aarch64_sve_ptrue)
14322           Ops.push_back(&II->getOperandUse(0));
14323       return !Ops.empty();
14324     case Intrinsic::aarch64_sme_write_horiz:
14325     case Intrinsic::aarch64_sme_write_vert:
14326     case Intrinsic::aarch64_sme_writeq_horiz:
14327     case Intrinsic::aarch64_sme_writeq_vert: {
14328       auto *Idx = dyn_cast<Instruction>(II->getOperand(1));
14329       if (!Idx || Idx->getOpcode() != Instruction::Add)
14330         return false;
14331       Ops.push_back(&II->getOperandUse(1));
14332       return true;
14333     }
14334     case Intrinsic::aarch64_sme_read_horiz:
14335     case Intrinsic::aarch64_sme_read_vert:
14336     case Intrinsic::aarch64_sme_readq_horiz:
14337     case Intrinsic::aarch64_sme_readq_vert:
14338     case Intrinsic::aarch64_sme_ld1b_vert:
14339     case Intrinsic::aarch64_sme_ld1h_vert:
14340     case Intrinsic::aarch64_sme_ld1w_vert:
14341     case Intrinsic::aarch64_sme_ld1d_vert:
14342     case Intrinsic::aarch64_sme_ld1q_vert:
14343     case Intrinsic::aarch64_sme_st1b_vert:
14344     case Intrinsic::aarch64_sme_st1h_vert:
14345     case Intrinsic::aarch64_sme_st1w_vert:
14346     case Intrinsic::aarch64_sme_st1d_vert:
14347     case Intrinsic::aarch64_sme_st1q_vert:
14348     case Intrinsic::aarch64_sme_ld1b_horiz:
14349     case Intrinsic::aarch64_sme_ld1h_horiz:
14350     case Intrinsic::aarch64_sme_ld1w_horiz:
14351     case Intrinsic::aarch64_sme_ld1d_horiz:
14352     case Intrinsic::aarch64_sme_ld1q_horiz:
14353     case Intrinsic::aarch64_sme_st1b_horiz:
14354     case Intrinsic::aarch64_sme_st1h_horiz:
14355     case Intrinsic::aarch64_sme_st1w_horiz:
14356     case Intrinsic::aarch64_sme_st1d_horiz:
14357     case Intrinsic::aarch64_sme_st1q_horiz: {
14358       auto *Idx = dyn_cast<Instruction>(II->getOperand(3));
14359       if (!Idx || Idx->getOpcode() != Instruction::Add)
14360         return false;
14361       Ops.push_back(&II->getOperandUse(3));
14362       return true;
14363     }
14364     case Intrinsic::aarch64_neon_pmull:
14365       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
14366         return false;
14367       Ops.push_back(&II->getOperandUse(0));
14368       Ops.push_back(&II->getOperandUse(1));
14369       return true;
14370     case Intrinsic::aarch64_neon_pmull64:
14371       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
14372                                      II->getArgOperand(1)))
14373         return false;
14374       Ops.push_back(&II->getArgOperandUse(0));
14375       Ops.push_back(&II->getArgOperandUse(1));
14376       return true;
14377     default:
14378       return false;
14379     }
14380   }
14381 
14382   if (!I->getType()->isVectorTy())
14383     return false;
14384 
14385   switch (I->getOpcode()) {
14386   case Instruction::Sub:
14387   case Instruction::Add: {
14388     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14389       return false;
14390 
14391     // If the exts' operands extract either the lower or upper elements, we
14392     // can sink them too.
14393     auto Ext1 = cast<Instruction>(I->getOperand(0));
14394     auto Ext2 = cast<Instruction>(I->getOperand(1));
14395     if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
14396       Ops.push_back(&Ext1->getOperandUse(0));
14397       Ops.push_back(&Ext2->getOperandUse(0));
14398     }
14399 
14400     Ops.push_back(&I->getOperandUse(0));
14401     Ops.push_back(&I->getOperandUse(1));
14402 
14403     return true;
14404   }
14405   case Instruction::Or: {
14406     // Pattern: Or(And(MaskValue, A), And(Not(MaskValue), B)) ->
14407     // bitselect(MaskValue, A, B) where Not(MaskValue) = Xor(MaskValue, -1)
14408     if (Subtarget->hasNEON()) {
14409       Instruction *OtherAnd, *IA, *IB;
14410       Value *MaskValue;
14411       // MainAnd refers to And instruction that has 'Not' as one of its operands
14412       if (match(I, m_c_Or(m_OneUse(m_Instruction(OtherAnd)),
14413                           m_OneUse(m_c_And(m_OneUse(m_Not(m_Value(MaskValue))),
14414                                            m_Instruction(IA)))))) {
14415         if (match(OtherAnd,
14416                   m_c_And(m_Specific(MaskValue), m_Instruction(IB)))) {
14417           Instruction *MainAnd = I->getOperand(0) == OtherAnd
14418                                      ? cast<Instruction>(I->getOperand(1))
14419                                      : cast<Instruction>(I->getOperand(0));
14420 
14421           // Both Ands should be in same basic block as Or
14422           if (I->getParent() != MainAnd->getParent() ||
14423               I->getParent() != OtherAnd->getParent())
14424             return false;
14425 
14426           // Non-mask operands of both Ands should also be in same basic block
14427           if (I->getParent() != IA->getParent() ||
14428               I->getParent() != IB->getParent())
14429             return false;
14430 
14431           Ops.push_back(&MainAnd->getOperandUse(MainAnd->getOperand(0) == IA ? 1 : 0));
14432           Ops.push_back(&I->getOperandUse(0));
14433           Ops.push_back(&I->getOperandUse(1));
14434 
14435           return true;
14436         }
14437       }
14438     }
14439 
14440     return false;
14441   }
14442   case Instruction::Mul: {
14443     int NumZExts = 0, NumSExts = 0;
14444     for (auto &Op : I->operands()) {
14445       // Make sure we are not already sinking this operand
14446       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
14447         continue;
14448 
14449       if (match(&Op, m_SExt(m_Value()))) {
14450         NumSExts++;
14451         continue;
14452       } else if (match(&Op, m_ZExt(m_Value()))) {
14453         NumZExts++;
14454         continue;
14455       }
14456 
14457       ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
14458 
14459       // If the Shuffle is a splat and the operand is a zext/sext, sinking the
14460       // operand and the s/zext can help create indexed s/umull. This is
14461       // especially useful to prevent i64 mul being scalarized.
14462       if (Shuffle && isSplatShuffle(Shuffle) &&
14463           match(Shuffle->getOperand(0), m_ZExtOrSExt(m_Value()))) {
14464         Ops.push_back(&Shuffle->getOperandUse(0));
14465         Ops.push_back(&Op);
14466         if (match(Shuffle->getOperand(0), m_SExt(m_Value())))
14467           NumSExts++;
14468         else
14469           NumZExts++;
14470         continue;
14471       }
14472 
14473       if (!Shuffle)
14474         continue;
14475 
14476       Value *ShuffleOperand = Shuffle->getOperand(0);
14477       InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
14478       if (!Insert)
14479         continue;
14480 
14481       Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
14482       if (!OperandInstr)
14483         continue;
14484 
14485       ConstantInt *ElementConstant =
14486           dyn_cast<ConstantInt>(Insert->getOperand(2));
14487       // Check that the insertelement is inserting into element 0
14488       if (!ElementConstant || !ElementConstant->isZero())
14489         continue;
14490 
14491       unsigned Opcode = OperandInstr->getOpcode();
14492       if (Opcode == Instruction::SExt)
14493         NumSExts++;
14494       else if (Opcode == Instruction::ZExt)
14495         NumZExts++;
14496       else {
14497         // If we find that the top bits are known 0, then we can sink and allow
14498         // the backend to generate a umull.
14499         unsigned Bitwidth = I->getType()->getScalarSizeInBits();
14500         APInt UpperMask = APInt::getHighBitsSet(Bitwidth, Bitwidth / 2);
14501         const DataLayout &DL = I->getFunction()->getParent()->getDataLayout();
14502         if (!MaskedValueIsZero(OperandInstr, UpperMask, DL))
14503           continue;
14504         NumZExts++;
14505       }
14506 
14507       Ops.push_back(&Shuffle->getOperandUse(0));
14508       Ops.push_back(&Op);
14509     }
14510 
14511     // Is it profitable to sink if we found two of the same type of extends.
14512     return !Ops.empty() && (NumSExts == 2 || NumZExts == 2);
14513   }
14514   default:
14515     return false;
14516   }
14517   return false;
14518 }
14519 
14520 static bool createTblShuffleForZExt(ZExtInst *ZExt, FixedVectorType *DstTy,
14521                                     bool IsLittleEndian) {
14522   Value *Op = ZExt->getOperand(0);
14523   auto *SrcTy = cast<FixedVectorType>(Op->getType());
14524   auto SrcWidth = cast<IntegerType>(SrcTy->getElementType())->getBitWidth();
14525   auto DstWidth = cast<IntegerType>(DstTy->getElementType())->getBitWidth();
14526   if (DstWidth % 8 != 0 || DstWidth <= 16 || DstWidth >= 64)
14527     return false;
14528 
14529   assert(DstWidth % SrcWidth == 0 &&
14530          "TBL lowering is not supported for a ZExt instruction with this "
14531          "source & destination element type.");
14532   unsigned ZExtFactor = DstWidth / SrcWidth;
14533   unsigned NumElts = SrcTy->getNumElements();
14534   IRBuilder<> Builder(ZExt);
14535   SmallVector<int> Mask;
14536   // Create a mask that selects <0,...,Op[i]> for each lane of the destination
14537   // vector to replace the original ZExt. This can later be lowered to a set of
14538   // tbl instructions.
14539   for (unsigned i = 0; i < NumElts * ZExtFactor; i++) {
14540     if (IsLittleEndian) {
14541       if (i % ZExtFactor == 0)
14542         Mask.push_back(i / ZExtFactor);
14543       else
14544         Mask.push_back(NumElts);
14545     } else {
14546       if ((i + 1) % ZExtFactor == 0)
14547         Mask.push_back((i - ZExtFactor + 1) / ZExtFactor);
14548       else
14549         Mask.push_back(NumElts);
14550     }
14551   }
14552 
14553   auto *FirstEltZero = Builder.CreateInsertElement(
14554       PoisonValue::get(SrcTy), Builder.getInt8(0), uint64_t(0));
14555   Value *Result = Builder.CreateShuffleVector(Op, FirstEltZero, Mask);
14556   Result = Builder.CreateBitCast(Result, DstTy);
14557   if (DstTy != ZExt->getType())
14558     Result = Builder.CreateZExt(Result, ZExt->getType());
14559   ZExt->replaceAllUsesWith(Result);
14560   ZExt->eraseFromParent();
14561   return true;
14562 }
14563 
14564 static void createTblForTrunc(TruncInst *TI, bool IsLittleEndian) {
14565   IRBuilder<> Builder(TI);
14566   SmallVector<Value *> Parts;
14567   int NumElements = cast<FixedVectorType>(TI->getType())->getNumElements();
14568   auto *SrcTy = cast<FixedVectorType>(TI->getOperand(0)->getType());
14569   auto *DstTy = cast<FixedVectorType>(TI->getType());
14570   assert(SrcTy->getElementType()->isIntegerTy() &&
14571          "Non-integer type source vector element is not supported");
14572   assert(DstTy->getElementType()->isIntegerTy(8) &&
14573          "Unsupported destination vector element type");
14574   unsigned SrcElemTySz =
14575       cast<IntegerType>(SrcTy->getElementType())->getBitWidth();
14576   unsigned DstElemTySz =
14577       cast<IntegerType>(DstTy->getElementType())->getBitWidth();
14578   assert((SrcElemTySz % DstElemTySz == 0) &&
14579          "Cannot lower truncate to tbl instructions for a source element size "
14580          "that is not divisible by the destination element size");
14581   unsigned TruncFactor = SrcElemTySz / DstElemTySz;
14582   assert((SrcElemTySz == 16 || SrcElemTySz == 32 || SrcElemTySz == 64) &&
14583          "Unsupported source vector element type size");
14584   Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), 16);
14585 
14586   // Create a mask to choose every nth byte from the source vector table of
14587   // bytes to create the truncated destination vector, where 'n' is the truncate
14588   // ratio. For example, for a truncate from Yxi64 to Yxi8, choose
14589   // 0,8,16,..Y*8th bytes for the little-endian format
14590   SmallVector<Constant *, 16> MaskConst;
14591   for (int Itr = 0; Itr < 16; Itr++) {
14592     if (Itr < NumElements)
14593       MaskConst.push_back(Builder.getInt8(
14594           IsLittleEndian ? Itr * TruncFactor
14595                          : Itr * TruncFactor + (TruncFactor - 1)));
14596     else
14597       MaskConst.push_back(Builder.getInt8(255));
14598   }
14599 
14600   int MaxTblSz = 128 * 4;
14601   int MaxSrcSz = SrcElemTySz * NumElements;
14602   int ElemsPerTbl =
14603       (MaxTblSz > MaxSrcSz) ? NumElements : (MaxTblSz / SrcElemTySz);
14604   assert(ElemsPerTbl <= 16 &&
14605          "Maximum elements selected using TBL instruction cannot exceed 16!");
14606 
14607   int ShuffleCount = 128 / SrcElemTySz;
14608   SmallVector<int> ShuffleLanes;
14609   for (int i = 0; i < ShuffleCount; ++i)
14610     ShuffleLanes.push_back(i);
14611 
14612   // Create TBL's table of bytes in 1,2,3 or 4 FP/SIMD registers using shuffles
14613   // over the source vector. If TBL's maximum 4 FP/SIMD registers are saturated,
14614   // call TBL & save the result in a vector of TBL results for combining later.
14615   SmallVector<Value *> Results;
14616   while (ShuffleLanes.back() < NumElements) {
14617     Parts.push_back(Builder.CreateBitCast(
14618         Builder.CreateShuffleVector(TI->getOperand(0), ShuffleLanes), VecTy));
14619 
14620     if (Parts.size() == 4) {
14621       auto *F = Intrinsic::getDeclaration(TI->getModule(),
14622                                           Intrinsic::aarch64_neon_tbl4, VecTy);
14623       Parts.push_back(ConstantVector::get(MaskConst));
14624       Results.push_back(Builder.CreateCall(F, Parts));
14625       Parts.clear();
14626     }
14627 
14628     for (int i = 0; i < ShuffleCount; ++i)
14629       ShuffleLanes[i] += ShuffleCount;
14630   }
14631 
14632   assert((Parts.empty() || Results.empty()) &&
14633          "Lowering trunc for vectors requiring different TBL instructions is "
14634          "not supported!");
14635   // Call TBL for the residual table bytes present in 1,2, or 3 FP/SIMD
14636   // registers
14637   if (!Parts.empty()) {
14638     Intrinsic::ID TblID;
14639     switch (Parts.size()) {
14640     case 1:
14641       TblID = Intrinsic::aarch64_neon_tbl1;
14642       break;
14643     case 2:
14644       TblID = Intrinsic::aarch64_neon_tbl2;
14645       break;
14646     case 3:
14647       TblID = Intrinsic::aarch64_neon_tbl3;
14648       break;
14649     }
14650 
14651     auto *F = Intrinsic::getDeclaration(TI->getModule(), TblID, VecTy);
14652     Parts.push_back(ConstantVector::get(MaskConst));
14653     Results.push_back(Builder.CreateCall(F, Parts));
14654   }
14655 
14656   // Extract the destination vector from TBL result(s) after combining them
14657   // where applicable. Currently, at most two TBLs are supported.
14658   assert(Results.size() <= 2 && "Trunc lowering does not support generation of "
14659                                 "more than 2 tbl instructions!");
14660   Value *FinalResult = Results[0];
14661   if (Results.size() == 1) {
14662     if (ElemsPerTbl < 16) {
14663       SmallVector<int> FinalMask(ElemsPerTbl);
14664       std::iota(FinalMask.begin(), FinalMask.end(), 0);
14665       FinalResult = Builder.CreateShuffleVector(Results[0], FinalMask);
14666     }
14667   } else {
14668     SmallVector<int> FinalMask(ElemsPerTbl * Results.size());
14669     if (ElemsPerTbl < 16) {
14670       std::iota(FinalMask.begin(), FinalMask.begin() + ElemsPerTbl, 0);
14671       std::iota(FinalMask.begin() + ElemsPerTbl, FinalMask.end(), 16);
14672     } else {
14673       std::iota(FinalMask.begin(), FinalMask.end(), 0);
14674     }
14675     FinalResult =
14676         Builder.CreateShuffleVector(Results[0], Results[1], FinalMask);
14677   }
14678 
14679   TI->replaceAllUsesWith(FinalResult);
14680   TI->eraseFromParent();
14681 }
14682 
14683 bool AArch64TargetLowering::optimizeExtendOrTruncateConversion(
14684     Instruction *I, Loop *L, const TargetTransformInfo &TTI) const {
14685   // shuffle_vector instructions are serialized when targeting SVE,
14686   // see LowerSPLAT_VECTOR. This peephole is not beneficial.
14687   if (Subtarget->useSVEForFixedLengthVectors())
14688     return false;
14689 
14690   // Try to optimize conversions using tbl. This requires materializing constant
14691   // index vectors, which can increase code size and add loads. Skip the
14692   // transform unless the conversion is in a loop block guaranteed to execute
14693   // and we are not optimizing for size.
14694   Function *F = I->getParent()->getParent();
14695   if (!L || L->getHeader() != I->getParent() || F->hasMinSize() ||
14696       F->hasOptSize())
14697     return false;
14698 
14699   auto *SrcTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
14700   auto *DstTy = dyn_cast<FixedVectorType>(I->getType());
14701   if (!SrcTy || !DstTy)
14702     return false;
14703 
14704   // Convert 'zext <Y x i8> %x to <Y x i8X>' to a shuffle that can be
14705   // lowered to tbl instructions to insert the original i8 elements
14706   // into i8x lanes. This is enabled for cases where it is beneficial.
14707   auto *ZExt = dyn_cast<ZExtInst>(I);
14708   if (ZExt && SrcTy->getElementType()->isIntegerTy(8)) {
14709     auto DstWidth = DstTy->getElementType()->getScalarSizeInBits();
14710     if (DstWidth % 8 != 0)
14711       return false;
14712 
14713     auto *TruncDstType =
14714         cast<FixedVectorType>(VectorType::getTruncatedElementVectorType(DstTy));
14715     // If the ZExt can be lowered to a single ZExt to the next power-of-2 and
14716     // the remaining ZExt folded into the user, don't use tbl lowering.
14717     auto SrcWidth = SrcTy->getElementType()->getScalarSizeInBits();
14718     if (TTI.getCastInstrCost(I->getOpcode(), DstTy, TruncDstType,
14719                              TargetTransformInfo::getCastContextHint(I),
14720                              TTI::TCK_SizeAndLatency, I) == TTI::TCC_Free) {
14721       if (SrcWidth * 2 >= TruncDstType->getElementType()->getScalarSizeInBits())
14722         return false;
14723 
14724       DstTy = TruncDstType;
14725     }
14726 
14727     return createTblShuffleForZExt(ZExt, DstTy, Subtarget->isLittleEndian());
14728   }
14729 
14730   auto *UIToFP = dyn_cast<UIToFPInst>(I);
14731   if (UIToFP && SrcTy->getElementType()->isIntegerTy(8) &&
14732       DstTy->getElementType()->isFloatTy()) {
14733     IRBuilder<> Builder(I);
14734     auto *ZExt = cast<ZExtInst>(
14735         Builder.CreateZExt(I->getOperand(0), VectorType::getInteger(DstTy)));
14736     auto *UI = Builder.CreateUIToFP(ZExt, DstTy);
14737     I->replaceAllUsesWith(UI);
14738     I->eraseFromParent();
14739     return createTblShuffleForZExt(ZExt, cast<FixedVectorType>(ZExt->getType()),
14740                                    Subtarget->isLittleEndian());
14741   }
14742 
14743   // Convert 'fptoui <(8|16) x float> to <(8|16) x i8>' to a wide fptoui
14744   // followed by a truncate lowered to using tbl.4.
14745   auto *FPToUI = dyn_cast<FPToUIInst>(I);
14746   if (FPToUI &&
14747       (SrcTy->getNumElements() == 8 || SrcTy->getNumElements() == 16) &&
14748       SrcTy->getElementType()->isFloatTy() &&
14749       DstTy->getElementType()->isIntegerTy(8)) {
14750     IRBuilder<> Builder(I);
14751     auto *WideConv = Builder.CreateFPToUI(FPToUI->getOperand(0),
14752                                           VectorType::getInteger(SrcTy));
14753     auto *TruncI = Builder.CreateTrunc(WideConv, DstTy);
14754     I->replaceAllUsesWith(TruncI);
14755     I->eraseFromParent();
14756     createTblForTrunc(cast<TruncInst>(TruncI), Subtarget->isLittleEndian());
14757     return true;
14758   }
14759 
14760   // Convert 'trunc <(8|16) x (i32|i64)> %x to <(8|16) x i8>' to an appropriate
14761   // tbl instruction selecting the lowest/highest (little/big endian) 8 bits
14762   // per lane of the input that is represented using 1,2,3 or 4 128-bit table
14763   // registers
14764   auto *TI = dyn_cast<TruncInst>(I);
14765   if (TI && DstTy->getElementType()->isIntegerTy(8) &&
14766       ((SrcTy->getElementType()->isIntegerTy(32) ||
14767         SrcTy->getElementType()->isIntegerTy(64)) &&
14768        (SrcTy->getNumElements() == 16 || SrcTy->getNumElements() == 8))) {
14769     createTblForTrunc(TI, Subtarget->isLittleEndian());
14770     return true;
14771   }
14772 
14773   return false;
14774 }
14775 
14776 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
14777                                           Align &RequiredAligment) const {
14778   if (!LoadedType.isSimple() ||
14779       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
14780     return false;
14781   // Cyclone supports unaligned accesses.
14782   RequiredAligment = Align(1);
14783   unsigned NumBits = LoadedType.getSizeInBits();
14784   return NumBits == 32 || NumBits == 64;
14785 }
14786 
14787 /// A helper function for determining the number of interleaved accesses we
14788 /// will generate when lowering accesses of the given type.
14789 unsigned AArch64TargetLowering::getNumInterleavedAccesses(
14790     VectorType *VecTy, const DataLayout &DL, bool UseScalable) const {
14791   unsigned VecSize = 128;
14792   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14793   unsigned MinElts = VecTy->getElementCount().getKnownMinValue();
14794   if (UseScalable)
14795     VecSize = std::max(Subtarget->getMinSVEVectorSizeInBits(), 128u);
14796   return std::max<unsigned>(1, (MinElts * ElSize + 127) / VecSize);
14797 }
14798 
14799 MachineMemOperand::Flags
14800 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
14801   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
14802       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
14803     return MOStridedAccess;
14804   return MachineMemOperand::MONone;
14805 }
14806 
14807 bool AArch64TargetLowering::isLegalInterleavedAccessType(
14808     VectorType *VecTy, const DataLayout &DL, bool &UseScalable) const {
14809   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14810   auto EC = VecTy->getElementCount();
14811   unsigned MinElts = EC.getKnownMinValue();
14812 
14813   UseScalable = false;
14814 
14815   if (!VecTy->isScalableTy() && !Subtarget->hasNEON())
14816     return false;
14817 
14818   if (VecTy->isScalableTy() && !Subtarget->hasSVEorSME())
14819     return false;
14820 
14821   // Ensure that the predicate for this number of elements is available.
14822   if (Subtarget->hasSVE() && !getSVEPredPatternFromNumElements(MinElts))
14823     return false;
14824 
14825   // Ensure the number of vector elements is greater than 1.
14826   if (MinElts < 2)
14827     return false;
14828 
14829   // Ensure the element type is legal.
14830   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
14831     return false;
14832 
14833   if (EC.isScalable()) {
14834     UseScalable = true;
14835     return isPowerOf2_32(MinElts) && (MinElts * ElSize) % 128 == 0;
14836   }
14837 
14838   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14839   if (!Subtarget->isNeonAvailable() ||
14840       (Subtarget->useSVEForFixedLengthVectors() &&
14841        (VecSize % Subtarget->getMinSVEVectorSizeInBits() == 0 ||
14842         (VecSize < Subtarget->getMinSVEVectorSizeInBits() &&
14843          isPowerOf2_32(MinElts) && VecSize > 128)))) {
14844     UseScalable = true;
14845     return true;
14846   }
14847 
14848   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14849   // 128 will be split into multiple interleaved accesses.
14850   return VecSize == 64 || VecSize % 128 == 0;
14851 }
14852 
14853 static ScalableVectorType *getSVEContainerIRType(FixedVectorType *VTy) {
14854   if (VTy->getElementType() == Type::getDoubleTy(VTy->getContext()))
14855     return ScalableVectorType::get(VTy->getElementType(), 2);
14856 
14857   if (VTy->getElementType() == Type::getFloatTy(VTy->getContext()))
14858     return ScalableVectorType::get(VTy->getElementType(), 4);
14859 
14860   if (VTy->getElementType() == Type::getBFloatTy(VTy->getContext()))
14861     return ScalableVectorType::get(VTy->getElementType(), 8);
14862 
14863   if (VTy->getElementType() == Type::getHalfTy(VTy->getContext()))
14864     return ScalableVectorType::get(VTy->getElementType(), 8);
14865 
14866   if (VTy->getElementType() == Type::getInt64Ty(VTy->getContext()))
14867     return ScalableVectorType::get(VTy->getElementType(), 2);
14868 
14869   if (VTy->getElementType() == Type::getInt32Ty(VTy->getContext()))
14870     return ScalableVectorType::get(VTy->getElementType(), 4);
14871 
14872   if (VTy->getElementType() == Type::getInt16Ty(VTy->getContext()))
14873     return ScalableVectorType::get(VTy->getElementType(), 8);
14874 
14875   if (VTy->getElementType() == Type::getInt8Ty(VTy->getContext()))
14876     return ScalableVectorType::get(VTy->getElementType(), 16);
14877 
14878   llvm_unreachable("Cannot handle input vector type");
14879 }
14880 
14881 static Function *getStructuredLoadFunction(Module *M, unsigned Factor,
14882                                            bool Scalable, Type *LDVTy,
14883                                            Type *PtrTy) {
14884   assert(Factor >= 2 && Factor <= 4 && "Invalid interleave factor");
14885   static const Intrinsic::ID SVELoads[3] = {Intrinsic::aarch64_sve_ld2_sret,
14886                                             Intrinsic::aarch64_sve_ld3_sret,
14887                                             Intrinsic::aarch64_sve_ld4_sret};
14888   static const Intrinsic::ID NEONLoads[3] = {Intrinsic::aarch64_neon_ld2,
14889                                              Intrinsic::aarch64_neon_ld3,
14890                                              Intrinsic::aarch64_neon_ld4};
14891   if (Scalable)
14892     return Intrinsic::getDeclaration(M, SVELoads[Factor - 2], {LDVTy});
14893 
14894   return Intrinsic::getDeclaration(M, NEONLoads[Factor - 2], {LDVTy, PtrTy});
14895 }
14896 
14897 static Function *getStructuredStoreFunction(Module *M, unsigned Factor,
14898                                             bool Scalable, Type *STVTy,
14899                                             Type *PtrTy) {
14900   assert(Factor >= 2 && Factor <= 4 && "Invalid interleave factor");
14901   static const Intrinsic::ID SVEStores[3] = {Intrinsic::aarch64_sve_st2,
14902                                              Intrinsic::aarch64_sve_st3,
14903                                              Intrinsic::aarch64_sve_st4};
14904   static const Intrinsic::ID NEONStores[3] = {Intrinsic::aarch64_neon_st2,
14905                                               Intrinsic::aarch64_neon_st3,
14906                                               Intrinsic::aarch64_neon_st4};
14907   if (Scalable)
14908     return Intrinsic::getDeclaration(M, SVEStores[Factor - 2], {STVTy});
14909 
14910   return Intrinsic::getDeclaration(M, NEONStores[Factor - 2], {STVTy, PtrTy});
14911 }
14912 
14913 /// Lower an interleaved load into a ldN intrinsic.
14914 ///
14915 /// E.g. Lower an interleaved load (Factor = 2):
14916 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
14917 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14918 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14919 ///
14920 ///      Into:
14921 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
14922 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
14923 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
14924 bool AArch64TargetLowering::lowerInterleavedLoad(
14925     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14926     ArrayRef<unsigned> Indices, unsigned Factor) const {
14927   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14928          "Invalid interleave factor");
14929   assert(!Shuffles.empty() && "Empty shufflevector input");
14930   assert(Shuffles.size() == Indices.size() &&
14931          "Unmatched number of shufflevectors and indices");
14932 
14933   const DataLayout &DL = LI->getModule()->getDataLayout();
14934 
14935   VectorType *VTy = Shuffles[0]->getType();
14936 
14937   // Skip if we do not have NEON and skip illegal vector types. We can
14938   // "legalize" wide vector types into multiple interleaved accesses as long as
14939   // the vector types are divisible by 128.
14940   bool UseScalable;
14941   if (!Subtarget->hasNEON() ||
14942       !isLegalInterleavedAccessType(VTy, DL, UseScalable))
14943     return false;
14944 
14945   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL, UseScalable);
14946 
14947   auto *FVTy = cast<FixedVectorType>(VTy);
14948 
14949   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14950   // load integer vectors first and then convert to pointer vectors.
14951   Type *EltTy = FVTy->getElementType();
14952   if (EltTy->isPointerTy())
14953     FVTy =
14954         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
14955 
14956   // If we're going to generate more than one load, reset the sub-vector type
14957   // to something legal.
14958   FVTy = FixedVectorType::get(FVTy->getElementType(),
14959                               FVTy->getNumElements() / NumLoads);
14960 
14961   auto *LDVTy =
14962       UseScalable ? cast<VectorType>(getSVEContainerIRType(FVTy)) : FVTy;
14963 
14964   IRBuilder<> Builder(LI);
14965 
14966   // The base address of the load.
14967   Value *BaseAddr = LI->getPointerOperand();
14968 
14969   if (NumLoads > 1) {
14970     // We will compute the pointer operand of each load from the original base
14971     // address using GEPs. Cast the base address to a pointer to the scalar
14972     // element type.
14973     BaseAddr = Builder.CreateBitCast(
14974         BaseAddr,
14975         LDVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
14976   }
14977 
14978   Type *PtrTy = LI->getPointerOperandType();
14979   Type *PredTy = VectorType::get(Type::getInt1Ty(LDVTy->getContext()),
14980                                  LDVTy->getElementCount());
14981 
14982   Function *LdNFunc = getStructuredLoadFunction(LI->getModule(), Factor,
14983                                                 UseScalable, LDVTy, PtrTy);
14984 
14985   // Holds sub-vectors extracted from the load intrinsic return values. The
14986   // sub-vectors are associated with the shufflevector instructions they will
14987   // replace.
14988   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14989 
14990   Value *PTrue = nullptr;
14991   if (UseScalable) {
14992     std::optional<unsigned> PgPattern =
14993         getSVEPredPatternFromNumElements(FVTy->getNumElements());
14994     if (Subtarget->getMinSVEVectorSizeInBits() ==
14995             Subtarget->getMaxSVEVectorSizeInBits() &&
14996         Subtarget->getMinSVEVectorSizeInBits() == DL.getTypeSizeInBits(FVTy))
14997       PgPattern = AArch64SVEPredPattern::all;
14998 
14999     auto *PTruePat =
15000         ConstantInt::get(Type::getInt32Ty(LDVTy->getContext()), *PgPattern);
15001     PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue, {PredTy},
15002                                     {PTruePat});
15003   }
15004 
15005   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
15006 
15007     // If we're generating more than one load, compute the base address of
15008     // subsequent loads as an offset from the previous.
15009     if (LoadCount > 0)
15010       BaseAddr = Builder.CreateConstGEP1_32(LDVTy->getElementType(), BaseAddr,
15011                                             FVTy->getNumElements() * Factor);
15012 
15013     CallInst *LdN;
15014     if (UseScalable)
15015       LdN = Builder.CreateCall(
15016           LdNFunc, {PTrue, Builder.CreateBitCast(BaseAddr, PtrTy)}, "ldN");
15017     else
15018       LdN = Builder.CreateCall(LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy),
15019                                "ldN");
15020 
15021     // Extract and store the sub-vectors returned by the load intrinsic.
15022     for (unsigned i = 0; i < Shuffles.size(); i++) {
15023       ShuffleVectorInst *SVI = Shuffles[i];
15024       unsigned Index = Indices[i];
15025 
15026       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
15027 
15028       if (UseScalable)
15029         SubVec = Builder.CreateExtractVector(
15030             FVTy, SubVec,
15031             ConstantInt::get(Type::getInt64Ty(VTy->getContext()), 0));
15032 
15033       // Convert the integer vector to pointer vector if the element is pointer.
15034       if (EltTy->isPointerTy())
15035         SubVec = Builder.CreateIntToPtr(
15036             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
15037                                          FVTy->getNumElements()));
15038 
15039       SubVecs[SVI].push_back(SubVec);
15040     }
15041   }
15042 
15043   // Replace uses of the shufflevector instructions with the sub-vectors
15044   // returned by the load intrinsic. If a shufflevector instruction is
15045   // associated with more than one sub-vector, those sub-vectors will be
15046   // concatenated into a single wide vector.
15047   for (ShuffleVectorInst *SVI : Shuffles) {
15048     auto &SubVec = SubVecs[SVI];
15049     auto *WideVec =
15050         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
15051     SVI->replaceAllUsesWith(WideVec);
15052   }
15053 
15054   return true;
15055 }
15056 
15057 /// Lower an interleaved store into a stN intrinsic.
15058 ///
15059 /// E.g. Lower an interleaved store (Factor = 3):
15060 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
15061 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
15062 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
15063 ///
15064 ///      Into:
15065 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
15066 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
15067 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
15068 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
15069 ///
15070 /// Note that the new shufflevectors will be removed and we'll only generate one
15071 /// st3 instruction in CodeGen.
15072 ///
15073 /// Example for a more general valid mask (Factor 3). Lower:
15074 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
15075 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
15076 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
15077 ///
15078 ///      Into:
15079 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
15080 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
15081 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
15082 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
15083 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
15084                                                   ShuffleVectorInst *SVI,
15085                                                   unsigned Factor) const {
15086 
15087   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
15088          "Invalid interleave factor");
15089 
15090   auto *VecTy = cast<FixedVectorType>(SVI->getType());
15091   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
15092 
15093   unsigned LaneLen = VecTy->getNumElements() / Factor;
15094   Type *EltTy = VecTy->getElementType();
15095   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
15096 
15097   const DataLayout &DL = SI->getModule()->getDataLayout();
15098   bool UseScalable;
15099 
15100   // Skip if we do not have NEON and skip illegal vector types. We can
15101   // "legalize" wide vector types into multiple interleaved accesses as long as
15102   // the vector types are divisible by 128.
15103   if (!Subtarget->hasNEON() ||
15104       !isLegalInterleavedAccessType(SubVecTy, DL, UseScalable))
15105     return false;
15106 
15107   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
15108 
15109   Value *Op0 = SVI->getOperand(0);
15110   Value *Op1 = SVI->getOperand(1);
15111   IRBuilder<> Builder(SI);
15112 
15113   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
15114   // vectors to integer vectors.
15115   if (EltTy->isPointerTy()) {
15116     Type *IntTy = DL.getIntPtrType(EltTy);
15117     unsigned NumOpElts =
15118         cast<FixedVectorType>(Op0->getType())->getNumElements();
15119 
15120     // Convert to the corresponding integer vector.
15121     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
15122     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
15123     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
15124 
15125     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
15126   }
15127 
15128   // If we're going to generate more than one store, reset the lane length
15129   // and sub-vector type to something legal.
15130   LaneLen /= NumStores;
15131   SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
15132 
15133   auto *STVTy = UseScalable ? cast<VectorType>(getSVEContainerIRType(SubVecTy))
15134                             : SubVecTy;
15135 
15136   // The base address of the store.
15137   Value *BaseAddr = SI->getPointerOperand();
15138 
15139   if (NumStores > 1) {
15140     // We will compute the pointer operand of each store from the original base
15141     // address using GEPs. Cast the base address to a pointer to the scalar
15142     // element type.
15143     BaseAddr = Builder.CreateBitCast(
15144         BaseAddr,
15145         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
15146   }
15147 
15148   auto Mask = SVI->getShuffleMask();
15149 
15150   // Sanity check if all the indices are NOT in range.
15151   // If mask is `poison`, `Mask` may be a vector of -1s.
15152   // If all of them are `poison`, OOB read will happen later.
15153   if (llvm::all_of(Mask, [](int Idx) { return Idx == PoisonMaskElem; })) {
15154     return false;
15155   }
15156   // A 64bit st2 which does not start at element 0 will involved adding extra
15157   // ext elements, making the st2 unprofitable.
15158   if (Factor == 2 && SubVecTy->getPrimitiveSizeInBits() == 64 && Mask[0] != 0)
15159     return false;
15160 
15161   Type *PtrTy = SI->getPointerOperandType();
15162   Type *PredTy = VectorType::get(Type::getInt1Ty(STVTy->getContext()),
15163                                  STVTy->getElementCount());
15164 
15165   Function *StNFunc = getStructuredStoreFunction(SI->getModule(), Factor,
15166                                                  UseScalable, STVTy, PtrTy);
15167 
15168   Value *PTrue = nullptr;
15169   if (UseScalable) {
15170     std::optional<unsigned> PgPattern =
15171         getSVEPredPatternFromNumElements(SubVecTy->getNumElements());
15172     if (Subtarget->getMinSVEVectorSizeInBits() ==
15173             Subtarget->getMaxSVEVectorSizeInBits() &&
15174         Subtarget->getMinSVEVectorSizeInBits() ==
15175             DL.getTypeSizeInBits(SubVecTy))
15176       PgPattern = AArch64SVEPredPattern::all;
15177 
15178     auto *PTruePat =
15179         ConstantInt::get(Type::getInt32Ty(STVTy->getContext()), *PgPattern);
15180     PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue, {PredTy},
15181                                     {PTruePat});
15182   }
15183 
15184   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
15185 
15186     SmallVector<Value *, 5> Ops;
15187 
15188     // Split the shufflevector operands into sub vectors for the new stN call.
15189     for (unsigned i = 0; i < Factor; i++) {
15190       Value *Shuffle;
15191       unsigned IdxI = StoreCount * LaneLen * Factor + i;
15192       if (Mask[IdxI] >= 0) {
15193         Shuffle = Builder.CreateShuffleVector(
15194             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0));
15195       } else {
15196         unsigned StartMask = 0;
15197         for (unsigned j = 1; j < LaneLen; j++) {
15198           unsigned IdxJ = StoreCount * LaneLen * Factor + j * Factor + i;
15199           if (Mask[IdxJ] >= 0) {
15200             StartMask = Mask[IdxJ] - j;
15201             break;
15202           }
15203         }
15204         // Note: Filling undef gaps with random elements is ok, since
15205         // those elements were being written anyway (with undefs).
15206         // In the case of all undefs we're defaulting to using elems from 0
15207         // Note: StartMask cannot be negative, it's checked in
15208         // isReInterleaveMask
15209         Shuffle = Builder.CreateShuffleVector(
15210             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0));
15211       }
15212 
15213       if (UseScalable)
15214         Shuffle = Builder.CreateInsertVector(
15215             STVTy, UndefValue::get(STVTy), Shuffle,
15216             ConstantInt::get(Type::getInt64Ty(STVTy->getContext()), 0));
15217 
15218       Ops.push_back(Shuffle);
15219     }
15220 
15221     if (UseScalable)
15222       Ops.push_back(PTrue);
15223 
15224     // If we generating more than one store, we compute the base address of
15225     // subsequent stores as an offset from the previous.
15226     if (StoreCount > 0)
15227       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
15228                                             BaseAddr, LaneLen * Factor);
15229 
15230     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
15231     Builder.CreateCall(StNFunc, Ops);
15232   }
15233   return true;
15234 }
15235 
15236 bool AArch64TargetLowering::lowerDeinterleaveIntrinsicToLoad(
15237     IntrinsicInst *DI, LoadInst *LI) const {
15238   // Only deinterleave2 supported at present.
15239   if (DI->getIntrinsicID() != Intrinsic::experimental_vector_deinterleave2)
15240     return false;
15241 
15242   // Only a factor of 2 supported at present.
15243   const unsigned Factor = 2;
15244 
15245   VectorType *VTy = cast<VectorType>(DI->getType()->getContainedType(0));
15246   const DataLayout &DL = DI->getModule()->getDataLayout();
15247   bool UseScalable;
15248   if (!isLegalInterleavedAccessType(VTy, DL, UseScalable))
15249     return false;
15250 
15251   // TODO: Add support for using SVE instructions with fixed types later, using
15252   // the code from lowerInterleavedLoad to obtain the correct container type.
15253   if (UseScalable && !VTy->isScalableTy())
15254     return false;
15255 
15256   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL, UseScalable);
15257 
15258   VectorType *LdTy =
15259       VectorType::get(VTy->getElementType(),
15260                       VTy->getElementCount().divideCoefficientBy(NumLoads));
15261 
15262   Type *PtrTy = LI->getPointerOperandType();
15263   Function *LdNFunc = getStructuredLoadFunction(DI->getModule(), Factor,
15264                                                 UseScalable, LdTy, PtrTy);
15265 
15266   IRBuilder<> Builder(LI);
15267 
15268   Value *Pred = nullptr;
15269   if (UseScalable)
15270     Pred =
15271         Builder.CreateVectorSplat(LdTy->getElementCount(), Builder.getTrue());
15272 
15273   Value *BaseAddr = LI->getPointerOperand();
15274   Value *Result;
15275   if (NumLoads > 1) {
15276     Value *Left = PoisonValue::get(VTy);
15277     Value *Right = PoisonValue::get(VTy);
15278 
15279     for (unsigned I = 0; I < NumLoads; ++I) {
15280       Value *Offset = Builder.getInt64(I * Factor);
15281 
15282       Value *Address = Builder.CreateGEP(LdTy, BaseAddr, {Offset});
15283       Value *LdN = nullptr;
15284       if (UseScalable)
15285         LdN = Builder.CreateCall(LdNFunc, {Pred, Address}, "ldN");
15286       else
15287         LdN = Builder.CreateCall(LdNFunc, Address, "ldN");
15288 
15289       Value *Idx =
15290           Builder.getInt64(I * LdTy->getElementCount().getKnownMinValue());
15291       Left = Builder.CreateInsertVector(
15292           VTy, Left, Builder.CreateExtractValue(LdN, 0), Idx);
15293       Right = Builder.CreateInsertVector(
15294           VTy, Right, Builder.CreateExtractValue(LdN, 1), Idx);
15295     }
15296 
15297     Result = PoisonValue::get(DI->getType());
15298     Result = Builder.CreateInsertValue(Result, Left, 0);
15299     Result = Builder.CreateInsertValue(Result, Right, 1);
15300   } else {
15301     if (UseScalable)
15302       Result = Builder.CreateCall(LdNFunc, {Pred, BaseAddr}, "ldN");
15303     else
15304       Result = Builder.CreateCall(LdNFunc, BaseAddr, "ldN");
15305   }
15306 
15307   DI->replaceAllUsesWith(Result);
15308   return true;
15309 }
15310 
15311 bool AArch64TargetLowering::lowerInterleaveIntrinsicToStore(
15312     IntrinsicInst *II, StoreInst *SI) const {
15313   // Only interleave2 supported at present.
15314   if (II->getIntrinsicID() != Intrinsic::experimental_vector_interleave2)
15315     return false;
15316 
15317   // Only a factor of 2 supported at present.
15318   const unsigned Factor = 2;
15319 
15320   VectorType *VTy = cast<VectorType>(II->getOperand(0)->getType());
15321   const DataLayout &DL = II->getModule()->getDataLayout();
15322   bool UseScalable;
15323   if (!isLegalInterleavedAccessType(VTy, DL, UseScalable))
15324     return false;
15325 
15326   // TODO: Add support for using SVE instructions with fixed types later, using
15327   // the code from lowerInterleavedStore to obtain the correct container type.
15328   if (UseScalable && !VTy->isScalableTy())
15329     return false;
15330 
15331   unsigned NumStores = getNumInterleavedAccesses(VTy, DL, UseScalable);
15332 
15333   VectorType *StTy =
15334       VectorType::get(VTy->getElementType(),
15335                       VTy->getElementCount().divideCoefficientBy(NumStores));
15336 
15337   Type *PtrTy = SI->getPointerOperandType();
15338   Function *StNFunc = getStructuredStoreFunction(SI->getModule(), Factor,
15339                                                  UseScalable, StTy, PtrTy);
15340 
15341   IRBuilder<> Builder(SI);
15342 
15343   Value *BaseAddr = SI->getPointerOperand();
15344   Value *Pred = nullptr;
15345 
15346   if (UseScalable)
15347     Pred =
15348         Builder.CreateVectorSplat(StTy->getElementCount(), Builder.getTrue());
15349 
15350   Value *L = II->getOperand(0);
15351   Value *R = II->getOperand(1);
15352 
15353   for (unsigned I = 0; I < NumStores; ++I) {
15354     Value *Address = BaseAddr;
15355     if (NumStores > 1) {
15356       Value *Offset = Builder.getInt64(I * Factor);
15357       Address = Builder.CreateGEP(StTy, BaseAddr, {Offset});
15358 
15359       Value *Idx =
15360           Builder.getInt64(I * StTy->getElementCount().getKnownMinValue());
15361       L = Builder.CreateExtractVector(StTy, II->getOperand(0), Idx);
15362       R = Builder.CreateExtractVector(StTy, II->getOperand(1), Idx);
15363     }
15364 
15365     if (UseScalable)
15366       Builder.CreateCall(StNFunc, {L, R, Pred, Address});
15367     else
15368       Builder.CreateCall(StNFunc, {L, R, Address});
15369   }
15370 
15371   return true;
15372 }
15373 
15374 EVT AArch64TargetLowering::getOptimalMemOpType(
15375     const MemOp &Op, const AttributeList &FuncAttributes) const {
15376   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
15377   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
15378   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
15379   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
15380   // taken one instruction to materialize the v2i64 zero and one store (with
15381   // restrictive addressing mode). Just do i64 stores.
15382   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
15383   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
15384     if (Op.isAligned(AlignCheck))
15385       return true;
15386     unsigned Fast;
15387     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
15388                                           MachineMemOperand::MONone, &Fast) &&
15389            Fast;
15390   };
15391 
15392   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
15393       AlignmentIsAcceptable(MVT::v16i8, Align(16)))
15394     return MVT::v16i8;
15395   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
15396     return MVT::f128;
15397   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
15398     return MVT::i64;
15399   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
15400     return MVT::i32;
15401   return MVT::Other;
15402 }
15403 
15404 LLT AArch64TargetLowering::getOptimalMemOpLLT(
15405     const MemOp &Op, const AttributeList &FuncAttributes) const {
15406   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
15407   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
15408   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
15409   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
15410   // taken one instruction to materialize the v2i64 zero and one store (with
15411   // restrictive addressing mode). Just do i64 stores.
15412   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
15413   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
15414     if (Op.isAligned(AlignCheck))
15415       return true;
15416     unsigned Fast;
15417     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
15418                                           MachineMemOperand::MONone, &Fast) &&
15419            Fast;
15420   };
15421 
15422   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
15423       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
15424     return LLT::fixed_vector(2, 64);
15425   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
15426     return LLT::scalar(128);
15427   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
15428     return LLT::scalar(64);
15429   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
15430     return LLT::scalar(32);
15431   return LLT();
15432 }
15433 
15434 // 12-bit optionally shifted immediates are legal for adds.
15435 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
15436   if (Immed == std::numeric_limits<int64_t>::min()) {
15437     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
15438                       << ": avoid UB for INT64_MIN\n");
15439     return false;
15440   }
15441   // Same encoding for add/sub, just flip the sign.
15442   Immed = std::abs(Immed);
15443   bool IsLegal = ((Immed >> 12) == 0 ||
15444                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
15445   LLVM_DEBUG(dbgs() << "Is " << Immed
15446                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
15447   return IsLegal;
15448 }
15449 
15450 // Return false to prevent folding
15451 // (mul (add x, c1), c2) -> (add (mul x, c2), c2*c1) in DAGCombine,
15452 // if the folding leads to worse code.
15453 bool AArch64TargetLowering::isMulAddWithConstProfitable(
15454     SDValue AddNode, SDValue ConstNode) const {
15455   // Let the DAGCombiner decide for vector types and large types.
15456   const EVT VT = AddNode.getValueType();
15457   if (VT.isVector() || VT.getScalarSizeInBits() > 64)
15458     return true;
15459 
15460   // It is worse if c1 is legal add immediate, while c1*c2 is not
15461   // and has to be composed by at least two instructions.
15462   const ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
15463   const ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
15464   const int64_t C1 = C1Node->getSExtValue();
15465   const APInt C1C2 = C1Node->getAPIntValue() * C2Node->getAPIntValue();
15466   if (!isLegalAddImmediate(C1) || isLegalAddImmediate(C1C2.getSExtValue()))
15467     return true;
15468   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
15469   // Adapt to the width of a register.
15470   unsigned BitSize = VT.getSizeInBits() <= 32 ? 32 : 64;
15471   AArch64_IMM::expandMOVImm(C1C2.getZExtValue(), BitSize, Insn);
15472   if (Insn.size() > 1)
15473     return false;
15474 
15475   // Default to true and let the DAGCombiner decide.
15476   return true;
15477 }
15478 
15479 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
15480 // immediates is the same as for an add or a sub.
15481 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
15482   return isLegalAddImmediate(Immed);
15483 }
15484 
15485 /// isLegalAddressingMode - Return true if the addressing mode represented
15486 /// by AM is legal for this target, for a load/store of the specified type.
15487 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
15488                                                   const AddrMode &AMode, Type *Ty,
15489                                                   unsigned AS, Instruction *I) const {
15490   // AArch64 has five basic addressing modes:
15491   //  reg
15492   //  reg + 9-bit signed offset
15493   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
15494   //  reg1 + reg2
15495   //  reg + SIZE_IN_BYTES * reg
15496 
15497   // No global is ever allowed as a base.
15498   if (AMode.BaseGV)
15499     return false;
15500 
15501   // No reg+reg+imm addressing.
15502   if (AMode.HasBaseReg && AMode.BaseOffs && AMode.Scale)
15503     return false;
15504 
15505   // Canonicalise `1*ScaledReg + imm` into `BaseReg + imm` and
15506   // `2*ScaledReg` into `BaseReg + ScaledReg`
15507   AddrMode AM = AMode;
15508   if (AM.Scale && !AM.HasBaseReg) {
15509     if (AM.Scale == 1) {
15510       AM.HasBaseReg = true;
15511       AM.Scale = 0;
15512     } else if (AM.Scale == 2) {
15513       AM.HasBaseReg = true;
15514       AM.Scale = 1;
15515     } else {
15516       return false;
15517     }
15518   }
15519 
15520   // A base register is required in all addressing modes.
15521   if (!AM.HasBaseReg)
15522     return false;
15523 
15524   if (Ty->isScalableTy()) {
15525     if (isa<ScalableVectorType>(Ty)) {
15526       uint64_t VecElemNumBytes =
15527           DL.getTypeSizeInBits(cast<VectorType>(Ty)->getElementType()) / 8;
15528       return AM.HasBaseReg && !AM.BaseOffs &&
15529              (AM.Scale == 0 || (uint64_t)AM.Scale == VecElemNumBytes);
15530     }
15531 
15532     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
15533   }
15534 
15535   // check reg + imm case:
15536   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
15537   uint64_t NumBytes = 0;
15538   if (Ty->isSized()) {
15539     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
15540     NumBytes = NumBits / 8;
15541     if (!isPowerOf2_64(NumBits))
15542       NumBytes = 0;
15543   }
15544 
15545   if (!AM.Scale) {
15546     int64_t Offset = AM.BaseOffs;
15547 
15548     // 9-bit signed offset
15549     if (isInt<9>(Offset))
15550       return true;
15551 
15552     // 12-bit unsigned offset
15553     unsigned shift = Log2_64(NumBytes);
15554     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
15555         // Must be a multiple of NumBytes (NumBytes is a power of 2)
15556         (Offset >> shift) << shift == Offset)
15557       return true;
15558     return false;
15559   }
15560 
15561   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
15562 
15563   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
15564 }
15565 
15566 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
15567   // Consider splitting large offset of struct or array.
15568   return true;
15569 }
15570 
15571 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
15572     const MachineFunction &MF, EVT VT) const {
15573   VT = VT.getScalarType();
15574 
15575   if (!VT.isSimple())
15576     return false;
15577 
15578   switch (VT.getSimpleVT().SimpleTy) {
15579   case MVT::f16:
15580     return Subtarget->hasFullFP16();
15581   case MVT::f32:
15582   case MVT::f64:
15583     return true;
15584   default:
15585     break;
15586   }
15587 
15588   return false;
15589 }
15590 
15591 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15592                                                        Type *Ty) const {
15593   switch (Ty->getScalarType()->getTypeID()) {
15594   case Type::FloatTyID:
15595   case Type::DoubleTyID:
15596     return true;
15597   default:
15598     return false;
15599   }
15600 }
15601 
15602 bool AArch64TargetLowering::generateFMAsInMachineCombiner(
15603     EVT VT, CodeGenOpt::Level OptLevel) const {
15604   return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector() &&
15605          !useSVEForFixedLengthVectorVT(VT);
15606 }
15607 
15608 const MCPhysReg *
15609 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
15610   // LR is a callee-save register, but we must treat it as clobbered by any call
15611   // site. Hence we include LR in the scratch registers, which are in turn added
15612   // as implicit-defs for stackmaps and patchpoints.
15613   static const MCPhysReg ScratchRegs[] = {
15614     AArch64::X16, AArch64::X17, AArch64::LR, 0
15615   };
15616   return ScratchRegs;
15617 }
15618 
15619 ArrayRef<MCPhysReg> AArch64TargetLowering::getRoundingControlRegisters() const {
15620   static const MCPhysReg RCRegs[] = {AArch64::FPCR};
15621   return RCRegs;
15622 }
15623 
15624 bool
15625 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
15626                                                      CombineLevel Level) const {
15627   assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
15628           N->getOpcode() == ISD::SRL) &&
15629          "Expected shift op");
15630 
15631   SDValue ShiftLHS = N->getOperand(0);
15632   EVT VT = N->getValueType(0);
15633 
15634   // If ShiftLHS is unsigned bit extraction: ((x >> C) & mask), then do not
15635   // combine it with shift 'N' to let it be lowered to UBFX except:
15636   // ((x >> C) & mask) << C.
15637   if (ShiftLHS.getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
15638       isa<ConstantSDNode>(ShiftLHS.getOperand(1))) {
15639     uint64_t TruncMask = ShiftLHS.getConstantOperandVal(1);
15640     if (isMask_64(TruncMask)) {
15641       SDValue AndLHS = ShiftLHS.getOperand(0);
15642       if (AndLHS.getOpcode() == ISD::SRL) {
15643         if (auto *SRLC = dyn_cast<ConstantSDNode>(AndLHS.getOperand(1))) {
15644           if (N->getOpcode() == ISD::SHL)
15645             if (auto *SHLC = dyn_cast<ConstantSDNode>(N->getOperand(1)))
15646               return SRLC->getZExtValue() == SHLC->getZExtValue();
15647           return false;
15648         }
15649       }
15650     }
15651   }
15652   return true;
15653 }
15654 
15655 bool AArch64TargetLowering::isDesirableToCommuteXorWithShift(
15656     const SDNode *N) const {
15657   assert(N->getOpcode() == ISD::XOR &&
15658          (N->getOperand(0).getOpcode() == ISD::SHL ||
15659           N->getOperand(0).getOpcode() == ISD::SRL) &&
15660          "Expected XOR(SHIFT) pattern");
15661 
15662   // Only commute if the entire NOT mask is a hidden shifted mask.
15663   auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
15664   auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
15665   if (XorC && ShiftC) {
15666     unsigned MaskIdx, MaskLen;
15667     if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
15668       unsigned ShiftAmt = ShiftC->getZExtValue();
15669       unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
15670       if (N->getOperand(0).getOpcode() == ISD::SHL)
15671         return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
15672       return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
15673     }
15674   }
15675 
15676   return false;
15677 }
15678 
15679 bool AArch64TargetLowering::shouldFoldConstantShiftPairToMask(
15680     const SDNode *N, CombineLevel Level) const {
15681   assert(((N->getOpcode() == ISD::SHL &&
15682            N->getOperand(0).getOpcode() == ISD::SRL) ||
15683           (N->getOpcode() == ISD::SRL &&
15684            N->getOperand(0).getOpcode() == ISD::SHL)) &&
15685          "Expected shift-shift mask");
15686   // Don't allow multiuse shift folding with the same shift amount.
15687   if (!N->getOperand(0)->hasOneUse())
15688     return false;
15689 
15690   // Only fold srl(shl(x,c1),c2) iff C1 >= C2 to prevent loss of UBFX patterns.
15691   EVT VT = N->getValueType(0);
15692   if (N->getOpcode() == ISD::SRL && (VT == MVT::i32 || VT == MVT::i64)) {
15693     auto *C1 = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
15694     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15695     return (!C1 || !C2 || C1->getZExtValue() >= C2->getZExtValue());
15696   }
15697 
15698   return true;
15699 }
15700 
15701 bool AArch64TargetLowering::shouldFoldSelectWithIdentityConstant(
15702     unsigned BinOpcode, EVT VT) const {
15703   return VT.isScalableVector() && isTypeLegal(VT);
15704 }
15705 
15706 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15707                                                               Type *Ty) const {
15708   assert(Ty->isIntegerTy());
15709 
15710   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15711   if (BitSize == 0)
15712     return false;
15713 
15714   int64_t Val = Imm.getSExtValue();
15715   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
15716     return true;
15717 
15718   if ((int64_t)Val < 0)
15719     Val = ~Val;
15720   if (BitSize == 32)
15721     Val &= (1LL << 32) - 1;
15722 
15723   unsigned Shift = llvm::Log2_64((uint64_t)Val) / 16;
15724   // MOVZ is free so return true for one or fewer MOVK.
15725   return Shift < 3;
15726 }
15727 
15728 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15729                                                     unsigned Index) const {
15730   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15731     return false;
15732 
15733   return (Index == 0 || Index == ResVT.getVectorMinNumElements());
15734 }
15735 
15736 /// Turn vector tests of the signbit in the form of:
15737 ///   xor (sra X, elt_size(X)-1), -1
15738 /// into:
15739 ///   cmge X, X, #0
15740 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
15741                                          const AArch64Subtarget *Subtarget) {
15742   EVT VT = N->getValueType(0);
15743   if (!Subtarget->hasNEON() || !VT.isVector())
15744     return SDValue();
15745 
15746   // There must be a shift right algebraic before the xor, and the xor must be a
15747   // 'not' operation.
15748   SDValue Shift = N->getOperand(0);
15749   SDValue Ones = N->getOperand(1);
15750   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
15751       !ISD::isBuildVectorAllOnes(Ones.getNode()))
15752     return SDValue();
15753 
15754   // The shift should be smearing the sign bit across each vector element.
15755   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
15756   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
15757   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
15758     return SDValue();
15759 
15760   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
15761 }
15762 
15763 // Given a vecreduce_add node, detect the below pattern and convert it to the
15764 // node sequence with UABDL, [S|U]ADB and UADDLP.
15765 //
15766 // i32 vecreduce_add(
15767 //  v16i32 abs(
15768 //    v16i32 sub(
15769 //     v16i32 [sign|zero]_extend(v16i8 a), v16i32 [sign|zero]_extend(v16i8 b))))
15770 // =================>
15771 // i32 vecreduce_add(
15772 //   v4i32 UADDLP(
15773 //     v8i16 add(
15774 //       v8i16 zext(
15775 //         v8i8 [S|U]ABD low8:v16i8 a, low8:v16i8 b
15776 //       v8i16 zext(
15777 //         v8i8 [S|U]ABD high8:v16i8 a, high8:v16i8 b
15778 static SDValue performVecReduceAddCombineWithUADDLP(SDNode *N,
15779                                                     SelectionDAG &DAG) {
15780   // Assumed i32 vecreduce_add
15781   if (N->getValueType(0) != MVT::i32)
15782     return SDValue();
15783 
15784   SDValue VecReduceOp0 = N->getOperand(0);
15785   unsigned Opcode = VecReduceOp0.getOpcode();
15786   // Assumed v16i32 abs
15787   if (Opcode != ISD::ABS || VecReduceOp0->getValueType(0) != MVT::v16i32)
15788     return SDValue();
15789 
15790   SDValue ABS = VecReduceOp0;
15791   // Assumed v16i32 sub
15792   if (ABS->getOperand(0)->getOpcode() != ISD::SUB ||
15793       ABS->getOperand(0)->getValueType(0) != MVT::v16i32)
15794     return SDValue();
15795 
15796   SDValue SUB = ABS->getOperand(0);
15797   unsigned Opcode0 = SUB->getOperand(0).getOpcode();
15798   unsigned Opcode1 = SUB->getOperand(1).getOpcode();
15799   // Assumed v16i32 type
15800   if (SUB->getOperand(0)->getValueType(0) != MVT::v16i32 ||
15801       SUB->getOperand(1)->getValueType(0) != MVT::v16i32)
15802     return SDValue();
15803 
15804   // Assumed zext or sext
15805   bool IsZExt = false;
15806   if (Opcode0 == ISD::ZERO_EXTEND && Opcode1 == ISD::ZERO_EXTEND) {
15807     IsZExt = true;
15808   } else if (Opcode0 == ISD::SIGN_EXTEND && Opcode1 == ISD::SIGN_EXTEND) {
15809     IsZExt = false;
15810   } else
15811     return SDValue();
15812 
15813   SDValue EXT0 = SUB->getOperand(0);
15814   SDValue EXT1 = SUB->getOperand(1);
15815   // Assumed zext's operand has v16i8 type
15816   if (EXT0->getOperand(0)->getValueType(0) != MVT::v16i8 ||
15817       EXT1->getOperand(0)->getValueType(0) != MVT::v16i8)
15818     return SDValue();
15819 
15820   // Pattern is dectected. Let's convert it to sequence of nodes.
15821   SDLoc DL(N);
15822 
15823   // First, create the node pattern of UABD/SABD.
15824   SDValue UABDHigh8Op0 =
15825       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
15826                   DAG.getConstant(8, DL, MVT::i64));
15827   SDValue UABDHigh8Op1 =
15828       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
15829                   DAG.getConstant(8, DL, MVT::i64));
15830   SDValue UABDHigh8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
15831                                   UABDHigh8Op0, UABDHigh8Op1);
15832   SDValue UABDL = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDHigh8);
15833 
15834   // Second, create the node pattern of UABAL.
15835   SDValue UABDLo8Op0 =
15836       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
15837                   DAG.getConstant(0, DL, MVT::i64));
15838   SDValue UABDLo8Op1 =
15839       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
15840                   DAG.getConstant(0, DL, MVT::i64));
15841   SDValue UABDLo8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
15842                                 UABDLo8Op0, UABDLo8Op1);
15843   SDValue ZExtUABD = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDLo8);
15844   SDValue UABAL = DAG.getNode(ISD::ADD, DL, MVT::v8i16, UABDL, ZExtUABD);
15845 
15846   // Third, create the node of UADDLP.
15847   SDValue UADDLP = DAG.getNode(AArch64ISD::UADDLP, DL, MVT::v4i32, UABAL);
15848 
15849   // Fourth, create the node of VECREDUCE_ADD.
15850   return DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, UADDLP);
15851 }
15852 
15853 // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce
15854 //   vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one))
15855 //   vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B))
15856 // If we have vectors larger than v16i8 we extract v16i8 vectors,
15857 // Follow the same steps above to get DOT instructions concatenate them
15858 // and generate vecreduce.add(concat_vector(DOT, DOT2, ..)).
15859 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
15860                                           const AArch64Subtarget *ST) {
15861   if (!ST->hasDotProd())
15862     return performVecReduceAddCombineWithUADDLP(N, DAG);
15863 
15864   SDValue Op0 = N->getOperand(0);
15865   if (N->getValueType(0) != MVT::i32 ||
15866       Op0.getValueType().getVectorElementType() != MVT::i32)
15867     return SDValue();
15868 
15869   unsigned ExtOpcode = Op0.getOpcode();
15870   SDValue A = Op0;
15871   SDValue B;
15872   if (ExtOpcode == ISD::MUL) {
15873     A = Op0.getOperand(0);
15874     B = Op0.getOperand(1);
15875     if (A.getOpcode() != B.getOpcode() ||
15876         A.getOperand(0).getValueType() != B.getOperand(0).getValueType())
15877       return SDValue();
15878     ExtOpcode = A.getOpcode();
15879   }
15880   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
15881     return SDValue();
15882 
15883   EVT Op0VT = A.getOperand(0).getValueType();
15884   bool IsValidElementCount = Op0VT.getVectorNumElements() % 8 == 0;
15885   bool IsValidSize = Op0VT.getScalarSizeInBits() == 8;
15886   if (!IsValidElementCount || !IsValidSize)
15887     return SDValue();
15888 
15889   SDLoc DL(Op0);
15890   // For non-mla reductions B can be set to 1. For MLA we take the operand of
15891   // the extend B.
15892   if (!B)
15893     B = DAG.getConstant(1, DL, Op0VT);
15894   else
15895     B = B.getOperand(0);
15896 
15897   unsigned IsMultipleOf16 = Op0VT.getVectorNumElements() % 16 == 0;
15898   unsigned NumOfVecReduce;
15899   EVT TargetType;
15900   if (IsMultipleOf16) {
15901     NumOfVecReduce = Op0VT.getVectorNumElements() / 16;
15902     TargetType = MVT::v4i32;
15903   } else {
15904     NumOfVecReduce = Op0VT.getVectorNumElements() / 8;
15905     TargetType = MVT::v2i32;
15906   }
15907   auto DotOpcode =
15908       (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT;
15909   // Handle the case where we need to generate only one Dot operation.
15910   if (NumOfVecReduce == 1) {
15911     SDValue Zeros = DAG.getConstant(0, DL, TargetType);
15912     SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros,
15913                               A.getOperand(0), B);
15914     return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
15915   }
15916   // Generate Dot instructions that are multiple of 16.
15917   unsigned VecReduce16Num = Op0VT.getVectorNumElements() / 16;
15918   SmallVector<SDValue, 4> SDotVec16;
15919   unsigned I = 0;
15920   for (; I < VecReduce16Num; I += 1) {
15921     SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32);
15922     SDValue Op0 =
15923         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, A.getOperand(0),
15924                     DAG.getConstant(I * 16, DL, MVT::i64));
15925     SDValue Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, B,
15926                               DAG.getConstant(I * 16, DL, MVT::i64));
15927     SDValue Dot =
15928         DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros, Op0, Op1);
15929     SDotVec16.push_back(Dot);
15930   }
15931   // Concatenate dot operations.
15932   EVT SDot16EVT =
15933       EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4 * VecReduce16Num);
15934   SDValue ConcatSDot16 =
15935       DAG.getNode(ISD::CONCAT_VECTORS, DL, SDot16EVT, SDotVec16);
15936   SDValue VecReduceAdd16 =
15937       DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), ConcatSDot16);
15938   unsigned VecReduce8Num = (Op0VT.getVectorNumElements() % 16) / 8;
15939   if (VecReduce8Num == 0)
15940     return VecReduceAdd16;
15941 
15942   // Generate the remainder Dot operation that is multiple of 8.
15943   SmallVector<SDValue, 4> SDotVec8;
15944   SDValue Zeros = DAG.getConstant(0, DL, MVT::v2i32);
15945   SDValue Vec8Op0 =
15946       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, A.getOperand(0),
15947                   DAG.getConstant(I * 16, DL, MVT::i64));
15948   SDValue Vec8Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, B,
15949                                 DAG.getConstant(I * 16, DL, MVT::i64));
15950   SDValue Dot =
15951       DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros, Vec8Op0, Vec8Op1);
15952   SDValue VecReudceAdd8 =
15953       DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
15954   return DAG.getNode(ISD::ADD, DL, N->getValueType(0), VecReduceAdd16,
15955                      VecReudceAdd8);
15956 }
15957 
15958 // Given an (integer) vecreduce, we know the order of the inputs does not
15959 // matter. We can convert UADDV(add(zext(extract_lo(x)), zext(extract_hi(x))))
15960 // into UADDV(UADDLP(x)). This can also happen through an extra add, where we
15961 // transform UADDV(add(y, add(zext(extract_lo(x)), zext(extract_hi(x))))).
15962 static SDValue performUADDVAddCombine(SDValue A, SelectionDAG &DAG) {
15963   auto DetectAddExtract = [&](SDValue A) {
15964     // Look for add(zext(extract_lo(x)), zext(extract_hi(x))), returning
15965     // UADDLP(x) if found.
15966     if (A.getOpcode() != ISD::ADD)
15967       return SDValue();
15968     EVT VT = A.getValueType();
15969     SDValue Op0 = A.getOperand(0);
15970     SDValue Op1 = A.getOperand(1);
15971     if (Op0.getOpcode() != Op0.getOpcode() ||
15972         (Op0.getOpcode() != ISD::ZERO_EXTEND &&
15973          Op0.getOpcode() != ISD::SIGN_EXTEND))
15974       return SDValue();
15975     SDValue Ext0 = Op0.getOperand(0);
15976     SDValue Ext1 = Op1.getOperand(0);
15977     if (Ext0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
15978         Ext1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
15979         Ext0.getOperand(0) != Ext1.getOperand(0))
15980       return SDValue();
15981     // Check that the type is twice the add types, and the extract are from
15982     // upper/lower parts of the same source.
15983     if (Ext0.getOperand(0).getValueType().getVectorNumElements() !=
15984         VT.getVectorNumElements() * 2)
15985       return SDValue();
15986     if ((Ext0.getConstantOperandVal(1) != 0 &&
15987          Ext1.getConstantOperandVal(1) != VT.getVectorNumElements()) &&
15988         (Ext1.getConstantOperandVal(1) != 0 &&
15989          Ext0.getConstantOperandVal(1) != VT.getVectorNumElements()))
15990       return SDValue();
15991     unsigned Opcode = Op0.getOpcode() == ISD::ZERO_EXTEND ? AArch64ISD::UADDLP
15992                                                           : AArch64ISD::SADDLP;
15993     return DAG.getNode(Opcode, SDLoc(A), VT, Ext0.getOperand(0));
15994   };
15995 
15996   if (SDValue R = DetectAddExtract(A))
15997     return R;
15998 
15999   if (A.getOperand(0).getOpcode() == ISD::ADD && A.getOperand(0).hasOneUse())
16000     if (SDValue R = performUADDVAddCombine(A.getOperand(0), DAG))
16001       return DAG.getNode(ISD::ADD, SDLoc(A), A.getValueType(), R,
16002                          A.getOperand(1));
16003   if (A.getOperand(1).getOpcode() == ISD::ADD && A.getOperand(1).hasOneUse())
16004     if (SDValue R = performUADDVAddCombine(A.getOperand(1), DAG))
16005       return DAG.getNode(ISD::ADD, SDLoc(A), A.getValueType(), R,
16006                          A.getOperand(0));
16007   return SDValue();
16008 }
16009 
16010 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
16011   SDValue A = N->getOperand(0);
16012   if (A.getOpcode() == ISD::ADD)
16013     if (SDValue R = performUADDVAddCombine(A, DAG))
16014       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), R);
16015   return SDValue();
16016 }
16017 
16018 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
16019                                  TargetLowering::DAGCombinerInfo &DCI,
16020                                  const AArch64Subtarget *Subtarget) {
16021   if (DCI.isBeforeLegalizeOps())
16022     return SDValue();
16023 
16024   return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
16025 }
16026 
16027 SDValue
16028 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
16029                                      SelectionDAG &DAG,
16030                                      SmallVectorImpl<SDNode *> &Created) const {
16031   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
16032   if (isIntDivCheap(N->getValueType(0), Attr))
16033     return SDValue(N,0); // Lower SDIV as SDIV
16034 
16035   EVT VT = N->getValueType(0);
16036 
16037   // For scalable and fixed types, mark them as cheap so we can handle it much
16038   // later. This allows us to handle larger than legal types.
16039   if (VT.isScalableVector() || Subtarget->useSVEForFixedLengthVectors())
16040     return SDValue(N, 0);
16041 
16042   // fold (sdiv X, pow2)
16043   if ((VT != MVT::i32 && VT != MVT::i64) ||
16044       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
16045     return SDValue();
16046 
16047   SDLoc DL(N);
16048   SDValue N0 = N->getOperand(0);
16049   unsigned Lg2 = Divisor.countr_zero();
16050   SDValue Zero = DAG.getConstant(0, DL, VT);
16051   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
16052 
16053   // Add (N0 < 0) ? Pow2 - 1 : 0;
16054   SDValue CCVal;
16055   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
16056   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
16057   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
16058 
16059   Created.push_back(Cmp.getNode());
16060   Created.push_back(Add.getNode());
16061   Created.push_back(CSel.getNode());
16062 
16063   // Divide by pow2.
16064   SDValue SRA =
16065       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
16066 
16067   // If we're dividing by a positive value, we're done.  Otherwise, we must
16068   // negate the result.
16069   if (Divisor.isNonNegative())
16070     return SRA;
16071 
16072   Created.push_back(SRA.getNode());
16073   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
16074 }
16075 
16076 SDValue
16077 AArch64TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor,
16078                                      SelectionDAG &DAG,
16079                                      SmallVectorImpl<SDNode *> &Created) const {
16080   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
16081   if (isIntDivCheap(N->getValueType(0), Attr))
16082     return SDValue(N, 0); // Lower SREM as SREM
16083 
16084   EVT VT = N->getValueType(0);
16085 
16086   // For scalable and fixed types, mark them as cheap so we can handle it much
16087   // later. This allows us to handle larger than legal types.
16088   if (VT.isScalableVector() || Subtarget->useSVEForFixedLengthVectors())
16089     return SDValue(N, 0);
16090 
16091   // fold (srem X, pow2)
16092   if ((VT != MVT::i32 && VT != MVT::i64) ||
16093       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
16094     return SDValue();
16095 
16096   unsigned Lg2 = Divisor.countr_zero();
16097   if (Lg2 == 0)
16098     return SDValue();
16099 
16100   SDLoc DL(N);
16101   SDValue N0 = N->getOperand(0);
16102   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
16103   SDValue Zero = DAG.getConstant(0, DL, VT);
16104   SDValue CCVal, CSNeg;
16105   if (Lg2 == 1) {
16106     SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETGE, CCVal, DAG, DL);
16107     SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, Pow2MinusOne);
16108     CSNeg = DAG.getNode(AArch64ISD::CSNEG, DL, VT, And, And, CCVal, Cmp);
16109 
16110     Created.push_back(Cmp.getNode());
16111     Created.push_back(And.getNode());
16112   } else {
16113     SDValue CCVal = DAG.getConstant(AArch64CC::MI, DL, MVT_CC);
16114     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16115 
16116     SDValue Negs = DAG.getNode(AArch64ISD::SUBS, DL, VTs, Zero, N0);
16117     SDValue AndPos = DAG.getNode(ISD::AND, DL, VT, N0, Pow2MinusOne);
16118     SDValue AndNeg = DAG.getNode(ISD::AND, DL, VT, Negs, Pow2MinusOne);
16119     CSNeg = DAG.getNode(AArch64ISD::CSNEG, DL, VT, AndPos, AndNeg, CCVal,
16120                         Negs.getValue(1));
16121 
16122     Created.push_back(Negs.getNode());
16123     Created.push_back(AndPos.getNode());
16124     Created.push_back(AndNeg.getNode());
16125   }
16126 
16127   return CSNeg;
16128 }
16129 
16130 static std::optional<unsigned> IsSVECntIntrinsic(SDValue S) {
16131   switch(getIntrinsicID(S.getNode())) {
16132   default:
16133     break;
16134   case Intrinsic::aarch64_sve_cntb:
16135     return 8;
16136   case Intrinsic::aarch64_sve_cnth:
16137     return 16;
16138   case Intrinsic::aarch64_sve_cntw:
16139     return 32;
16140   case Intrinsic::aarch64_sve_cntd:
16141     return 64;
16142   }
16143   return {};
16144 }
16145 
16146 /// Calculates what the pre-extend type is, based on the extension
16147 /// operation node provided by \p Extend.
16148 ///
16149 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
16150 /// pre-extend type is pulled directly from the operand, while other extend
16151 /// operations need a bit more inspection to get this information.
16152 ///
16153 /// \param Extend The SDNode from the DAG that represents the extend operation
16154 ///
16155 /// \returns The type representing the \p Extend source type, or \p MVT::Other
16156 /// if no valid type can be determined
16157 static EVT calculatePreExtendType(SDValue Extend) {
16158   switch (Extend.getOpcode()) {
16159   case ISD::SIGN_EXTEND:
16160   case ISD::ZERO_EXTEND:
16161     return Extend.getOperand(0).getValueType();
16162   case ISD::AssertSext:
16163   case ISD::AssertZext:
16164   case ISD::SIGN_EXTEND_INREG: {
16165     VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
16166     if (!TypeNode)
16167       return MVT::Other;
16168     return TypeNode->getVT();
16169   }
16170   case ISD::AND: {
16171     ConstantSDNode *Constant =
16172         dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
16173     if (!Constant)
16174       return MVT::Other;
16175 
16176     uint32_t Mask = Constant->getZExtValue();
16177 
16178     if (Mask == UCHAR_MAX)
16179       return MVT::i8;
16180     else if (Mask == USHRT_MAX)
16181       return MVT::i16;
16182     else if (Mask == UINT_MAX)
16183       return MVT::i32;
16184 
16185     return MVT::Other;
16186   }
16187   default:
16188     return MVT::Other;
16189   }
16190 }
16191 
16192 /// Combines a buildvector(sext/zext) or shuffle(sext/zext, undef) node pattern
16193 /// into sext/zext(buildvector) or sext/zext(shuffle) making use of the vector
16194 /// SExt/ZExt rather than the scalar SExt/ZExt
16195 static SDValue performBuildShuffleExtendCombine(SDValue BV, SelectionDAG &DAG) {
16196   EVT VT = BV.getValueType();
16197   if (BV.getOpcode() != ISD::BUILD_VECTOR &&
16198       BV.getOpcode() != ISD::VECTOR_SHUFFLE)
16199     return SDValue();
16200 
16201   // Use the first item in the buildvector/shuffle to get the size of the
16202   // extend, and make sure it looks valid.
16203   SDValue Extend = BV->getOperand(0);
16204   unsigned ExtendOpcode = Extend.getOpcode();
16205   bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
16206                 ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
16207                 ExtendOpcode == ISD::AssertSext;
16208   if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
16209       ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
16210     return SDValue();
16211   // Shuffle inputs are vector, limit to SIGN_EXTEND and ZERO_EXTEND to ensure
16212   // calculatePreExtendType will work without issue.
16213   if (BV.getOpcode() == ISD::VECTOR_SHUFFLE &&
16214       ExtendOpcode != ISD::SIGN_EXTEND && ExtendOpcode != ISD::ZERO_EXTEND)
16215     return SDValue();
16216 
16217   // Restrict valid pre-extend data type
16218   EVT PreExtendType = calculatePreExtendType(Extend);
16219   if (PreExtendType == MVT::Other ||
16220       PreExtendType.getScalarSizeInBits() != VT.getScalarSizeInBits() / 2)
16221     return SDValue();
16222 
16223   // Make sure all other operands are equally extended
16224   for (SDValue Op : drop_begin(BV->ops())) {
16225     if (Op.isUndef())
16226       continue;
16227     unsigned Opc = Op.getOpcode();
16228     bool OpcIsSExt = Opc == ISD::SIGN_EXTEND || Opc == ISD::SIGN_EXTEND_INREG ||
16229                      Opc == ISD::AssertSext;
16230     if (OpcIsSExt != IsSExt || calculatePreExtendType(Op) != PreExtendType)
16231       return SDValue();
16232   }
16233 
16234   SDValue NBV;
16235   SDLoc DL(BV);
16236   if (BV.getOpcode() == ISD::BUILD_VECTOR) {
16237     EVT PreExtendVT = VT.changeVectorElementType(PreExtendType);
16238     EVT PreExtendLegalType =
16239         PreExtendType.getScalarSizeInBits() < 32 ? MVT::i32 : PreExtendType;
16240     SmallVector<SDValue, 8> NewOps;
16241     for (SDValue Op : BV->ops())
16242       NewOps.push_back(Op.isUndef() ? DAG.getUNDEF(PreExtendLegalType)
16243                                     : DAG.getAnyExtOrTrunc(Op.getOperand(0), DL,
16244                                                            PreExtendLegalType));
16245     NBV = DAG.getNode(ISD::BUILD_VECTOR, DL, PreExtendVT, NewOps);
16246   } else { // BV.getOpcode() == ISD::VECTOR_SHUFFLE
16247     EVT PreExtendVT = VT.changeVectorElementType(PreExtendType.getScalarType());
16248     NBV = DAG.getVectorShuffle(PreExtendVT, DL, BV.getOperand(0).getOperand(0),
16249                                BV.getOperand(1).isUndef()
16250                                    ? DAG.getUNDEF(PreExtendVT)
16251                                    : BV.getOperand(1).getOperand(0),
16252                                cast<ShuffleVectorSDNode>(BV)->getMask());
16253   }
16254   return DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT, NBV);
16255 }
16256 
16257 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
16258 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
16259 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
16260   // If the value type isn't a vector, none of the operands are going to be dups
16261   EVT VT = Mul->getValueType(0);
16262   if (VT != MVT::v8i16 && VT != MVT::v4i32 && VT != MVT::v2i64)
16263     return SDValue();
16264 
16265   SDValue Op0 = performBuildShuffleExtendCombine(Mul->getOperand(0), DAG);
16266   SDValue Op1 = performBuildShuffleExtendCombine(Mul->getOperand(1), DAG);
16267 
16268   // Neither operands have been changed, don't make any further changes
16269   if (!Op0 && !Op1)
16270     return SDValue();
16271 
16272   SDLoc DL(Mul);
16273   return DAG.getNode(Mul->getOpcode(), DL, VT, Op0 ? Op0 : Mul->getOperand(0),
16274                      Op1 ? Op1 : Mul->getOperand(1));
16275 }
16276 
16277 // Combine v4i32 Mul(And(Srl(X, 15), 0x10001), 0xffff) -> v8i16 CMLTz
16278 // Same for other types with equivalent constants.
16279 static SDValue performMulVectorCmpZeroCombine(SDNode *N, SelectionDAG &DAG) {
16280   EVT VT = N->getValueType(0);
16281   if (VT != MVT::v2i64 && VT != MVT::v1i64 && VT != MVT::v2i32 &&
16282       VT != MVT::v4i32 && VT != MVT::v4i16 && VT != MVT::v8i16)
16283     return SDValue();
16284   if (N->getOperand(0).getOpcode() != ISD::AND ||
16285       N->getOperand(0).getOperand(0).getOpcode() != ISD::SRL)
16286     return SDValue();
16287 
16288   SDValue And = N->getOperand(0);
16289   SDValue Srl = And.getOperand(0);
16290 
16291   APInt V1, V2, V3;
16292   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), V1) ||
16293       !ISD::isConstantSplatVector(And.getOperand(1).getNode(), V2) ||
16294       !ISD::isConstantSplatVector(Srl.getOperand(1).getNode(), V3))
16295     return SDValue();
16296 
16297   unsigned HalfSize = VT.getScalarSizeInBits() / 2;
16298   if (!V1.isMask(HalfSize) || V2 != (1ULL | 1ULL << HalfSize) ||
16299       V3 != (HalfSize - 1))
16300     return SDValue();
16301 
16302   EVT HalfVT = EVT::getVectorVT(*DAG.getContext(),
16303                                 EVT::getIntegerVT(*DAG.getContext(), HalfSize),
16304                                 VT.getVectorElementCount() * 2);
16305 
16306   SDLoc DL(N);
16307   SDValue In = DAG.getNode(AArch64ISD::NVCAST, DL, HalfVT, Srl.getOperand(0));
16308   SDValue CM = DAG.getNode(AArch64ISD::CMLTz, DL, HalfVT, In);
16309   return DAG.getNode(AArch64ISD::NVCAST, DL, VT, CM);
16310 }
16311 
16312 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
16313                                  TargetLowering::DAGCombinerInfo &DCI,
16314                                  const AArch64Subtarget *Subtarget) {
16315 
16316   if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
16317     return Ext;
16318   if (SDValue Ext = performMulVectorCmpZeroCombine(N, DAG))
16319     return Ext;
16320 
16321   if (DCI.isBeforeLegalizeOps())
16322     return SDValue();
16323 
16324   // Canonicalize X*(Y+1) -> X*Y+X and (X+1)*Y -> X*Y+Y,
16325   // and in MachineCombiner pass, add+mul will be combined into madd.
16326   // Similarly, X*(1-Y) -> X - X*Y and (1-Y)*X -> X - Y*X.
16327   SDLoc DL(N);
16328   EVT VT = N->getValueType(0);
16329   SDValue N0 = N->getOperand(0);
16330   SDValue N1 = N->getOperand(1);
16331   SDValue MulOper;
16332   unsigned AddSubOpc;
16333 
16334   auto IsAddSubWith1 = [&](SDValue V) -> bool {
16335     AddSubOpc = V->getOpcode();
16336     if ((AddSubOpc == ISD::ADD || AddSubOpc == ISD::SUB) && V->hasOneUse()) {
16337       SDValue Opnd = V->getOperand(1);
16338       MulOper = V->getOperand(0);
16339       if (AddSubOpc == ISD::SUB)
16340         std::swap(Opnd, MulOper);
16341       if (auto C = dyn_cast<ConstantSDNode>(Opnd))
16342         return C->isOne();
16343     }
16344     return false;
16345   };
16346 
16347   if (IsAddSubWith1(N0)) {
16348     SDValue MulVal = DAG.getNode(ISD::MUL, DL, VT, N1, MulOper);
16349     return DAG.getNode(AddSubOpc, DL, VT, N1, MulVal);
16350   }
16351 
16352   if (IsAddSubWith1(N1)) {
16353     SDValue MulVal = DAG.getNode(ISD::MUL, DL, VT, N0, MulOper);
16354     return DAG.getNode(AddSubOpc, DL, VT, N0, MulVal);
16355   }
16356 
16357   // The below optimizations require a constant RHS.
16358   if (!isa<ConstantSDNode>(N1))
16359     return SDValue();
16360 
16361   ConstantSDNode *C = cast<ConstantSDNode>(N1);
16362   const APInt &ConstValue = C->getAPIntValue();
16363 
16364   // Allow the scaling to be folded into the `cnt` instruction by preventing
16365   // the scaling to be obscured here. This makes it easier to pattern match.
16366   if (IsSVECntIntrinsic(N0) ||
16367      (N0->getOpcode() == ISD::TRUNCATE &&
16368       (IsSVECntIntrinsic(N0->getOperand(0)))))
16369        if (ConstValue.sge(1) && ConstValue.sle(16))
16370          return SDValue();
16371 
16372   // Multiplication of a power of two plus/minus one can be done more
16373   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
16374   // future CPUs have a cheaper MADD instruction, this may need to be
16375   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
16376   // 64-bit is 5 cycles, so this is always a win.
16377   // More aggressively, some multiplications N0 * C can be lowered to
16378   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
16379   // e.g. 6=3*2=(2+1)*2, 45=(1+4)*(1+8)
16380   // TODO: lower more cases.
16381 
16382   // TrailingZeroes is used to test if the mul can be lowered to
16383   // shift+add+shift.
16384   unsigned TrailingZeroes = ConstValue.countr_zero();
16385   if (TrailingZeroes) {
16386     // Conservatively do not lower to shift+add+shift if the mul might be
16387     // folded into smul or umul.
16388     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
16389                             isZeroExtended(N0.getNode(), DAG)))
16390       return SDValue();
16391     // Conservatively do not lower to shift+add+shift if the mul might be
16392     // folded into madd or msub.
16393     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
16394                            N->use_begin()->getOpcode() == ISD::SUB))
16395       return SDValue();
16396   }
16397   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
16398   // and shift+add+shift.
16399   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
16400   unsigned ShiftAmt;
16401 
16402   auto Shl = [&](SDValue N0, unsigned N1) {
16403     SDValue RHS = DAG.getConstant(N1, DL, MVT::i64);
16404     return DAG.getNode(ISD::SHL, DL, VT, N0, RHS);
16405   };
16406   auto Add = [&](SDValue N0, SDValue N1) {
16407     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
16408   };
16409   auto Sub = [&](SDValue N0, SDValue N1) {
16410     return DAG.getNode(ISD::SUB, DL, VT, N0, N1);
16411   };
16412   auto Negate = [&](SDValue N) {
16413     SDValue Zero = DAG.getConstant(0, DL, VT);
16414     return DAG.getNode(ISD::SUB, DL, VT, Zero, N);
16415   };
16416 
16417   // Can the const C be decomposed into (1+2^M1)*(1+2^N1), eg:
16418   // C = 45 is equal to (1+4)*(1+8), we don't decompose it into (1+2)*(16-1) as
16419   // the (2^N - 1) can't be execused via a single instruction.
16420   auto isPowPlusPlusConst = [](APInt C, APInt &M, APInt &N) {
16421     unsigned BitWidth = C.getBitWidth();
16422     for (unsigned i = 1; i < BitWidth / 2; i++) {
16423       APInt Rem;
16424       APInt X(BitWidth, (1 << i) + 1);
16425       APInt::sdivrem(C, X, N, Rem);
16426       APInt NVMinus1 = N - 1;
16427       if (Rem == 0 && NVMinus1.isPowerOf2()) {
16428         M = X;
16429         return true;
16430       }
16431     }
16432     return false;
16433   };
16434 
16435   if (ConstValue.isNonNegative()) {
16436     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
16437     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16438     // (mul x, (2^(N-M) - 1) * 2^M) => (sub (shl x, N), (shl x, M))
16439     // (mul x, (2^M + 1) * (2^N + 1))
16440     //     => MV = (add (shl x, M), x); (add (shl MV, N), MV)
16441     APInt SCVMinus1 = ShiftedConstValue - 1;
16442     APInt SCVPlus1 = ShiftedConstValue + 1;
16443     APInt CVPlus1 = ConstValue + 1;
16444     APInt CVM, CVN;
16445     if (SCVMinus1.isPowerOf2()) {
16446       ShiftAmt = SCVMinus1.logBase2();
16447       return Shl(Add(Shl(N0, ShiftAmt), N0), TrailingZeroes);
16448     } else if (CVPlus1.isPowerOf2()) {
16449       ShiftAmt = CVPlus1.logBase2();
16450       return Sub(Shl(N0, ShiftAmt), N0);
16451     } else if (SCVPlus1.isPowerOf2()) {
16452       ShiftAmt = SCVPlus1.logBase2() + TrailingZeroes;
16453       return Sub(Shl(N0, ShiftAmt), Shl(N0, TrailingZeroes));
16454     } else if (Subtarget->hasLSLFast() &&
16455                isPowPlusPlusConst(ConstValue, CVM, CVN)) {
16456       APInt CVMMinus1 = CVM - 1;
16457       APInt CVNMinus1 = CVN - 1;
16458       unsigned ShiftM1 = CVMMinus1.logBase2();
16459       unsigned ShiftN1 = CVNMinus1.logBase2();
16460       // LSLFast implicate that Shifts <= 3 places are fast
16461       if (ShiftM1 <= 3 && ShiftN1 <= 3) {
16462         SDValue MVal = Add(Shl(N0, ShiftM1), N0);
16463         return Add(Shl(MVal, ShiftN1), MVal);
16464       }
16465     }
16466   } else {
16467     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16468     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
16469     // (mul x, -(2^(N-M) - 1) * 2^M) => (sub (shl x, M), (shl x, N))
16470     APInt SCVPlus1 = -ShiftedConstValue + 1;
16471     APInt CVNegPlus1 = -ConstValue + 1;
16472     APInt CVNegMinus1 = -ConstValue - 1;
16473     if (CVNegPlus1.isPowerOf2()) {
16474       ShiftAmt = CVNegPlus1.logBase2();
16475       return Sub(N0, Shl(N0, ShiftAmt));
16476     } else if (CVNegMinus1.isPowerOf2()) {
16477       ShiftAmt = CVNegMinus1.logBase2();
16478       return Negate(Add(Shl(N0, ShiftAmt), N0));
16479     } else if (SCVPlus1.isPowerOf2()) {
16480       ShiftAmt = SCVPlus1.logBase2() + TrailingZeroes;
16481       return Sub(Shl(N0, TrailingZeroes), Shl(N0, ShiftAmt));
16482     }
16483   }
16484 
16485   return SDValue();
16486 }
16487 
16488 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
16489                                                          SelectionDAG &DAG) {
16490   // Take advantage of vector comparisons producing 0 or -1 in each lane to
16491   // optimize away operation when it's from a constant.
16492   //
16493   // The general transformation is:
16494   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
16495   //       AND(VECTOR_CMP(x,y), constant2)
16496   //    constant2 = UNARYOP(constant)
16497 
16498   // Early exit if this isn't a vector operation, the operand of the
16499   // unary operation isn't a bitwise AND, or if the sizes of the operations
16500   // aren't the same.
16501   EVT VT = N->getValueType(0);
16502   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
16503       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
16504       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
16505     return SDValue();
16506 
16507   // Now check that the other operand of the AND is a constant. We could
16508   // make the transformation for non-constant splats as well, but it's unclear
16509   // that would be a benefit as it would not eliminate any operations, just
16510   // perform one more step in scalar code before moving to the vector unit.
16511   if (BuildVectorSDNode *BV =
16512           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
16513     // Bail out if the vector isn't a constant.
16514     if (!BV->isConstant())
16515       return SDValue();
16516 
16517     // Everything checks out. Build up the new and improved node.
16518     SDLoc DL(N);
16519     EVT IntVT = BV->getValueType(0);
16520     // Create a new constant of the appropriate type for the transformed
16521     // DAG.
16522     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
16523     // The AND node needs bitcasts to/from an integer vector type around it.
16524     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
16525     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
16526                                  N->getOperand(0)->getOperand(0), MaskConst);
16527     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
16528     return Res;
16529   }
16530 
16531   return SDValue();
16532 }
16533 
16534 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
16535                                      const AArch64Subtarget *Subtarget) {
16536   // First try to optimize away the conversion when it's conditionally from
16537   // a constant. Vectors only.
16538   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
16539     return Res;
16540 
16541   EVT VT = N->getValueType(0);
16542   if (VT != MVT::f32 && VT != MVT::f64)
16543     return SDValue();
16544 
16545   // Only optimize when the source and destination types have the same width.
16546   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
16547     return SDValue();
16548 
16549   // If the result of an integer load is only used by an integer-to-float
16550   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
16551   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
16552   SDValue N0 = N->getOperand(0);
16553   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
16554       // Do not change the width of a volatile load.
16555       !cast<LoadSDNode>(N0)->isVolatile()) {
16556     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16557     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
16558                                LN0->getPointerInfo(), LN0->getAlign(),
16559                                LN0->getMemOperand()->getFlags());
16560 
16561     // Make sure successors of the original load stay after it by updating them
16562     // to use the new Chain.
16563     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
16564 
16565     unsigned Opcode =
16566         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
16567     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
16568   }
16569 
16570   return SDValue();
16571 }
16572 
16573 /// Fold a floating-point multiply by power of two into floating-point to
16574 /// fixed-point conversion.
16575 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
16576                                      TargetLowering::DAGCombinerInfo &DCI,
16577                                      const AArch64Subtarget *Subtarget) {
16578   if (!Subtarget->isNeonAvailable())
16579     return SDValue();
16580 
16581   if (!N->getValueType(0).isSimple())
16582     return SDValue();
16583 
16584   SDValue Op = N->getOperand(0);
16585   if (!Op.getValueType().isSimple() || Op.getOpcode() != ISD::FMUL)
16586     return SDValue();
16587 
16588   if (!Op.getValueType().is64BitVector() && !Op.getValueType().is128BitVector())
16589     return SDValue();
16590 
16591   SDValue ConstVec = Op->getOperand(1);
16592   if (!isa<BuildVectorSDNode>(ConstVec))
16593     return SDValue();
16594 
16595   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16596   uint32_t FloatBits = FloatTy.getSizeInBits();
16597   if (FloatBits != 32 && FloatBits != 64 &&
16598       (FloatBits != 16 || !Subtarget->hasFullFP16()))
16599     return SDValue();
16600 
16601   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16602   uint32_t IntBits = IntTy.getSizeInBits();
16603   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
16604     return SDValue();
16605 
16606   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
16607   if (IntBits > FloatBits)
16608     return SDValue();
16609 
16610   BitVector UndefElements;
16611   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16612   int32_t Bits = IntBits == 64 ? 64 : 32;
16613   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
16614   if (C == -1 || C == 0 || C > Bits)
16615     return SDValue();
16616 
16617   EVT ResTy = Op.getValueType().changeVectorElementTypeToInteger();
16618   if (!DAG.getTargetLoweringInfo().isTypeLegal(ResTy))
16619     return SDValue();
16620 
16621   if (N->getOpcode() == ISD::FP_TO_SINT_SAT ||
16622       N->getOpcode() == ISD::FP_TO_UINT_SAT) {
16623     EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
16624     if (SatVT.getScalarSizeInBits() != IntBits || IntBits != FloatBits)
16625       return SDValue();
16626   }
16627 
16628   SDLoc DL(N);
16629   bool IsSigned = (N->getOpcode() == ISD::FP_TO_SINT ||
16630                    N->getOpcode() == ISD::FP_TO_SINT_SAT);
16631   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
16632                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
16633   SDValue FixConv =
16634       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
16635                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
16636                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
16637   // We can handle smaller integers by generating an extra trunc.
16638   if (IntBits < FloatBits)
16639     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
16640 
16641   return FixConv;
16642 }
16643 
16644 /// Fold a floating-point divide by power of two into fixed-point to
16645 /// floating-point conversion.
16646 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
16647                                   TargetLowering::DAGCombinerInfo &DCI,
16648                                   const AArch64Subtarget *Subtarget) {
16649   if (!Subtarget->hasNEON())
16650     return SDValue();
16651 
16652   SDValue Op = N->getOperand(0);
16653   unsigned Opc = Op->getOpcode();
16654   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16655       !Op.getOperand(0).getValueType().isSimple() ||
16656       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
16657     return SDValue();
16658 
16659   SDValue ConstVec = N->getOperand(1);
16660   if (!isa<BuildVectorSDNode>(ConstVec))
16661     return SDValue();
16662 
16663   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
16664   int32_t IntBits = IntTy.getSizeInBits();
16665   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
16666     return SDValue();
16667 
16668   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
16669   int32_t FloatBits = FloatTy.getSizeInBits();
16670   if (FloatBits != 32 && FloatBits != 64)
16671     return SDValue();
16672 
16673   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
16674   if (IntBits > FloatBits)
16675     return SDValue();
16676 
16677   BitVector UndefElements;
16678   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16679   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
16680   if (C == -1 || C == 0 || C > FloatBits)
16681     return SDValue();
16682 
16683   MVT ResTy;
16684   unsigned NumLanes = Op.getValueType().getVectorNumElements();
16685   switch (NumLanes) {
16686   default:
16687     return SDValue();
16688   case 2:
16689     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
16690     break;
16691   case 4:
16692     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
16693     break;
16694   }
16695 
16696   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
16697     return SDValue();
16698 
16699   SDLoc DL(N);
16700   SDValue ConvInput = Op.getOperand(0);
16701   bool IsSigned = Opc == ISD::SINT_TO_FP;
16702   if (IntBits < FloatBits)
16703     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
16704                             ResTy, ConvInput);
16705 
16706   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
16707                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
16708   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
16709                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
16710                      DAG.getConstant(C, DL, MVT::i32));
16711 }
16712 
16713 /// An EXTR instruction is made up of two shifts, ORed together. This helper
16714 /// searches for and classifies those shifts.
16715 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
16716                          bool &FromHi) {
16717   if (N.getOpcode() == ISD::SHL)
16718     FromHi = false;
16719   else if (N.getOpcode() == ISD::SRL)
16720     FromHi = true;
16721   else
16722     return false;
16723 
16724   if (!isa<ConstantSDNode>(N.getOperand(1)))
16725     return false;
16726 
16727   ShiftAmount = N->getConstantOperandVal(1);
16728   Src = N->getOperand(0);
16729   return true;
16730 }
16731 
16732 /// EXTR instruction extracts a contiguous chunk of bits from two existing
16733 /// registers viewed as a high/low pair. This function looks for the pattern:
16734 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
16735 /// with an EXTR. Can't quite be done in TableGen because the two immediates
16736 /// aren't independent.
16737 static SDValue tryCombineToEXTR(SDNode *N,
16738                                 TargetLowering::DAGCombinerInfo &DCI) {
16739   SelectionDAG &DAG = DCI.DAG;
16740   SDLoc DL(N);
16741   EVT VT = N->getValueType(0);
16742 
16743   assert(N->getOpcode() == ISD::OR && "Unexpected root");
16744 
16745   if (VT != MVT::i32 && VT != MVT::i64)
16746     return SDValue();
16747 
16748   SDValue LHS;
16749   uint32_t ShiftLHS = 0;
16750   bool LHSFromHi = false;
16751   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
16752     return SDValue();
16753 
16754   SDValue RHS;
16755   uint32_t ShiftRHS = 0;
16756   bool RHSFromHi = false;
16757   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
16758     return SDValue();
16759 
16760   // If they're both trying to come from the high part of the register, they're
16761   // not really an EXTR.
16762   if (LHSFromHi == RHSFromHi)
16763     return SDValue();
16764 
16765   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
16766     return SDValue();
16767 
16768   if (LHSFromHi) {
16769     std::swap(LHS, RHS);
16770     std::swap(ShiftLHS, ShiftRHS);
16771   }
16772 
16773   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
16774                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
16775 }
16776 
16777 static SDValue tryCombineToBSL(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
16778                                const AArch64TargetLowering &TLI) {
16779   EVT VT = N->getValueType(0);
16780   SelectionDAG &DAG = DCI.DAG;
16781   SDLoc DL(N);
16782 
16783   if (!VT.isVector())
16784     return SDValue();
16785 
16786   // The combining code currently only works for NEON vectors. In particular,
16787   // it does not work for SVE when dealing with vectors wider than 128 bits.
16788   // It also doesn't work for streaming mode because it causes generating
16789   // bsl instructions that are invalid in streaming mode.
16790   if (TLI.useSVEForFixedLengthVectorVT(
16791           VT, !DAG.getSubtarget<AArch64Subtarget>().isNeonAvailable()))
16792     return SDValue();
16793 
16794   SDValue N0 = N->getOperand(0);
16795   if (N0.getOpcode() != ISD::AND)
16796     return SDValue();
16797 
16798   SDValue N1 = N->getOperand(1);
16799   if (N1.getOpcode() != ISD::AND)
16800     return SDValue();
16801 
16802   // InstCombine does (not (neg a)) => (add a -1).
16803   // Try: (or (and (neg a) b) (and (add a -1) c)) => (bsl (neg a) b c)
16804   // Loop over all combinations of AND operands.
16805   for (int i = 1; i >= 0; --i) {
16806     for (int j = 1; j >= 0; --j) {
16807       SDValue O0 = N0->getOperand(i);
16808       SDValue O1 = N1->getOperand(j);
16809       SDValue Sub, Add, SubSibling, AddSibling;
16810 
16811       // Find a SUB and an ADD operand, one from each AND.
16812       if (O0.getOpcode() == ISD::SUB && O1.getOpcode() == ISD::ADD) {
16813         Sub = O0;
16814         Add = O1;
16815         SubSibling = N0->getOperand(1 - i);
16816         AddSibling = N1->getOperand(1 - j);
16817       } else if (O0.getOpcode() == ISD::ADD && O1.getOpcode() == ISD::SUB) {
16818         Add = O0;
16819         Sub = O1;
16820         AddSibling = N0->getOperand(1 - i);
16821         SubSibling = N1->getOperand(1 - j);
16822       } else
16823         continue;
16824 
16825       if (!ISD::isBuildVectorAllZeros(Sub.getOperand(0).getNode()))
16826         continue;
16827 
16828       // Constant ones is always righthand operand of the Add.
16829       if (!ISD::isBuildVectorAllOnes(Add.getOperand(1).getNode()))
16830         continue;
16831 
16832       if (Sub.getOperand(1) != Add.getOperand(0))
16833         continue;
16834 
16835       return DAG.getNode(AArch64ISD::BSP, DL, VT, Sub, SubSibling, AddSibling);
16836     }
16837   }
16838 
16839   // (or (and a b) (and (not a) c)) => (bsl a b c)
16840   // We only have to look for constant vectors here since the general, variable
16841   // case can be handled in TableGen.
16842   unsigned Bits = VT.getScalarSizeInBits();
16843   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
16844   for (int i = 1; i >= 0; --i)
16845     for (int j = 1; j >= 0; --j) {
16846       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
16847       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
16848       if (!BVN0 || !BVN1)
16849         continue;
16850 
16851       bool FoundMatch = true;
16852       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
16853         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
16854         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
16855         if (!CN0 || !CN1 ||
16856             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
16857           FoundMatch = false;
16858           break;
16859         }
16860       }
16861 
16862       if (FoundMatch)
16863         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
16864                            N0->getOperand(1 - i), N1->getOperand(1 - j));
16865     }
16866 
16867   return SDValue();
16868 }
16869 
16870 // Given a tree of and/or(csel(0, 1, cc0), csel(0, 1, cc1)), we may be able to
16871 // convert to csel(ccmp(.., cc0)), depending on cc1:
16872 
16873 // (AND (CSET cc0 cmp0) (CSET cc1 (CMP x1 y1)))
16874 // =>
16875 // (CSET cc1 (CCMP x1 y1 !cc1 cc0 cmp0))
16876 //
16877 // (OR (CSET cc0 cmp0) (CSET cc1 (CMP x1 y1)))
16878 // =>
16879 // (CSET cc1 (CCMP x1 y1 cc1 !cc0 cmp0))
16880 static SDValue performANDORCSELCombine(SDNode *N, SelectionDAG &DAG) {
16881   EVT VT = N->getValueType(0);
16882   SDValue CSel0 = N->getOperand(0);
16883   SDValue CSel1 = N->getOperand(1);
16884 
16885   if (CSel0.getOpcode() != AArch64ISD::CSEL ||
16886       CSel1.getOpcode() != AArch64ISD::CSEL)
16887     return SDValue();
16888 
16889   if (!CSel0->hasOneUse() || !CSel1->hasOneUse())
16890     return SDValue();
16891 
16892   if (!isNullConstant(CSel0.getOperand(0)) ||
16893       !isOneConstant(CSel0.getOperand(1)) ||
16894       !isNullConstant(CSel1.getOperand(0)) ||
16895       !isOneConstant(CSel1.getOperand(1)))
16896     return SDValue();
16897 
16898   SDValue Cmp0 = CSel0.getOperand(3);
16899   SDValue Cmp1 = CSel1.getOperand(3);
16900   AArch64CC::CondCode CC0 = (AArch64CC::CondCode)CSel0.getConstantOperandVal(2);
16901   AArch64CC::CondCode CC1 = (AArch64CC::CondCode)CSel1.getConstantOperandVal(2);
16902   if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
16903     return SDValue();
16904   if (Cmp1.getOpcode() != AArch64ISD::SUBS &&
16905       Cmp0.getOpcode() == AArch64ISD::SUBS) {
16906     std::swap(Cmp0, Cmp1);
16907     std::swap(CC0, CC1);
16908   }
16909 
16910   if (Cmp1.getOpcode() != AArch64ISD::SUBS)
16911     return SDValue();
16912 
16913   SDLoc DL(N);
16914   SDValue CCmp, Condition;
16915   unsigned NZCV;
16916 
16917   if (N->getOpcode() == ISD::AND) {
16918     AArch64CC::CondCode InvCC0 = AArch64CC::getInvertedCondCode(CC0);
16919     Condition = DAG.getConstant(InvCC0, DL, MVT_CC);
16920     NZCV = AArch64CC::getNZCVToSatisfyCondCode(CC1);
16921   } else {
16922     AArch64CC::CondCode InvCC1 = AArch64CC::getInvertedCondCode(CC1);
16923     Condition = DAG.getConstant(CC0, DL, MVT_CC);
16924     NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvCC1);
16925   }
16926 
16927   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
16928 
16929   auto *Op1 = dyn_cast<ConstantSDNode>(Cmp1.getOperand(1));
16930   if (Op1 && Op1->getAPIntValue().isNegative() &&
16931       Op1->getAPIntValue().sgt(-32)) {
16932     // CCMP accept the constant int the range [0, 31]
16933     // if the Op1 is a constant in the range [-31, -1], we
16934     // can select to CCMN to avoid the extra mov
16935     SDValue AbsOp1 =
16936         DAG.getConstant(Op1->getAPIntValue().abs(), DL, Op1->getValueType(0));
16937     CCmp = DAG.getNode(AArch64ISD::CCMN, DL, MVT_CC, Cmp1.getOperand(0), AbsOp1,
16938                        NZCVOp, Condition, Cmp0);
16939   } else {
16940     CCmp = DAG.getNode(AArch64ISD::CCMP, DL, MVT_CC, Cmp1.getOperand(0),
16941                        Cmp1.getOperand(1), NZCVOp, Condition, Cmp0);
16942   }
16943   return DAG.getNode(AArch64ISD::CSEL, DL, VT, CSel0.getOperand(0),
16944                      CSel0.getOperand(1), DAG.getConstant(CC1, DL, MVT::i32),
16945                      CCmp);
16946 }
16947 
16948 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
16949                                 const AArch64Subtarget *Subtarget,
16950                                 const AArch64TargetLowering &TLI) {
16951   SelectionDAG &DAG = DCI.DAG;
16952   EVT VT = N->getValueType(0);
16953 
16954   if (SDValue R = performANDORCSELCombine(N, DAG))
16955     return R;
16956 
16957   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16958     return SDValue();
16959 
16960   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
16961   if (SDValue Res = tryCombineToEXTR(N, DCI))
16962     return Res;
16963 
16964   if (SDValue Res = tryCombineToBSL(N, DCI, TLI))
16965     return Res;
16966 
16967   return SDValue();
16968 }
16969 
16970 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
16971   if (!MemVT.getVectorElementType().isSimple())
16972     return false;
16973 
16974   uint64_t MaskForTy = 0ull;
16975   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
16976   case MVT::i8:
16977     MaskForTy = 0xffull;
16978     break;
16979   case MVT::i16:
16980     MaskForTy = 0xffffull;
16981     break;
16982   case MVT::i32:
16983     MaskForTy = 0xffffffffull;
16984     break;
16985   default:
16986     return false;
16987     break;
16988   }
16989 
16990   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
16991     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
16992       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
16993 
16994   return false;
16995 }
16996 
16997 static bool isAllInactivePredicate(SDValue N) {
16998   // Look through cast.
16999   while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST)
17000     N = N.getOperand(0);
17001 
17002   return ISD::isConstantSplatVectorAllZeros(N.getNode());
17003 }
17004 
17005 static bool isAllActivePredicate(SelectionDAG &DAG, SDValue N) {
17006   unsigned NumElts = N.getValueType().getVectorMinNumElements();
17007 
17008   // Look through cast.
17009   while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST) {
17010     N = N.getOperand(0);
17011     // When reinterpreting from a type with fewer elements the "new" elements
17012     // are not active, so bail if they're likely to be used.
17013     if (N.getValueType().getVectorMinNumElements() < NumElts)
17014       return false;
17015   }
17016 
17017   if (ISD::isConstantSplatVectorAllOnes(N.getNode()))
17018     return true;
17019 
17020   // "ptrue p.<ty>, all" can be considered all active when <ty> is the same size
17021   // or smaller than the implicit element type represented by N.
17022   // NOTE: A larger element count implies a smaller element type.
17023   if (N.getOpcode() == AArch64ISD::PTRUE &&
17024       N.getConstantOperandVal(0) == AArch64SVEPredPattern::all)
17025     return N.getValueType().getVectorMinNumElements() >= NumElts;
17026 
17027   // If we're compiling for a specific vector-length, we can check if the
17028   // pattern's VL equals that of the scalable vector at runtime.
17029   if (N.getOpcode() == AArch64ISD::PTRUE) {
17030     const auto &Subtarget = DAG.getSubtarget<AArch64Subtarget>();
17031     unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
17032     unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
17033     if (MaxSVESize && MinSVESize == MaxSVESize) {
17034       unsigned VScale = MaxSVESize / AArch64::SVEBitsPerBlock;
17035       unsigned PatNumElts =
17036           getNumElementsFromSVEPredPattern(N.getConstantOperandVal(0));
17037       return PatNumElts == (NumElts * VScale);
17038     }
17039   }
17040 
17041   return false;
17042 }
17043 
17044 static SDValue performReinterpretCastCombine(SDNode *N) {
17045   SDValue LeafOp = SDValue(N, 0);
17046   SDValue Op = N->getOperand(0);
17047   while (Op.getOpcode() == AArch64ISD::REINTERPRET_CAST &&
17048          LeafOp.getValueType() != Op.getValueType())
17049     Op = Op->getOperand(0);
17050   if (LeafOp.getValueType() == Op.getValueType())
17051     return Op;
17052   return SDValue();
17053 }
17054 
17055 static SDValue performSVEAndCombine(SDNode *N,
17056                                     TargetLowering::DAGCombinerInfo &DCI) {
17057   if (DCI.isBeforeLegalizeOps())
17058     return SDValue();
17059 
17060   SelectionDAG &DAG = DCI.DAG;
17061   SDValue Src = N->getOperand(0);
17062   unsigned Opc = Src->getOpcode();
17063 
17064   // Zero/any extend of an unsigned unpack
17065   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
17066     SDValue UnpkOp = Src->getOperand(0);
17067     SDValue Dup = N->getOperand(1);
17068 
17069     if (Dup.getOpcode() != ISD::SPLAT_VECTOR)
17070       return SDValue();
17071 
17072     SDLoc DL(N);
17073     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
17074     if (!C)
17075       return SDValue();
17076 
17077     uint64_t ExtVal = C->getZExtValue();
17078 
17079     auto MaskAndTypeMatch = [ExtVal](EVT VT) -> bool {
17080       return ((ExtVal == 0xFF && VT == MVT::i8) ||
17081               (ExtVal == 0xFFFF && VT == MVT::i16) ||
17082               (ExtVal == 0xFFFFFFFF && VT == MVT::i32));
17083     };
17084 
17085     // If the mask is fully covered by the unpack, we don't need to push
17086     // a new AND onto the operand
17087     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
17088     if (MaskAndTypeMatch(EltTy))
17089       return Src;
17090 
17091     // If this is 'and (uunpklo/hi (extload MemTy -> ExtTy)), mask', then check
17092     // to see if the mask is all-ones of size MemTy.
17093     auto MaskedLoadOp = dyn_cast<MaskedLoadSDNode>(UnpkOp);
17094     if (MaskedLoadOp && (MaskedLoadOp->getExtensionType() == ISD::ZEXTLOAD ||
17095                          MaskedLoadOp->getExtensionType() == ISD::EXTLOAD)) {
17096       EVT EltTy = MaskedLoadOp->getMemoryVT().getVectorElementType();
17097       if (MaskAndTypeMatch(EltTy))
17098         return Src;
17099     }
17100 
17101     // Truncate to prevent a DUP with an over wide constant
17102     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
17103 
17104     // Otherwise, make sure we propagate the AND to the operand
17105     // of the unpack
17106     Dup = DAG.getNode(ISD::SPLAT_VECTOR, DL, UnpkOp->getValueType(0),
17107                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
17108 
17109     SDValue And = DAG.getNode(ISD::AND, DL,
17110                               UnpkOp->getValueType(0), UnpkOp, Dup);
17111 
17112     return DAG.getNode(Opc, DL, N->getValueType(0), And);
17113   }
17114 
17115   // If both sides of AND operations are i1 splat_vectors then
17116   // we can produce just i1 splat_vector as the result.
17117   if (isAllActivePredicate(DAG, N->getOperand(0)))
17118     return N->getOperand(1);
17119   if (isAllActivePredicate(DAG, N->getOperand(1)))
17120     return N->getOperand(0);
17121 
17122   if (!EnableCombineMGatherIntrinsics)
17123     return SDValue();
17124 
17125   SDValue Mask = N->getOperand(1);
17126 
17127   if (!Src.hasOneUse())
17128     return SDValue();
17129 
17130   EVT MemVT;
17131 
17132   // SVE load instructions perform an implicit zero-extend, which makes them
17133   // perfect candidates for combining.
17134   switch (Opc) {
17135   case AArch64ISD::LD1_MERGE_ZERO:
17136   case AArch64ISD::LDNF1_MERGE_ZERO:
17137   case AArch64ISD::LDFF1_MERGE_ZERO:
17138     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
17139     break;
17140   case AArch64ISD::GLD1_MERGE_ZERO:
17141   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
17142   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
17143   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
17144   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
17145   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
17146   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
17147   case AArch64ISD::GLDFF1_MERGE_ZERO:
17148   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
17149   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
17150   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
17151   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
17152   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
17153   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
17154   case AArch64ISD::GLDNT1_MERGE_ZERO:
17155     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
17156     break;
17157   default:
17158     return SDValue();
17159   }
17160 
17161   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
17162     return Src;
17163 
17164   return SDValue();
17165 }
17166 
17167 static SDValue performANDCombine(SDNode *N,
17168                                  TargetLowering::DAGCombinerInfo &DCI) {
17169   SelectionDAG &DAG = DCI.DAG;
17170   SDValue LHS = N->getOperand(0);
17171   SDValue RHS = N->getOperand(1);
17172   EVT VT = N->getValueType(0);
17173 
17174   if (SDValue R = performANDORCSELCombine(N, DAG))
17175     return R;
17176 
17177   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17178     return SDValue();
17179 
17180   if (VT.isScalableVector())
17181     return performSVEAndCombine(N, DCI);
17182 
17183   // The combining code below works only for NEON vectors. In particular, it
17184   // does not work for SVE when dealing with vectors wider than 128 bits.
17185   if (!VT.is64BitVector() && !VT.is128BitVector())
17186     return SDValue();
17187 
17188   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
17189   if (!BVN)
17190     return SDValue();
17191 
17192   // AND does not accept an immediate, so check if we can use a BIC immediate
17193   // instruction instead. We do this here instead of using a (and x, (mvni imm))
17194   // pattern in isel, because some immediates may be lowered to the preferred
17195   // (and x, (movi imm)) form, even though an mvni representation also exists.
17196   APInt DefBits(VT.getSizeInBits(), 0);
17197   APInt UndefBits(VT.getSizeInBits(), 0);
17198   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
17199     SDValue NewOp;
17200 
17201     // Any bits known to already be 0 need not be cleared again, which can help
17202     // reduce the size of the immediate to one supported by the instruction.
17203     KnownBits Known = DAG.computeKnownBits(LHS);
17204     APInt ZeroSplat(VT.getSizeInBits(), 0);
17205     for (unsigned I = 0; I < VT.getSizeInBits() / Known.Zero.getBitWidth(); I++)
17206       ZeroSplat |= Known.Zero.zext(VT.getSizeInBits())
17207                    << (Known.Zero.getBitWidth() * I);
17208 
17209     DefBits = ~(DefBits | ZeroSplat);
17210     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
17211                                     DefBits, &LHS)) ||
17212         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
17213                                     DefBits, &LHS)))
17214       return NewOp;
17215 
17216     UndefBits = ~(UndefBits | ZeroSplat);
17217     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
17218                                     UndefBits, &LHS)) ||
17219         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
17220                                     UndefBits, &LHS)))
17221       return NewOp;
17222   }
17223 
17224   return SDValue();
17225 }
17226 
17227 static SDValue performFADDCombine(SDNode *N,
17228                                   TargetLowering::DAGCombinerInfo &DCI) {
17229   SelectionDAG &DAG = DCI.DAG;
17230   SDValue LHS = N->getOperand(0);
17231   SDValue RHS = N->getOperand(1);
17232   EVT VT = N->getValueType(0);
17233   SDLoc DL(N);
17234 
17235   if (!N->getFlags().hasAllowReassociation())
17236     return SDValue();
17237 
17238   // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
17239   auto ReassocComplex = [&](SDValue A, SDValue B) {
17240     if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
17241       return SDValue();
17242     unsigned Opc = A.getConstantOperandVal(0);
17243     if (Opc != Intrinsic::aarch64_neon_vcmla_rot0 &&
17244         Opc != Intrinsic::aarch64_neon_vcmla_rot90 &&
17245         Opc != Intrinsic::aarch64_neon_vcmla_rot180 &&
17246         Opc != Intrinsic::aarch64_neon_vcmla_rot270)
17247       return SDValue();
17248     SDValue VCMLA = DAG.getNode(
17249         ISD::INTRINSIC_WO_CHAIN, DL, VT, A.getOperand(0),
17250         DAG.getNode(ISD::FADD, DL, VT, A.getOperand(1), B, N->getFlags()),
17251         A.getOperand(2), A.getOperand(3));
17252     VCMLA->setFlags(A->getFlags());
17253     return VCMLA;
17254   };
17255   if (SDValue R = ReassocComplex(LHS, RHS))
17256     return R;
17257   if (SDValue R = ReassocComplex(RHS, LHS))
17258     return R;
17259 
17260   return SDValue();
17261 }
17262 
17263 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
17264   switch (Opcode) {
17265   case ISD::STRICT_FADD:
17266   case ISD::FADD:
17267     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
17268   case ISD::ADD:
17269     return VT == MVT::i64;
17270   default:
17271     return false;
17272   }
17273 }
17274 
17275 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
17276                         AArch64CC::CondCode Cond);
17277 
17278 static bool isPredicateCCSettingOp(SDValue N) {
17279   if ((N.getOpcode() == ISD::SETCC) ||
17280       (N.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
17281        (N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilege ||
17282         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilegt ||
17283         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilehi ||
17284         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilehs ||
17285         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilele ||
17286         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilelo ||
17287         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilels ||
17288         N.getConstantOperandVal(0) == Intrinsic::aarch64_sve_whilelt ||
17289         // get_active_lane_mask is lowered to a whilelo instruction.
17290         N.getConstantOperandVal(0) == Intrinsic::get_active_lane_mask)))
17291     return true;
17292 
17293   return false;
17294 }
17295 
17296 // Materialize : i1 = extract_vector_elt t37, Constant:i64<0>
17297 // ... into: "ptrue p, all" + PTEST
17298 static SDValue
17299 performFirstTrueTestVectorCombine(SDNode *N,
17300                                   TargetLowering::DAGCombinerInfo &DCI,
17301                                   const AArch64Subtarget *Subtarget) {
17302   assert(N->getOpcode() == ISD::EXTRACT_VECTOR_ELT);
17303   // Make sure PTEST can be legalised with illegal types.
17304   if (!Subtarget->hasSVE() || DCI.isBeforeLegalize())
17305     return SDValue();
17306 
17307   SDValue N0 = N->getOperand(0);
17308   EVT VT = N0.getValueType();
17309 
17310   if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1 ||
17311       !isNullConstant(N->getOperand(1)))
17312     return SDValue();
17313 
17314   // Restricted the DAG combine to only cases where we're extracting from a
17315   // flag-setting operation.
17316   if (!isPredicateCCSettingOp(N0))
17317     return SDValue();
17318 
17319   // Extracts of lane 0 for SVE can be expressed as PTEST(Op, FIRST) ? 1 : 0
17320   SelectionDAG &DAG = DCI.DAG;
17321   SDValue Pg = getPTrue(DAG, SDLoc(N), VT, AArch64SVEPredPattern::all);
17322   return getPTest(DAG, N->getValueType(0), Pg, N0, AArch64CC::FIRST_ACTIVE);
17323 }
17324 
17325 // Materialize : Idx = (add (mul vscale, NumEls), -1)
17326 //               i1 = extract_vector_elt t37, Constant:i64<Idx>
17327 //     ... into: "ptrue p, all" + PTEST
17328 static SDValue
17329 performLastTrueTestVectorCombine(SDNode *N,
17330                                  TargetLowering::DAGCombinerInfo &DCI,
17331                                  const AArch64Subtarget *Subtarget) {
17332   assert(N->getOpcode() == ISD::EXTRACT_VECTOR_ELT);
17333   // Make sure PTEST is legal types.
17334   if (!Subtarget->hasSVE() || DCI.isBeforeLegalize())
17335     return SDValue();
17336 
17337   SDValue N0 = N->getOperand(0);
17338   EVT OpVT = N0.getValueType();
17339 
17340   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
17341     return SDValue();
17342 
17343   // Idx == (add (mul vscale, NumEls), -1)
17344   SDValue Idx = N->getOperand(1);
17345   if (Idx.getOpcode() != ISD::ADD || !isAllOnesConstant(Idx.getOperand(1)))
17346     return SDValue();
17347 
17348   SDValue VS = Idx.getOperand(0);
17349   if (VS.getOpcode() != ISD::VSCALE)
17350     return SDValue();
17351 
17352   unsigned NumEls = OpVT.getVectorElementCount().getKnownMinValue();
17353   if (VS.getConstantOperandVal(0) != NumEls)
17354     return SDValue();
17355 
17356   // Extracts of lane EC-1 for SVE can be expressed as PTEST(Op, LAST) ? 1 : 0
17357   SelectionDAG &DAG = DCI.DAG;
17358   SDValue Pg = getPTrue(DAG, SDLoc(N), OpVT, AArch64SVEPredPattern::all);
17359   return getPTest(DAG, N->getValueType(0), Pg, N0, AArch64CC::LAST_ACTIVE);
17360 }
17361 
17362 static SDValue
17363 performExtractVectorEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
17364                                const AArch64Subtarget *Subtarget) {
17365   assert(N->getOpcode() == ISD::EXTRACT_VECTOR_ELT);
17366   if (SDValue Res = performFirstTrueTestVectorCombine(N, DCI, Subtarget))
17367     return Res;
17368   if (SDValue Res = performLastTrueTestVectorCombine(N, DCI, Subtarget))
17369     return Res;
17370 
17371   SelectionDAG &DAG = DCI.DAG;
17372   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
17373 
17374   EVT VT = N->getValueType(0);
17375   const bool FullFP16 = DAG.getSubtarget<AArch64Subtarget>().hasFullFP16();
17376   bool IsStrict = N0->isStrictFPOpcode();
17377 
17378   // extract(dup x) -> x
17379   if (N0.getOpcode() == AArch64ISD::DUP)
17380     return VT.isInteger() ? DAG.getZExtOrTrunc(N0.getOperand(0), SDLoc(N), VT)
17381                           : N0.getOperand(0);
17382 
17383   // Rewrite for pairwise fadd pattern
17384   //   (f32 (extract_vector_elt
17385   //           (fadd (vXf32 Other)
17386   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
17387   // ->
17388   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
17389   //              (extract_vector_elt (vXf32 Other) 1))
17390   // For strict_fadd we need to make sure the old strict_fadd can be deleted, so
17391   // we can only do this when it's used only by the extract_vector_elt.
17392   if (isNullConstant(N1) && hasPairwiseAdd(N0->getOpcode(), VT, FullFP16) &&
17393       (!IsStrict || N0.hasOneUse())) {
17394     SDLoc DL(N0);
17395     SDValue N00 = N0->getOperand(IsStrict ? 1 : 0);
17396     SDValue N01 = N0->getOperand(IsStrict ? 2 : 1);
17397 
17398     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
17399     SDValue Other = N00;
17400 
17401     // And handle the commutative case.
17402     if (!Shuffle) {
17403       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
17404       Other = N01;
17405     }
17406 
17407     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
17408         Other == Shuffle->getOperand(0)) {
17409       SDValue Extract1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
17410                                      DAG.getConstant(0, DL, MVT::i64));
17411       SDValue Extract2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
17412                                      DAG.getConstant(1, DL, MVT::i64));
17413       if (!IsStrict)
17414         return DAG.getNode(N0->getOpcode(), DL, VT, Extract1, Extract2);
17415 
17416       // For strict_fadd we need uses of the final extract_vector to be replaced
17417       // with the strict_fadd, but we also need uses of the chain output of the
17418       // original strict_fadd to use the chain output of the new strict_fadd as
17419       // otherwise it may not be deleted.
17420       SDValue Ret = DAG.getNode(N0->getOpcode(), DL,
17421                                 {VT, MVT::Other},
17422                                 {N0->getOperand(0), Extract1, Extract2});
17423       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Ret);
17424       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Ret.getValue(1));
17425       return SDValue(N, 0);
17426     }
17427   }
17428 
17429   return SDValue();
17430 }
17431 
17432 static SDValue performConcatVectorsCombine(SDNode *N,
17433                                            TargetLowering::DAGCombinerInfo &DCI,
17434                                            SelectionDAG &DAG) {
17435   SDLoc dl(N);
17436   EVT VT = N->getValueType(0);
17437   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
17438   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
17439 
17440   if (VT.isScalableVector())
17441     return SDValue();
17442 
17443   // Optimize concat_vectors of truncated vectors, where the intermediate
17444   // type is illegal, to avoid said illegality,  e.g.,
17445   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
17446   //                          (v2i16 (truncate (v2i64)))))
17447   // ->
17448   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
17449   //                                    (v4i32 (bitcast (v2i64))),
17450   //                                    <0, 2, 4, 6>)))
17451   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
17452   // on both input and result type, so we might generate worse code.
17453   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
17454   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
17455       N1Opc == ISD::TRUNCATE) {
17456     SDValue N00 = N0->getOperand(0);
17457     SDValue N10 = N1->getOperand(0);
17458     EVT N00VT = N00.getValueType();
17459 
17460     if (N00VT == N10.getValueType() &&
17461         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
17462         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
17463       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
17464       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
17465       for (size_t i = 0; i < Mask.size(); ++i)
17466         Mask[i] = i * 2;
17467       return DAG.getNode(ISD::TRUNCATE, dl, VT,
17468                          DAG.getVectorShuffle(
17469                              MidVT, dl,
17470                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
17471                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
17472     }
17473   }
17474 
17475   if (N->getOperand(0).getValueType() == MVT::v4i8) {
17476     // If we have a concat of v4i8 loads, convert them to a buildvector of f32
17477     // loads to prevent having to go through the v4i8 load legalization that
17478     // needs to extend each element into a larger type.
17479     if (N->getNumOperands() % 2 == 0 && all_of(N->op_values(), [](SDValue V) {
17480           if (V.getValueType() != MVT::v4i8)
17481             return false;
17482           if (V.isUndef())
17483             return true;
17484           LoadSDNode *LD = dyn_cast<LoadSDNode>(V);
17485           return LD && V.hasOneUse() && LD->isSimple() && !LD->isIndexed() &&
17486                  LD->getExtensionType() == ISD::NON_EXTLOAD;
17487         })) {
17488       EVT NVT =
17489           EVT::getVectorVT(*DAG.getContext(), MVT::f32, N->getNumOperands());
17490       SmallVector<SDValue> Ops;
17491 
17492       for (unsigned i = 0; i < N->getNumOperands(); i++) {
17493         SDValue V = N->getOperand(i);
17494         if (V.isUndef())
17495           Ops.push_back(DAG.getUNDEF(MVT::f32));
17496         else {
17497           LoadSDNode *LD = cast<LoadSDNode>(V);
17498           SDValue NewLoad =
17499               DAG.getLoad(MVT::f32, dl, LD->getChain(), LD->getBasePtr(),
17500                           LD->getMemOperand());
17501           DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLoad.getValue(1));
17502           Ops.push_back(NewLoad);
17503         }
17504       }
17505       return DAG.getBitcast(N->getValueType(0),
17506                             DAG.getBuildVector(NVT, dl, Ops));
17507     }
17508   }
17509 
17510   // Canonicalise concat_vectors to replace concatenations of truncated nots
17511   // with nots of concatenated truncates. This in some cases allows for multiple
17512   // redundant negations to be eliminated.
17513   //  (concat_vectors (v4i16 (truncate (not (v4i32)))),
17514   //                  (v4i16 (truncate (not (v4i32)))))
17515   // ->
17516   //  (not (concat_vectors (v4i16 (truncate (v4i32))),
17517   //                       (v4i16 (truncate (v4i32)))))
17518   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
17519       N1Opc == ISD::TRUNCATE && N->isOnlyUserOf(N0.getNode()) &&
17520       N->isOnlyUserOf(N1.getNode())) {
17521     auto isBitwiseVectorNegate = [](SDValue V) {
17522       return V->getOpcode() == ISD::XOR &&
17523              ISD::isConstantSplatVectorAllOnes(V.getOperand(1).getNode());
17524     };
17525     SDValue N00 = N0->getOperand(0);
17526     SDValue N10 = N1->getOperand(0);
17527     if (isBitwiseVectorNegate(N00) && N0->isOnlyUserOf(N00.getNode()) &&
17528         isBitwiseVectorNegate(N10) && N1->isOnlyUserOf(N10.getNode())) {
17529       return DAG.getNOT(
17530           dl,
17531           DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17532                       DAG.getNode(ISD::TRUNCATE, dl, N0.getValueType(),
17533                                   N00->getOperand(0)),
17534                       DAG.getNode(ISD::TRUNCATE, dl, N1.getValueType(),
17535                                   N10->getOperand(0))),
17536           VT);
17537     }
17538   }
17539 
17540   // Wait till after everything is legalized to try this. That way we have
17541   // legal vector types and such.
17542   if (DCI.isBeforeLegalizeOps())
17543     return SDValue();
17544 
17545   // Optimise concat_vectors of two [us]avgceils or [us]avgfloors that use
17546   // extracted subvectors from the same original vectors. Combine these into a
17547   // single avg that operates on the two original vectors.
17548   // avgceil is the target independant name for rhadd, avgfloor is a hadd.
17549   // Example:
17550   //  (concat_vectors (v8i8 (avgceils (extract_subvector (v16i8 OpA, <0>),
17551   //                                   extract_subvector (v16i8 OpB, <0>))),
17552   //                  (v8i8 (avgceils (extract_subvector (v16i8 OpA, <8>),
17553   //                                   extract_subvector (v16i8 OpB, <8>)))))
17554   // ->
17555   //  (v16i8(avgceils(v16i8 OpA, v16i8 OpB)))
17556   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
17557       (N0Opc == ISD::AVGCEILU || N0Opc == ISD::AVGCEILS ||
17558        N0Opc == ISD::AVGFLOORU || N0Opc == ISD::AVGFLOORS)) {
17559     SDValue N00 = N0->getOperand(0);
17560     SDValue N01 = N0->getOperand(1);
17561     SDValue N10 = N1->getOperand(0);
17562     SDValue N11 = N1->getOperand(1);
17563 
17564     EVT N00VT = N00.getValueType();
17565     EVT N10VT = N10.getValueType();
17566 
17567     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
17568         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
17569         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
17570         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
17571       SDValue N00Source = N00->getOperand(0);
17572       SDValue N01Source = N01->getOperand(0);
17573       SDValue N10Source = N10->getOperand(0);
17574       SDValue N11Source = N11->getOperand(0);
17575 
17576       if (N00Source == N10Source && N01Source == N11Source &&
17577           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
17578         assert(N0.getValueType() == N1.getValueType());
17579 
17580         uint64_t N00Index = N00.getConstantOperandVal(1);
17581         uint64_t N01Index = N01.getConstantOperandVal(1);
17582         uint64_t N10Index = N10.getConstantOperandVal(1);
17583         uint64_t N11Index = N11.getConstantOperandVal(1);
17584 
17585         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
17586             N10Index == N00VT.getVectorNumElements())
17587           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
17588       }
17589     }
17590   }
17591 
17592   auto IsRSHRN = [](SDValue Shr) {
17593     if (Shr.getOpcode() != AArch64ISD::VLSHR)
17594       return false;
17595     SDValue Op = Shr.getOperand(0);
17596     EVT VT = Op.getValueType();
17597     unsigned ShtAmt = Shr.getConstantOperandVal(1);
17598     if (ShtAmt > VT.getScalarSizeInBits() / 2 || Op.getOpcode() != ISD::ADD)
17599       return false;
17600 
17601     APInt Imm;
17602     if (Op.getOperand(1).getOpcode() == AArch64ISD::MOVIshift)
17603       Imm = APInt(VT.getScalarSizeInBits(),
17604                   Op.getOperand(1).getConstantOperandVal(0)
17605                       << Op.getOperand(1).getConstantOperandVal(1));
17606     else if (Op.getOperand(1).getOpcode() == AArch64ISD::DUP &&
17607              isa<ConstantSDNode>(Op.getOperand(1).getOperand(0)))
17608       Imm = APInt(VT.getScalarSizeInBits(),
17609                   Op.getOperand(1).getConstantOperandVal(0));
17610     else
17611       return false;
17612 
17613     if (Imm != 1ULL << (ShtAmt - 1))
17614       return false;
17615     return true;
17616   };
17617 
17618   // concat(rshrn(x), rshrn(y)) -> rshrn(concat(x, y))
17619   if (N->getNumOperands() == 2 && IsRSHRN(N0) &&
17620       ((IsRSHRN(N1) &&
17621         N0.getConstantOperandVal(1) == N1.getConstantOperandVal(1)) ||
17622        N1.isUndef())) {
17623     SDValue X = N0.getOperand(0).getOperand(0);
17624     SDValue Y = N1.isUndef() ? DAG.getUNDEF(X.getValueType())
17625                              : N1.getOperand(0).getOperand(0);
17626     EVT BVT =
17627         X.getValueType().getDoubleNumVectorElementsVT(*DCI.DAG.getContext());
17628     SDValue CC = DAG.getNode(ISD::CONCAT_VECTORS, dl, BVT, X, Y);
17629     SDValue Add = DAG.getNode(
17630         ISD::ADD, dl, BVT, CC,
17631         DAG.getConstant(1ULL << (N0.getConstantOperandVal(1) - 1), dl, BVT));
17632     SDValue Shr =
17633         DAG.getNode(AArch64ISD::VLSHR, dl, BVT, Add, N0.getOperand(1));
17634     return Shr;
17635   }
17636 
17637   // concat(zip1(a, b), zip2(a, b)) is zip1(a, b)
17638   if (N->getNumOperands() == 2 && N0Opc == AArch64ISD::ZIP1 &&
17639       N1Opc == AArch64ISD::ZIP2 && N0.getOperand(0) == N1.getOperand(0) &&
17640       N0.getOperand(1) == N1.getOperand(1)) {
17641     SDValue E0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, N0.getOperand(0),
17642                              DAG.getUNDEF(N0.getValueType()));
17643     SDValue E1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, N0.getOperand(1),
17644                              DAG.getUNDEF(N0.getValueType()));
17645     return DAG.getNode(AArch64ISD::ZIP1, dl, VT, E0, E1);
17646   }
17647 
17648   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
17649   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
17650   // canonicalise to that.
17651   if (N->getNumOperands() == 2 && N0 == N1 && VT.getVectorNumElements() == 2) {
17652     assert(VT.getScalarSizeInBits() == 64);
17653     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
17654                        DAG.getConstant(0, dl, MVT::i64));
17655   }
17656 
17657   // Canonicalise concat_vectors so that the right-hand vector has as few
17658   // bit-casts as possible before its real operation. The primary matching
17659   // destination for these operations will be the narrowing "2" instructions,
17660   // which depend on the operation being performed on this right-hand vector.
17661   // For example,
17662   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
17663   // becomes
17664   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
17665 
17666   if (N->getNumOperands() != 2 || N1Opc != ISD::BITCAST)
17667     return SDValue();
17668   SDValue RHS = N1->getOperand(0);
17669   MVT RHSTy = RHS.getValueType().getSimpleVT();
17670   // If the RHS is not a vector, this is not the pattern we're looking for.
17671   if (!RHSTy.isVector())
17672     return SDValue();
17673 
17674   LLVM_DEBUG(
17675       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
17676 
17677   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
17678                                   RHSTy.getVectorNumElements() * 2);
17679   return DAG.getNode(ISD::BITCAST, dl, VT,
17680                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
17681                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
17682                                  RHS));
17683 }
17684 
17685 static SDValue
17686 performExtractSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
17687                                SelectionDAG &DAG) {
17688   if (DCI.isBeforeLegalizeOps())
17689     return SDValue();
17690 
17691   EVT VT = N->getValueType(0);
17692   if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
17693     return SDValue();
17694 
17695   SDValue V = N->getOperand(0);
17696 
17697   // NOTE: This combine exists in DAGCombiner, but that version's legality check
17698   // blocks this combine because the non-const case requires custom lowering.
17699   //
17700   // ty1 extract_vector(ty2 splat(const))) -> ty1 splat(const)
17701   if (V.getOpcode() == ISD::SPLAT_VECTOR)
17702     if (isa<ConstantSDNode>(V.getOperand(0)))
17703       return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V.getOperand(0));
17704 
17705   return SDValue();
17706 }
17707 
17708 static SDValue
17709 performInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
17710                               SelectionDAG &DAG) {
17711   SDLoc DL(N);
17712   SDValue Vec = N->getOperand(0);
17713   SDValue SubVec = N->getOperand(1);
17714   uint64_t IdxVal = N->getConstantOperandVal(2);
17715   EVT VecVT = Vec.getValueType();
17716   EVT SubVT = SubVec.getValueType();
17717 
17718   // Only do this for legal fixed vector types.
17719   if (!VecVT.isFixedLengthVector() ||
17720       !DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
17721       !DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
17722     return SDValue();
17723 
17724   // Ignore widening patterns.
17725   if (IdxVal == 0 && Vec.isUndef())
17726     return SDValue();
17727 
17728   // Subvector must be half the width and an "aligned" insertion.
17729   unsigned NumSubElts = SubVT.getVectorNumElements();
17730   if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
17731       (IdxVal != 0 && IdxVal != NumSubElts))
17732     return SDValue();
17733 
17734   // Fold insert_subvector -> concat_vectors
17735   // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
17736   // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
17737   SDValue Lo, Hi;
17738   if (IdxVal == 0) {
17739     Lo = SubVec;
17740     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
17741                      DAG.getVectorIdxConstant(NumSubElts, DL));
17742   } else {
17743     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
17744                      DAG.getVectorIdxConstant(0, DL));
17745     Hi = SubVec;
17746   }
17747   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
17748 }
17749 
17750 static SDValue tryCombineFixedPointConvert(SDNode *N,
17751                                            TargetLowering::DAGCombinerInfo &DCI,
17752                                            SelectionDAG &DAG) {
17753   // Wait until after everything is legalized to try this. That way we have
17754   // legal vector types and such.
17755   if (DCI.isBeforeLegalizeOps())
17756     return SDValue();
17757   // Transform a scalar conversion of a value from a lane extract into a
17758   // lane extract of a vector conversion. E.g., from foo1 to foo2:
17759   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
17760   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
17761   //
17762   // The second form interacts better with instruction selection and the
17763   // register allocator to avoid cross-class register copies that aren't
17764   // coalescable due to a lane reference.
17765 
17766   // Check the operand and see if it originates from a lane extract.
17767   SDValue Op1 = N->getOperand(1);
17768   if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17769     return SDValue();
17770 
17771   // Yep, no additional predication needed. Perform the transform.
17772   SDValue IID = N->getOperand(0);
17773   SDValue Shift = N->getOperand(2);
17774   SDValue Vec = Op1.getOperand(0);
17775   SDValue Lane = Op1.getOperand(1);
17776   EVT ResTy = N->getValueType(0);
17777   EVT VecResTy;
17778   SDLoc DL(N);
17779 
17780   // The vector width should be 128 bits by the time we get here, even
17781   // if it started as 64 bits (the extract_vector handling will have
17782   // done so). Bail if it is not.
17783   if (Vec.getValueSizeInBits() != 128)
17784     return SDValue();
17785 
17786   if (Vec.getValueType() == MVT::v4i32)
17787     VecResTy = MVT::v4f32;
17788   else if (Vec.getValueType() == MVT::v2i64)
17789     VecResTy = MVT::v2f64;
17790   else
17791     return SDValue();
17792 
17793   SDValue Convert =
17794       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
17795   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
17796 }
17797 
17798 // AArch64 high-vector "long" operations are formed by performing the non-high
17799 // version on an extract_subvector of each operand which gets the high half:
17800 //
17801 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
17802 //
17803 // However, there are cases which don't have an extract_high explicitly, but
17804 // have another operation that can be made compatible with one for free. For
17805 // example:
17806 //
17807 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
17808 //
17809 // This routine does the actual conversion of such DUPs, once outer routines
17810 // have determined that everything else is in order.
17811 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
17812 // similarly here.
17813 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
17814   MVT VT = N.getSimpleValueType();
17815   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
17816       N.getConstantOperandVal(1) == 0)
17817     N = N.getOperand(0);
17818 
17819   switch (N.getOpcode()) {
17820   case AArch64ISD::DUP:
17821   case AArch64ISD::DUPLANE8:
17822   case AArch64ISD::DUPLANE16:
17823   case AArch64ISD::DUPLANE32:
17824   case AArch64ISD::DUPLANE64:
17825   case AArch64ISD::MOVI:
17826   case AArch64ISD::MOVIshift:
17827   case AArch64ISD::MOVIedit:
17828   case AArch64ISD::MOVImsl:
17829   case AArch64ISD::MVNIshift:
17830   case AArch64ISD::MVNImsl:
17831     break;
17832   default:
17833     // FMOV could be supported, but isn't very useful, as it would only occur
17834     // if you passed a bitcast' floating point immediate to an eligible long
17835     // integer op (addl, smull, ...).
17836     return SDValue();
17837   }
17838 
17839   if (!VT.is64BitVector())
17840     return SDValue();
17841 
17842   SDLoc DL(N);
17843   unsigned NumElems = VT.getVectorNumElements();
17844   if (N.getValueType().is64BitVector()) {
17845     MVT ElementTy = VT.getVectorElementType();
17846     MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
17847     N = DAG.getNode(N->getOpcode(), DL, NewVT, N->ops());
17848   }
17849 
17850   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N,
17851                      DAG.getConstant(NumElems, DL, MVT::i64));
17852 }
17853 
17854 static bool isEssentiallyExtractHighSubvector(SDValue N) {
17855   if (N.getOpcode() == ISD::BITCAST)
17856     N = N.getOperand(0);
17857   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
17858     return false;
17859   if (N.getOperand(0).getValueType().isScalableVector())
17860     return false;
17861   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
17862          N.getOperand(0).getValueType().getVectorNumElements() / 2;
17863 }
17864 
17865 /// Helper structure to keep track of ISD::SET_CC operands.
17866 struct GenericSetCCInfo {
17867   const SDValue *Opnd0;
17868   const SDValue *Opnd1;
17869   ISD::CondCode CC;
17870 };
17871 
17872 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
17873 struct AArch64SetCCInfo {
17874   const SDValue *Cmp;
17875   AArch64CC::CondCode CC;
17876 };
17877 
17878 /// Helper structure to keep track of SetCC information.
17879 union SetCCInfo {
17880   GenericSetCCInfo Generic;
17881   AArch64SetCCInfo AArch64;
17882 };
17883 
17884 /// Helper structure to be able to read SetCC information.  If set to
17885 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
17886 /// GenericSetCCInfo.
17887 struct SetCCInfoAndKind {
17888   SetCCInfo Info;
17889   bool IsAArch64;
17890 };
17891 
17892 /// Check whether or not \p Op is a SET_CC operation, either a generic or
17893 /// an
17894 /// AArch64 lowered one.
17895 /// \p SetCCInfo is filled accordingly.
17896 /// \post SetCCInfo is meanginfull only when this function returns true.
17897 /// \return True when Op is a kind of SET_CC operation.
17898 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
17899   // If this is a setcc, this is straight forward.
17900   if (Op.getOpcode() == ISD::SETCC) {
17901     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
17902     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
17903     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
17904     SetCCInfo.IsAArch64 = false;
17905     return true;
17906   }
17907   // Otherwise, check if this is a matching csel instruction.
17908   // In other words:
17909   // - csel 1, 0, cc
17910   // - csel 0, 1, !cc
17911   if (Op.getOpcode() != AArch64ISD::CSEL)
17912     return false;
17913   // Set the information about the operands.
17914   // TODO: we want the operands of the Cmp not the csel
17915   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
17916   SetCCInfo.IsAArch64 = true;
17917   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
17918       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17919 
17920   // Check that the operands matches the constraints:
17921   // (1) Both operands must be constants.
17922   // (2) One must be 1 and the other must be 0.
17923   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
17924   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
17925 
17926   // Check (1).
17927   if (!TValue || !FValue)
17928     return false;
17929 
17930   // Check (2).
17931   if (!TValue->isOne()) {
17932     // Update the comparison when we are interested in !cc.
17933     std::swap(TValue, FValue);
17934     SetCCInfo.Info.AArch64.CC =
17935         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
17936   }
17937   return TValue->isOne() && FValue->isZero();
17938 }
17939 
17940 // Returns true if Op is setcc or zext of setcc.
17941 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
17942   if (isSetCC(Op, Info))
17943     return true;
17944   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
17945     isSetCC(Op->getOperand(0), Info));
17946 }
17947 
17948 // The folding we want to perform is:
17949 // (add x, [zext] (setcc cc ...) )
17950 //   -->
17951 // (csel x, (add x, 1), !cc ...)
17952 //
17953 // The latter will get matched to a CSINC instruction.
17954 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
17955   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
17956   SDValue LHS = Op->getOperand(0);
17957   SDValue RHS = Op->getOperand(1);
17958   SetCCInfoAndKind InfoAndKind;
17959 
17960   // If both operands are a SET_CC, then we don't want to perform this
17961   // folding and create another csel as this results in more instructions
17962   // (and higher register usage).
17963   if (isSetCCOrZExtSetCC(LHS, InfoAndKind) &&
17964       isSetCCOrZExtSetCC(RHS, InfoAndKind))
17965     return SDValue();
17966 
17967   // If neither operand is a SET_CC, give up.
17968   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
17969     std::swap(LHS, RHS);
17970     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
17971       return SDValue();
17972   }
17973 
17974   // FIXME: This could be generatized to work for FP comparisons.
17975   EVT CmpVT = InfoAndKind.IsAArch64
17976                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
17977                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
17978   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
17979     return SDValue();
17980 
17981   SDValue CCVal;
17982   SDValue Cmp;
17983   SDLoc dl(Op);
17984   if (InfoAndKind.IsAArch64) {
17985     CCVal = DAG.getConstant(
17986         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
17987         MVT::i32);
17988     Cmp = *InfoAndKind.Info.AArch64.Cmp;
17989   } else
17990     Cmp = getAArch64Cmp(
17991         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
17992         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
17993         dl);
17994 
17995   EVT VT = Op->getValueType(0);
17996   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
17997   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
17998 }
17999 
18000 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
18001 static SDValue performAddUADDVCombine(SDNode *N, SelectionDAG &DAG) {
18002   EVT VT = N->getValueType(0);
18003   // Only scalar integer and vector types.
18004   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
18005     return SDValue();
18006 
18007   SDValue LHS = N->getOperand(0);
18008   SDValue RHS = N->getOperand(1);
18009   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18010       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
18011     return SDValue();
18012 
18013   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
18014   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
18015   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isZero())
18016     return SDValue();
18017 
18018   SDValue Op1 = LHS->getOperand(0);
18019   SDValue Op2 = RHS->getOperand(0);
18020   EVT OpVT1 = Op1.getValueType();
18021   EVT OpVT2 = Op2.getValueType();
18022   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
18023       Op2.getOpcode() != AArch64ISD::UADDV ||
18024       OpVT1.getVectorElementType() != VT)
18025     return SDValue();
18026 
18027   SDValue Val1 = Op1.getOperand(0);
18028   SDValue Val2 = Op2.getOperand(0);
18029   EVT ValVT = Val1->getValueType(0);
18030   SDLoc DL(N);
18031   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
18032   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
18033                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
18034                      DAG.getConstant(0, DL, MVT::i64));
18035 }
18036 
18037 /// Perform the scalar expression combine in the form of:
18038 ///   CSEL(c, 1, cc) + b => CSINC(b+c, b, cc)
18039 ///   CSNEG(c, -1, cc) + b => CSINC(b+c, b, cc)
18040 static SDValue performAddCSelIntoCSinc(SDNode *N, SelectionDAG &DAG) {
18041   EVT VT = N->getValueType(0);
18042   if (!VT.isScalarInteger() || N->getOpcode() != ISD::ADD)
18043     return SDValue();
18044 
18045   SDValue LHS = N->getOperand(0);
18046   SDValue RHS = N->getOperand(1);
18047 
18048   // Handle commutivity.
18049   if (LHS.getOpcode() != AArch64ISD::CSEL &&
18050       LHS.getOpcode() != AArch64ISD::CSNEG) {
18051     std::swap(LHS, RHS);
18052     if (LHS.getOpcode() != AArch64ISD::CSEL &&
18053         LHS.getOpcode() != AArch64ISD::CSNEG) {
18054       return SDValue();
18055     }
18056   }
18057 
18058   if (!LHS.hasOneUse())
18059     return SDValue();
18060 
18061   AArch64CC::CondCode AArch64CC =
18062       static_cast<AArch64CC::CondCode>(LHS.getConstantOperandVal(2));
18063 
18064   // The CSEL should include a const one operand, and the CSNEG should include
18065   // One or NegOne operand.
18066   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(LHS.getOperand(0));
18067   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
18068   if (!CTVal || !CFVal)
18069     return SDValue();
18070 
18071   if (!(LHS.getOpcode() == AArch64ISD::CSEL &&
18072         (CTVal->isOne() || CFVal->isOne())) &&
18073       !(LHS.getOpcode() == AArch64ISD::CSNEG &&
18074         (CTVal->isOne() || CFVal->isAllOnes())))
18075     return SDValue();
18076 
18077   // Switch CSEL(1, c, cc) to CSEL(c, 1, !cc)
18078   if (LHS.getOpcode() == AArch64ISD::CSEL && CTVal->isOne() &&
18079       !CFVal->isOne()) {
18080     std::swap(CTVal, CFVal);
18081     AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
18082   }
18083 
18084   SDLoc DL(N);
18085   // Switch CSNEG(1, c, cc) to CSNEG(-c, -1, !cc)
18086   if (LHS.getOpcode() == AArch64ISD::CSNEG && CTVal->isOne() &&
18087       !CFVal->isAllOnes()) {
18088     APInt C = -1 * CFVal->getAPIntValue();
18089     CTVal = cast<ConstantSDNode>(DAG.getConstant(C, DL, VT));
18090     CFVal = cast<ConstantSDNode>(DAG.getAllOnesConstant(DL, VT));
18091     AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
18092   }
18093 
18094   // It might be neutral for larger constants, as the immediate need to be
18095   // materialized in a register.
18096   APInt ADDC = CTVal->getAPIntValue();
18097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18098   if (!TLI.isLegalAddImmediate(ADDC.getSExtValue()))
18099     return SDValue();
18100 
18101   assert(((LHS.getOpcode() == AArch64ISD::CSEL && CFVal->isOne()) ||
18102           (LHS.getOpcode() == AArch64ISD::CSNEG && CFVal->isAllOnes())) &&
18103          "Unexpected constant value");
18104 
18105   SDValue NewNode = DAG.getNode(ISD::ADD, DL, VT, RHS, SDValue(CTVal, 0));
18106   SDValue CCVal = DAG.getConstant(AArch64CC, DL, MVT::i32);
18107   SDValue Cmp = LHS.getOperand(3);
18108 
18109   return DAG.getNode(AArch64ISD::CSINC, DL, VT, NewNode, RHS, CCVal, Cmp);
18110 }
18111 
18112 // ADD(UDOT(zero, x, y), A) -->  UDOT(A, x, y)
18113 static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) {
18114   EVT VT = N->getValueType(0);
18115   if (N->getOpcode() != ISD::ADD)
18116     return SDValue();
18117 
18118   SDValue Dot = N->getOperand(0);
18119   SDValue A = N->getOperand(1);
18120   // Handle commutivity
18121   auto isZeroDot = [](SDValue Dot) {
18122     return (Dot.getOpcode() == AArch64ISD::UDOT ||
18123             Dot.getOpcode() == AArch64ISD::SDOT) &&
18124            isZerosVector(Dot.getOperand(0).getNode());
18125   };
18126   if (!isZeroDot(Dot))
18127     std::swap(Dot, A);
18128   if (!isZeroDot(Dot))
18129     return SDValue();
18130 
18131   return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1),
18132                      Dot.getOperand(2));
18133 }
18134 
18135 static bool isNegatedInteger(SDValue Op) {
18136   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0));
18137 }
18138 
18139 static SDValue getNegatedInteger(SDValue Op, SelectionDAG &DAG) {
18140   SDLoc DL(Op);
18141   EVT VT = Op.getValueType();
18142   SDValue Zero = DAG.getConstant(0, DL, VT);
18143   return DAG.getNode(ISD::SUB, DL, VT, Zero, Op);
18144 }
18145 
18146 // Try to fold
18147 //
18148 // (neg (csel X, Y)) -> (csel (neg X), (neg Y))
18149 //
18150 // The folding helps csel to be matched with csneg without generating
18151 // redundant neg instruction, which includes negation of the csel expansion
18152 // of abs node lowered by lowerABS.
18153 static SDValue performNegCSelCombine(SDNode *N, SelectionDAG &DAG) {
18154   if (!isNegatedInteger(SDValue(N, 0)))
18155     return SDValue();
18156 
18157   SDValue CSel = N->getOperand(1);
18158   if (CSel.getOpcode() != AArch64ISD::CSEL || !CSel->hasOneUse())
18159     return SDValue();
18160 
18161   SDValue N0 = CSel.getOperand(0);
18162   SDValue N1 = CSel.getOperand(1);
18163 
18164   // If both of them is not negations, it's not worth the folding as it
18165   // introduces two additional negations while reducing one negation.
18166   if (!isNegatedInteger(N0) && !isNegatedInteger(N1))
18167     return SDValue();
18168 
18169   SDValue N0N = getNegatedInteger(N0, DAG);
18170   SDValue N1N = getNegatedInteger(N1, DAG);
18171 
18172   SDLoc DL(N);
18173   EVT VT = CSel.getValueType();
18174   return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0N, N1N, CSel.getOperand(2),
18175                      CSel.getOperand(3));
18176 }
18177 
18178 // The basic add/sub long vector instructions have variants with "2" on the end
18179 // which act on the high-half of their inputs. They are normally matched by
18180 // patterns like:
18181 //
18182 // (add (zeroext (extract_high LHS)),
18183 //      (zeroext (extract_high RHS)))
18184 // -> uaddl2 vD, vN, vM
18185 //
18186 // However, if one of the extracts is something like a duplicate, this
18187 // instruction can still be used profitably. This function puts the DAG into a
18188 // more appropriate form for those patterns to trigger.
18189 static SDValue performAddSubLongCombine(SDNode *N,
18190                                         TargetLowering::DAGCombinerInfo &DCI) {
18191   SelectionDAG &DAG = DCI.DAG;
18192   if (DCI.isBeforeLegalizeOps())
18193     return SDValue();
18194 
18195   MVT VT = N->getSimpleValueType(0);
18196   if (!VT.is128BitVector()) {
18197     if (N->getOpcode() == ISD::ADD)
18198       return performSetccAddFolding(N, DAG);
18199     return SDValue();
18200   }
18201 
18202   // Make sure both branches are extended in the same way.
18203   SDValue LHS = N->getOperand(0);
18204   SDValue RHS = N->getOperand(1);
18205   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
18206        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
18207       LHS.getOpcode() != RHS.getOpcode())
18208     return SDValue();
18209 
18210   unsigned ExtType = LHS.getOpcode();
18211 
18212   // It's not worth doing if at least one of the inputs isn't already an
18213   // extract, but we don't know which it'll be so we have to try both.
18214   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
18215     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
18216     if (!RHS.getNode())
18217       return SDValue();
18218 
18219     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
18220   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
18221     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
18222     if (!LHS.getNode())
18223       return SDValue();
18224 
18225     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
18226   }
18227 
18228   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
18229 }
18230 
18231 static bool isCMP(SDValue Op) {
18232   return Op.getOpcode() == AArch64ISD::SUBS &&
18233          !Op.getNode()->hasAnyUseOfValue(0);
18234 }
18235 
18236 // (CSEL 1 0 CC Cond) => CC
18237 // (CSEL 0 1 CC Cond) => !CC
18238 static std::optional<AArch64CC::CondCode> getCSETCondCode(SDValue Op) {
18239   if (Op.getOpcode() != AArch64ISD::CSEL)
18240     return std::nullopt;
18241   auto CC = static_cast<AArch64CC::CondCode>(Op.getConstantOperandVal(2));
18242   if (CC == AArch64CC::AL || CC == AArch64CC::NV)
18243     return std::nullopt;
18244   SDValue OpLHS = Op.getOperand(0);
18245   SDValue OpRHS = Op.getOperand(1);
18246   if (isOneConstant(OpLHS) && isNullConstant(OpRHS))
18247     return CC;
18248   if (isNullConstant(OpLHS) && isOneConstant(OpRHS))
18249     return getInvertedCondCode(CC);
18250 
18251   return std::nullopt;
18252 }
18253 
18254 // (ADC{S} l r (CMP (CSET HS carry) 1)) => (ADC{S} l r carry)
18255 // (SBC{S} l r (CMP 0 (CSET LO carry))) => (SBC{S} l r carry)
18256 static SDValue foldOverflowCheck(SDNode *Op, SelectionDAG &DAG, bool IsAdd) {
18257   SDValue CmpOp = Op->getOperand(2);
18258   if (!isCMP(CmpOp))
18259     return SDValue();
18260 
18261   if (IsAdd) {
18262     if (!isOneConstant(CmpOp.getOperand(1)))
18263       return SDValue();
18264   } else {
18265     if (!isNullConstant(CmpOp.getOperand(0)))
18266       return SDValue();
18267   }
18268 
18269   SDValue CsetOp = CmpOp->getOperand(IsAdd ? 0 : 1);
18270   auto CC = getCSETCondCode(CsetOp);
18271   if (CC != (IsAdd ? AArch64CC::HS : AArch64CC::LO))
18272     return SDValue();
18273 
18274   return DAG.getNode(Op->getOpcode(), SDLoc(Op), Op->getVTList(),
18275                      Op->getOperand(0), Op->getOperand(1),
18276                      CsetOp.getOperand(3));
18277 }
18278 
18279 // (ADC x 0 cond) => (CINC x HS cond)
18280 static SDValue foldADCToCINC(SDNode *N, SelectionDAG &DAG) {
18281   SDValue LHS = N->getOperand(0);
18282   SDValue RHS = N->getOperand(1);
18283   SDValue Cond = N->getOperand(2);
18284 
18285   if (!isNullConstant(RHS))
18286     return SDValue();
18287 
18288   EVT VT = N->getValueType(0);
18289   SDLoc DL(N);
18290 
18291   // (CINC x cc cond) <=> (CSINC x x !cc cond)
18292   SDValue CC = DAG.getConstant(AArch64CC::LO, DL, MVT::i32);
18293   return DAG.getNode(AArch64ISD::CSINC, DL, VT, LHS, LHS, CC, Cond);
18294 }
18295 
18296 // Transform vector add(zext i8 to i32, zext i8 to i32)
18297 //  into sext(add(zext(i8 to i16), zext(i8 to i16)) to i32)
18298 // This allows extra uses of saddl/uaddl at the lower vector widths, and less
18299 // extends.
18300 static SDValue performVectorAddSubExtCombine(SDNode *N, SelectionDAG &DAG) {
18301   EVT VT = N->getValueType(0);
18302   if (!VT.isFixedLengthVector() || VT.getSizeInBits() <= 128 ||
18303       (N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
18304        N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND) ||
18305       (N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
18306        N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND) ||
18307       N->getOperand(0).getOperand(0).getValueType() !=
18308           N->getOperand(1).getOperand(0).getValueType())
18309     return SDValue();
18310 
18311   SDValue N0 = N->getOperand(0).getOperand(0);
18312   SDValue N1 = N->getOperand(1).getOperand(0);
18313   EVT InVT = N0.getValueType();
18314 
18315   EVT S1 = InVT.getScalarType();
18316   EVT S2 = VT.getScalarType();
18317   if ((S2 == MVT::i32 && S1 == MVT::i8) ||
18318       (S2 == MVT::i64 && (S1 == MVT::i8 || S1 == MVT::i16))) {
18319     SDLoc DL(N);
18320     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(),
18321                                   S2.getHalfSizedIntegerVT(*DAG.getContext()),
18322                                   VT.getVectorElementCount());
18323     SDValue NewN0 = DAG.getNode(N->getOperand(0).getOpcode(), DL, HalfVT, N0);
18324     SDValue NewN1 = DAG.getNode(N->getOperand(1).getOpcode(), DL, HalfVT, N1);
18325     SDValue NewOp = DAG.getNode(N->getOpcode(), DL, HalfVT, NewN0, NewN1);
18326     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewOp);
18327   }
18328   return SDValue();
18329 }
18330 
18331 static SDValue performBuildVectorCombine(SDNode *N,
18332                                          TargetLowering::DAGCombinerInfo &DCI,
18333                                          SelectionDAG &DAG) {
18334   SDLoc DL(N);
18335   EVT VT = N->getValueType(0);
18336 
18337   // A build vector of two extracted elements is equivalent to an
18338   // extract subvector where the inner vector is any-extended to the
18339   // extract_vector_elt VT.
18340   //    (build_vector (extract_elt_iXX_to_i32 vec Idx+0)
18341   //                  (extract_elt_iXX_to_i32 vec Idx+1))
18342   // => (extract_subvector (anyext_iXX_to_i32 vec) Idx)
18343 
18344   // For now, only consider the v2i32 case, which arises as a result of
18345   // legalization.
18346   if (VT != MVT::v2i32)
18347     return SDValue();
18348 
18349   SDValue Elt0 = N->getOperand(0), Elt1 = N->getOperand(1);
18350   // Reminder, EXTRACT_VECTOR_ELT has the effect of any-extending to its VT.
18351   if (Elt0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
18352       Elt1->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
18353       // Constant index.
18354       isa<ConstantSDNode>(Elt0->getOperand(1)) &&
18355       isa<ConstantSDNode>(Elt1->getOperand(1)) &&
18356       // Both EXTRACT_VECTOR_ELT from same vector...
18357       Elt0->getOperand(0) == Elt1->getOperand(0) &&
18358       // ... and contiguous. First element's index +1 == second element's index.
18359       Elt0->getConstantOperandVal(1) + 1 == Elt1->getConstantOperandVal(1) &&
18360       // EXTRACT_SUBVECTOR requires that Idx be a constant multiple of
18361       // ResultType's known minimum vector length.
18362       Elt0->getConstantOperandVal(1) % VT.getVectorMinNumElements() == 0) {
18363     SDValue VecToExtend = Elt0->getOperand(0);
18364     EVT ExtVT = VecToExtend.getValueType().changeVectorElementType(MVT::i32);
18365     if (!DAG.getTargetLoweringInfo().isTypeLegal(ExtVT))
18366       return SDValue();
18367 
18368     SDValue SubvectorIdx = DAG.getVectorIdxConstant(Elt0->getConstantOperandVal(1), DL);
18369 
18370     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, VecToExtend);
18371     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Ext,
18372                        SubvectorIdx);
18373   }
18374 
18375   return SDValue();
18376 }
18377 
18378 static SDValue performTruncateCombine(SDNode *N,
18379                                       SelectionDAG &DAG) {
18380   EVT VT = N->getValueType(0);
18381   SDValue N0 = N->getOperand(0);
18382   if (VT.isFixedLengthVector() && VT.is64BitVector() && N0.hasOneUse() &&
18383       N0.getOpcode() == AArch64ISD::DUP) {
18384     SDValue Op = N0.getOperand(0);
18385     if (VT.getScalarType() == MVT::i32 &&
18386         N0.getOperand(0).getValueType().getScalarType() == MVT::i64)
18387       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i32, Op);
18388     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Op);
18389   }
18390 
18391   return SDValue();
18392 }
18393 
18394 // Check an node is an extend or shift operand
18395 static bool isExtendOrShiftOperand(SDValue N) {
18396   unsigned Opcode = N.getOpcode();
18397   if (ISD::isExtOpcode(Opcode) || Opcode == ISD::SIGN_EXTEND_INREG) {
18398     EVT SrcVT;
18399     if (Opcode == ISD::SIGN_EXTEND_INREG)
18400       SrcVT = cast<VTSDNode>(N.getOperand(1))->getVT();
18401     else
18402       SrcVT = N.getOperand(0).getValueType();
18403 
18404     return SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8;
18405   } else if (Opcode == ISD::AND) {
18406     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
18407     if (!CSD)
18408       return false;
18409     uint64_t AndMask = CSD->getZExtValue();
18410     return AndMask == 0xff || AndMask == 0xffff || AndMask == 0xffffffff;
18411   } else if (Opcode == ISD::SHL || Opcode == ISD::SRL || Opcode == ISD::SRA) {
18412     return isa<ConstantSDNode>(N.getOperand(1));
18413   }
18414 
18415   return false;
18416 }
18417 
18418 // (N - Y) + Z --> (Z - Y) + N
18419 // when N is an extend or shift operand
18420 static SDValue performAddCombineSubShift(SDNode *N, SDValue SUB, SDValue Z,
18421                                          SelectionDAG &DAG) {
18422   auto IsOneUseExtend = [](SDValue N) {
18423     return N.hasOneUse() && isExtendOrShiftOperand(N);
18424   };
18425 
18426   // DAGCombiner will revert the combination when Z is constant cause
18427   // dead loop. So don't enable the combination when Z is constant.
18428   // If Z is one use shift C, we also can't do the optimization.
18429   // It will falling to self infinite loop.
18430   if (isa<ConstantSDNode>(Z) || IsOneUseExtend(Z))
18431     return SDValue();
18432 
18433   if (SUB.getOpcode() != ISD::SUB || !SUB.hasOneUse())
18434     return SDValue();
18435 
18436   SDValue Shift = SUB.getOperand(0);
18437   if (!IsOneUseExtend(Shift))
18438     return SDValue();
18439 
18440   SDLoc DL(N);
18441   EVT VT = N->getValueType(0);
18442 
18443   SDValue Y = SUB.getOperand(1);
18444   SDValue NewSub = DAG.getNode(ISD::SUB, DL, VT, Z, Y);
18445   return DAG.getNode(ISD::ADD, DL, VT, NewSub, Shift);
18446 }
18447 
18448 static SDValue performAddCombineForShiftedOperands(SDNode *N,
18449                                                    SelectionDAG &DAG) {
18450   // NOTE: Swapping LHS and RHS is not done for SUB, since SUB is not
18451   // commutative.
18452   if (N->getOpcode() != ISD::ADD)
18453     return SDValue();
18454 
18455   // Bail out when value type is not one of {i32, i64}, since AArch64 ADD with
18456   // shifted register is only available for i32 and i64.
18457   EVT VT = N->getValueType(0);
18458   if (VT != MVT::i32 && VT != MVT::i64)
18459     return SDValue();
18460 
18461   SDLoc DL(N);
18462   SDValue LHS = N->getOperand(0);
18463   SDValue RHS = N->getOperand(1);
18464 
18465   if (SDValue Val = performAddCombineSubShift(N, LHS, RHS, DAG))
18466     return Val;
18467   if (SDValue Val = performAddCombineSubShift(N, RHS, LHS, DAG))
18468     return Val;
18469 
18470   uint64_t LHSImm = 0, RHSImm = 0;
18471   // If both operand are shifted by imm and shift amount is not greater than 4
18472   // for one operand, swap LHS and RHS to put operand with smaller shift amount
18473   // on RHS.
18474   //
18475   // On many AArch64 processors (Cortex A78, Neoverse N1/N2/V1, etc), ADD with
18476   // LSL shift (shift <= 4) has smaller latency and larger throughput than ADD
18477   // with LSL (shift > 4). For the rest of processors, this is no-op for
18478   // performance or correctness.
18479   if (isOpcWithIntImmediate(LHS.getNode(), ISD::SHL, LHSImm) &&
18480       isOpcWithIntImmediate(RHS.getNode(), ISD::SHL, RHSImm) && LHSImm <= 4 &&
18481       RHSImm > 4 && LHS.hasOneUse())
18482     return DAG.getNode(ISD::ADD, DL, VT, RHS, LHS);
18483 
18484   return SDValue();
18485 }
18486 
18487 // The mid end will reassociate sub(sub(x, m1), m2) to sub(x, add(m1, m2))
18488 // This reassociates it back to allow the creation of more mls instructions.
18489 static SDValue performSubAddMULCombine(SDNode *N, SelectionDAG &DAG) {
18490   if (N->getOpcode() != ISD::SUB)
18491     return SDValue();
18492 
18493   SDValue Add = N->getOperand(1);
18494   SDValue X = N->getOperand(0);
18495   if (Add.getOpcode() != ISD::ADD)
18496     return SDValue();
18497 
18498   if (!Add.hasOneUse())
18499     return SDValue();
18500   if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(X)))
18501     return SDValue();
18502 
18503   SDValue M1 = Add.getOperand(0);
18504   SDValue M2 = Add.getOperand(1);
18505   if (M1.getOpcode() != ISD::MUL && M1.getOpcode() != AArch64ISD::SMULL &&
18506       M1.getOpcode() != AArch64ISD::UMULL)
18507     return SDValue();
18508   if (M2.getOpcode() != ISD::MUL && M2.getOpcode() != AArch64ISD::SMULL &&
18509       M2.getOpcode() != AArch64ISD::UMULL)
18510     return SDValue();
18511 
18512   EVT VT = N->getValueType(0);
18513   SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, X, M1);
18514   return DAG.getNode(ISD::SUB, SDLoc(N), VT, Sub, M2);
18515 }
18516 
18517 // Combine into mla/mls.
18518 // This works on the patterns of:
18519 //   add v1, (mul v2, v3)
18520 //   sub v1, (mul v2, v3)
18521 // for vectors of type <1 x i64> and <2 x i64> when SVE is available.
18522 // It will transform the add/sub to a scalable version, so that we can
18523 // make use of SVE's MLA/MLS that will be generated for that pattern
18524 static SDValue
18525 performSVEMulAddSubCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
18526   SelectionDAG &DAG = DCI.DAG;
18527   // Make sure that the types are legal
18528   if (!DCI.isAfterLegalizeDAG())
18529     return SDValue();
18530   // Before using SVE's features, check first if it's available.
18531   if (!DAG.getSubtarget<AArch64Subtarget>().hasSVE())
18532     return SDValue();
18533 
18534   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::SUB)
18535     return SDValue();
18536 
18537   if (!N->getValueType(0).isFixedLengthVector())
18538     return SDValue();
18539 
18540   auto performOpt = [&DAG, &N](SDValue Op0, SDValue Op1) -> SDValue {
18541     if (Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR)
18542       return SDValue();
18543 
18544     if (!cast<ConstantSDNode>(Op1->getOperand(1))->isZero())
18545       return SDValue();
18546 
18547     SDValue MulValue = Op1->getOperand(0);
18548     if (MulValue.getOpcode() != AArch64ISD::MUL_PRED)
18549       return SDValue();
18550 
18551     if (!Op1.hasOneUse() || !MulValue.hasOneUse())
18552       return SDValue();
18553 
18554     EVT ScalableVT = MulValue.getValueType();
18555     if (!ScalableVT.isScalableVector())
18556       return SDValue();
18557 
18558     SDValue ScaledOp = convertToScalableVector(DAG, ScalableVT, Op0);
18559     SDValue NewValue =
18560         DAG.getNode(N->getOpcode(), SDLoc(N), ScalableVT, {ScaledOp, MulValue});
18561     return convertFromScalableVector(DAG, N->getValueType(0), NewValue);
18562   };
18563 
18564   if (SDValue res = performOpt(N->getOperand(0), N->getOperand(1)))
18565     return res;
18566   else if (N->getOpcode() == ISD::ADD)
18567     return performOpt(N->getOperand(1), N->getOperand(0));
18568 
18569   return SDValue();
18570 }
18571 
18572 // Given a i64 add from a v1i64 extract, convert to a neon v1i64 add. This can
18573 // help, for example, to produce ssra from sshr+add.
18574 static SDValue performAddSubIntoVectorOp(SDNode *N, SelectionDAG &DAG) {
18575   EVT VT = N->getValueType(0);
18576   if (VT != MVT::i64)
18577     return SDValue();
18578   SDValue Op0 = N->getOperand(0);
18579   SDValue Op1 = N->getOperand(1);
18580 
18581   // At least one of the operands should be an extract, and the other should be
18582   // something that is easy to convert to v1i64 type (in this case a load).
18583   if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
18584       Op0.getOpcode() != ISD::LOAD)
18585     return SDValue();
18586   if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
18587       Op1.getOpcode() != ISD::LOAD)
18588     return SDValue();
18589 
18590   SDLoc DL(N);
18591   if (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
18592       Op0.getOperand(0).getValueType() == MVT::v1i64) {
18593     Op0 = Op0.getOperand(0);
18594     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i64, Op1);
18595   } else if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
18596              Op1.getOperand(0).getValueType() == MVT::v1i64) {
18597     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i64, Op0);
18598     Op1 = Op1.getOperand(0);
18599   } else
18600     return SDValue();
18601 
18602   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64,
18603                      DAG.getNode(N->getOpcode(), DL, MVT::v1i64, Op0, Op1),
18604                      DAG.getConstant(0, DL, MVT::i64));
18605 }
18606 
18607 static bool isLoadOrMultipleLoads(SDValue B, SmallVector<LoadSDNode *> &Loads) {
18608   SDValue BV = peekThroughOneUseBitcasts(B);
18609   if (!BV->hasOneUse())
18610     return false;
18611   if (auto *Ld = dyn_cast<LoadSDNode>(BV)) {
18612     if (!Ld || !Ld->isSimple())
18613       return false;
18614     Loads.push_back(Ld);
18615     return true;
18616   } else if (BV.getOpcode() == ISD::BUILD_VECTOR ||
18617              BV.getOpcode() == ISD::CONCAT_VECTORS) {
18618     for (unsigned Op = 0; Op < BV.getNumOperands(); Op++) {
18619       auto *Ld = dyn_cast<LoadSDNode>(BV.getOperand(Op));
18620       if (!Ld || !Ld->isSimple() || !BV.getOperand(Op).hasOneUse())
18621         return false;
18622       Loads.push_back(Ld);
18623     }
18624     return true;
18625   } else if (B.getOpcode() == ISD::VECTOR_SHUFFLE) {
18626     // Try to find a tree of shuffles and concats from how IR shuffles of loads
18627     // are lowered. Note that this only comes up because we do not always visit
18628     // operands before uses. After that is fixed this can be removed and in the
18629     // meantime this is fairly specific to the lowering we expect from IR.
18630     // t46: v16i8 = vector_shuffle<0,1,2,3,4,5,6,7,8,9,10,11,16,17,18,19> t44, t45
18631     //   t44: v16i8 = vector_shuffle<0,1,2,3,4,5,6,7,16,17,18,19,u,u,u,u> t42, t43
18632     //     t42: v16i8 = concat_vectors t40, t36, undef:v4i8, undef:v4i8
18633     //       t40: v4i8,ch = load<(load (s32) from %ir.17)> t0, t22, undef:i64
18634     //       t36: v4i8,ch = load<(load (s32) from %ir.13)> t0, t18, undef:i64
18635     //     t43: v16i8 = concat_vectors t32, undef:v4i8, undef:v4i8, undef:v4i8
18636     //       t32: v4i8,ch = load<(load (s32) from %ir.9)> t0, t14, undef:i64
18637     //   t45: v16i8 = concat_vectors t28, undef:v4i8, undef:v4i8, undef:v4i8
18638     //     t28: v4i8,ch = load<(load (s32) from %ir.0)> t0, t2, undef:i64
18639     if (B.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE ||
18640         B.getOperand(0).getOperand(0).getOpcode() != ISD::CONCAT_VECTORS ||
18641         B.getOperand(0).getOperand(1).getOpcode() != ISD::CONCAT_VECTORS ||
18642         B.getOperand(1).getOpcode() != ISD::CONCAT_VECTORS ||
18643         B.getOperand(1).getNumOperands() != 4)
18644       return false;
18645     auto SV1 = cast<ShuffleVectorSDNode>(B);
18646     auto SV2 = cast<ShuffleVectorSDNode>(B.getOperand(0));
18647     int NumElts = B.getValueType().getVectorNumElements();
18648     int NumSubElts = NumElts / 4;
18649     for (int I = 0; I < NumSubElts; I++) {
18650       // <0,1,2,3,4,5,6,7,8,9,10,11,16,17,18,19>
18651       if (SV1->getMaskElt(I) != I ||
18652           SV1->getMaskElt(I + NumSubElts) != I + NumSubElts ||
18653           SV1->getMaskElt(I + NumSubElts * 2) != I + NumSubElts * 2 ||
18654           SV1->getMaskElt(I + NumSubElts * 3) != I + NumElts)
18655         return false;
18656       // <0,1,2,3,4,5,6,7,16,17,18,19,u,u,u,u>
18657       if (SV2->getMaskElt(I) != I ||
18658           SV2->getMaskElt(I + NumSubElts) != I + NumSubElts ||
18659           SV2->getMaskElt(I + NumSubElts * 2) != I + NumElts)
18660         return false;
18661     }
18662     auto *Ld0 = dyn_cast<LoadSDNode>(SV2->getOperand(0).getOperand(0));
18663     auto *Ld1 = dyn_cast<LoadSDNode>(SV2->getOperand(0).getOperand(1));
18664     auto *Ld2 = dyn_cast<LoadSDNode>(SV2->getOperand(1).getOperand(0));
18665     auto *Ld3 = dyn_cast<LoadSDNode>(B.getOperand(1).getOperand(0));
18666     if (!Ld0 || !Ld1 || !Ld2 || !Ld3 || !Ld0->isSimple() || !Ld1->isSimple() ||
18667         !Ld2->isSimple() || !Ld3->isSimple())
18668       return false;
18669     Loads.push_back(Ld0);
18670     Loads.push_back(Ld1);
18671     Loads.push_back(Ld2);
18672     Loads.push_back(Ld3);
18673     return true;
18674   }
18675   return false;
18676 }
18677 
18678 static bool areLoadedOffsetButOtherwiseSame(SDValue Op0, SDValue Op1,
18679                                             SelectionDAG &DAG,
18680                                             unsigned &NumSubLoads) {
18681   if (!Op0.hasOneUse() || !Op1.hasOneUse())
18682     return false;
18683 
18684   SmallVector<LoadSDNode *> Loads0, Loads1;
18685   if (isLoadOrMultipleLoads(Op0, Loads0) &&
18686       isLoadOrMultipleLoads(Op1, Loads1)) {
18687     if (NumSubLoads && Loads0.size() != NumSubLoads)
18688       return false;
18689     NumSubLoads = Loads0.size();
18690     return Loads0.size() == Loads1.size() &&
18691            all_of(zip(Loads0, Loads1), [&DAG](auto L) {
18692              unsigned Size = get<0>(L)->getValueType(0).getSizeInBits();
18693              return Size == get<1>(L)->getValueType(0).getSizeInBits() &&
18694                     DAG.areNonVolatileConsecutiveLoads(get<1>(L), get<0>(L),
18695                                                        Size / 8, 1);
18696            });
18697   }
18698 
18699   if (Op0.getOpcode() != Op1.getOpcode())
18700     return false;
18701 
18702   switch (Op0.getOpcode()) {
18703   case ISD::ADD:
18704   case ISD::SUB:
18705     return areLoadedOffsetButOtherwiseSame(Op0.getOperand(0), Op1.getOperand(0),
18706                                            DAG, NumSubLoads) &&
18707            areLoadedOffsetButOtherwiseSame(Op0.getOperand(1), Op1.getOperand(1),
18708                                            DAG, NumSubLoads);
18709   case ISD::SIGN_EXTEND:
18710   case ISD::ANY_EXTEND:
18711   case ISD::ZERO_EXTEND:
18712     EVT XVT = Op0.getOperand(0).getValueType();
18713     if (XVT.getScalarSizeInBits() != 8 && XVT.getScalarSizeInBits() != 16 &&
18714         XVT.getScalarSizeInBits() != 32)
18715       return false;
18716     return areLoadedOffsetButOtherwiseSame(Op0.getOperand(0), Op1.getOperand(0),
18717                                            DAG, NumSubLoads);
18718   }
18719   return false;
18720 }
18721 
18722 // This method attempts to fold trees of add(ext(load p), shl(ext(load p+4))
18723 // into a single load of twice the size, that we extract the bottom part and top
18724 // part so that the shl can use a shll2 instruction. The two loads in that
18725 // example can also be larger trees of instructions, which are identical except
18726 // for the leaves which are all loads offset from the LHS, including
18727 // buildvectors of multiple loads. For example the RHS tree could be
18728 // sub(zext(buildvec(load p+4, load q+4)), zext(buildvec(load r+4, load s+4)))
18729 // Whilst it can be common for the larger loads to replace LDP instructions
18730 // (which doesn't gain anything on it's own), the larger loads can help create
18731 // more efficient code, and in buildvectors prevent the need for ld1 lane
18732 // inserts which can be slower than normal loads.
18733 static SDValue performExtBinopLoadFold(SDNode *N, SelectionDAG &DAG) {
18734   EVT VT = N->getValueType(0);
18735   if (!VT.isFixedLengthVector() ||
18736       (VT.getScalarSizeInBits() != 16 && VT.getScalarSizeInBits() != 32 &&
18737        VT.getScalarSizeInBits() != 64))
18738     return SDValue();
18739 
18740   SDValue Other = N->getOperand(0);
18741   SDValue Shift = N->getOperand(1);
18742   if (Shift.getOpcode() != ISD::SHL && N->getOpcode() != ISD::SUB)
18743     std::swap(Shift, Other);
18744   APInt ShiftAmt;
18745   if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse() ||
18746       !ISD::isConstantSplatVector(Shift.getOperand(1).getNode(), ShiftAmt))
18747     return SDValue();
18748 
18749   if (!ISD::isExtOpcode(Shift.getOperand(0).getOpcode()) ||
18750       !ISD::isExtOpcode(Other.getOpcode()) ||
18751       Shift.getOperand(0).getOperand(0).getValueType() !=
18752           Other.getOperand(0).getValueType() ||
18753       !Other.hasOneUse() || !Shift.getOperand(0).hasOneUse())
18754     return SDValue();
18755 
18756   SDValue Op0 = Other.getOperand(0);
18757   SDValue Op1 = Shift.getOperand(0).getOperand(0);
18758 
18759   unsigned NumSubLoads = 0;
18760   if (!areLoadedOffsetButOtherwiseSame(Op0, Op1, DAG, NumSubLoads))
18761     return SDValue();
18762 
18763   // Attempt to rule out some unprofitable cases using heuristics (some working
18764   // around suboptimal code generation), notably if the extend not be able to
18765   // use ushll2 instructions as the types are not large enough. Otherwise zip's
18766   // will need to be created which can increase the instruction count.
18767   unsigned NumElts = Op0.getValueType().getVectorNumElements();
18768   unsigned NumSubElts = NumElts / NumSubLoads;
18769   if (NumSubElts * VT.getScalarSizeInBits() < 128 ||
18770       (Other.getOpcode() != Shift.getOperand(0).getOpcode() &&
18771        Op0.getValueType().getSizeInBits() < 128 &&
18772        !DAG.getTargetLoweringInfo().isTypeLegal(Op0.getValueType())))
18773     return SDValue();
18774 
18775   // Recreate the tree with the new combined loads.
18776   std::function<SDValue(SDValue, SDValue, SelectionDAG &)> GenCombinedTree =
18777       [&GenCombinedTree](SDValue Op0, SDValue Op1, SelectionDAG &DAG) {
18778         EVT DVT =
18779             Op0.getValueType().getDoubleNumVectorElementsVT(*DAG.getContext());
18780 
18781         SmallVector<LoadSDNode *> Loads0, Loads1;
18782         if (isLoadOrMultipleLoads(Op0, Loads0) &&
18783             isLoadOrMultipleLoads(Op1, Loads1)) {
18784           EVT LoadVT = EVT::getVectorVT(
18785               *DAG.getContext(), Op0.getValueType().getScalarType(),
18786               Op0.getValueType().getVectorNumElements() / Loads0.size());
18787           EVT DLoadVT = LoadVT.getDoubleNumVectorElementsVT(*DAG.getContext());
18788 
18789           SmallVector<SDValue> NewLoads;
18790           for (const auto &[L0, L1] : zip(Loads0, Loads1)) {
18791             SDValue Load = DAG.getLoad(DLoadVT, SDLoc(L0), L0->getChain(),
18792                                        L0->getBasePtr(), L0->getPointerInfo(),
18793                                        L0->getOriginalAlign());
18794             DAG.makeEquivalentMemoryOrdering(L0, Load.getValue(1));
18795             DAG.makeEquivalentMemoryOrdering(L1, Load.getValue(1));
18796             NewLoads.push_back(Load);
18797           }
18798           return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op0), DVT, NewLoads);
18799         }
18800 
18801         SmallVector<SDValue> Ops;
18802         for (const auto &[O0, O1] : zip(Op0->op_values(), Op1->op_values()))
18803           Ops.push_back(GenCombinedTree(O0, O1, DAG));
18804         return DAG.getNode(Op0.getOpcode(), SDLoc(Op0), DVT, Ops);
18805       };
18806   SDValue NewOp = GenCombinedTree(Op0, Op1, DAG);
18807 
18808   SmallVector<int> LowMask(NumElts, 0), HighMask(NumElts, 0);
18809   int Hi = NumSubElts, Lo = 0;
18810   for (unsigned i = 0; i < NumSubLoads; i++) {
18811     for (unsigned j = 0; j < NumSubElts; j++) {
18812       LowMask[i * NumSubElts + j] = Lo++;
18813       HighMask[i * NumSubElts + j] = Hi++;
18814     }
18815     Lo += NumSubElts;
18816     Hi += NumSubElts;
18817   }
18818   SDLoc DL(N);
18819   SDValue Ext0, Ext1;
18820   // Extract the top and bottom lanes, then extend the result. Possibly extend
18821   // the result then extract the lanes if the two operands match as it produces
18822   // slightly smaller code.
18823   if (Other.getOpcode() != Shift.getOperand(0).getOpcode()) {
18824     SDValue SubL = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, Op0.getValueType(),
18825                                NewOp, DAG.getConstant(0, DL, MVT::i64));
18826     SDValue SubH =
18827         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, Op0.getValueType(), NewOp,
18828                     DAG.getConstant(NumSubElts * NumSubLoads, DL, MVT::i64));
18829     SDValue Extr0 =
18830         DAG.getVectorShuffle(Op0.getValueType(), DL, SubL, SubH, LowMask);
18831     SDValue Extr1 =
18832         DAG.getVectorShuffle(Op0.getValueType(), DL, SubL, SubH, HighMask);
18833     Ext0 = DAG.getNode(Other.getOpcode(), DL, VT, Extr0);
18834     Ext1 = DAG.getNode(Shift.getOperand(0).getOpcode(), DL, VT, Extr1);
18835   } else {
18836     EVT DVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
18837     SDValue Ext = DAG.getNode(Other.getOpcode(), DL, DVT, NewOp);
18838     SDValue SubL = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Ext,
18839                                DAG.getConstant(0, DL, MVT::i64));
18840     SDValue SubH =
18841         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Ext,
18842                     DAG.getConstant(NumSubElts * NumSubLoads, DL, MVT::i64));
18843     Ext0 = DAG.getVectorShuffle(VT, DL, SubL, SubH, LowMask);
18844     Ext1 = DAG.getVectorShuffle(VT, DL, SubL, SubH, HighMask);
18845   }
18846   SDValue NShift =
18847       DAG.getNode(Shift.getOpcode(), DL, VT, Ext1, Shift.getOperand(1));
18848   return DAG.getNode(N->getOpcode(), DL, VT, Ext0, NShift);
18849 }
18850 
18851 static SDValue performAddSubCombine(SDNode *N,
18852                                     TargetLowering::DAGCombinerInfo &DCI) {
18853   // Try to change sum of two reductions.
18854   if (SDValue Val = performAddUADDVCombine(N, DCI.DAG))
18855     return Val;
18856   if (SDValue Val = performAddDotCombine(N, DCI.DAG))
18857     return Val;
18858   if (SDValue Val = performAddCSelIntoCSinc(N, DCI.DAG))
18859     return Val;
18860   if (SDValue Val = performNegCSelCombine(N, DCI.DAG))
18861     return Val;
18862   if (SDValue Val = performVectorAddSubExtCombine(N, DCI.DAG))
18863     return Val;
18864   if (SDValue Val = performAddCombineForShiftedOperands(N, DCI.DAG))
18865     return Val;
18866   if (SDValue Val = performSubAddMULCombine(N, DCI.DAG))
18867     return Val;
18868   if (SDValue Val = performSVEMulAddSubCombine(N, DCI))
18869     return Val;
18870   if (SDValue Val = performAddSubIntoVectorOp(N, DCI.DAG))
18871     return Val;
18872 
18873   if (SDValue Val = performExtBinopLoadFold(N, DCI.DAG))
18874     return Val;
18875 
18876   return performAddSubLongCombine(N, DCI);
18877 }
18878 
18879 // Massage DAGs which we can use the high-half "long" operations on into
18880 // something isel will recognize better. E.g.
18881 //
18882 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
18883 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
18884 //                     (extract_high (v2i64 (dup128 scalar)))))
18885 //
18886 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
18887                                        TargetLowering::DAGCombinerInfo &DCI,
18888                                        SelectionDAG &DAG) {
18889   if (DCI.isBeforeLegalizeOps())
18890     return SDValue();
18891 
18892   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
18893   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
18894   assert(LHS.getValueType().is64BitVector() &&
18895          RHS.getValueType().is64BitVector() &&
18896          "unexpected shape for long operation");
18897 
18898   // Either node could be a DUP, but it's not worth doing both of them (you'd
18899   // just as well use the non-high version) so look for a corresponding extract
18900   // operation on the other "wing".
18901   if (isEssentiallyExtractHighSubvector(LHS)) {
18902     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
18903     if (!RHS.getNode())
18904       return SDValue();
18905   } else if (isEssentiallyExtractHighSubvector(RHS)) {
18906     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
18907     if (!LHS.getNode())
18908       return SDValue();
18909   } else
18910     return SDValue();
18911 
18912   if (IID == Intrinsic::not_intrinsic)
18913     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
18914 
18915   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
18916                      N->getOperand(0), LHS, RHS);
18917 }
18918 
18919 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
18920   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
18921   unsigned ElemBits = ElemTy.getSizeInBits();
18922 
18923   int64_t ShiftAmount;
18924   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
18925     APInt SplatValue, SplatUndef;
18926     unsigned SplatBitSize;
18927     bool HasAnyUndefs;
18928     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
18929                               HasAnyUndefs, ElemBits) ||
18930         SplatBitSize != ElemBits)
18931       return SDValue();
18932 
18933     ShiftAmount = SplatValue.getSExtValue();
18934   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
18935     ShiftAmount = CVN->getSExtValue();
18936   } else
18937     return SDValue();
18938 
18939   // If the shift amount is zero, remove the shift intrinsic.
18940   if (ShiftAmount == 0 && IID != Intrinsic::aarch64_neon_sqshlu)
18941     return N->getOperand(1);
18942 
18943   unsigned Opcode;
18944   bool IsRightShift;
18945   switch (IID) {
18946   default:
18947     llvm_unreachable("Unknown shift intrinsic");
18948   case Intrinsic::aarch64_neon_sqshl:
18949     Opcode = AArch64ISD::SQSHL_I;
18950     IsRightShift = false;
18951     break;
18952   case Intrinsic::aarch64_neon_uqshl:
18953     Opcode = AArch64ISD::UQSHL_I;
18954     IsRightShift = false;
18955     break;
18956   case Intrinsic::aarch64_neon_srshl:
18957     Opcode = AArch64ISD::SRSHR_I;
18958     IsRightShift = true;
18959     break;
18960   case Intrinsic::aarch64_neon_urshl:
18961     Opcode = AArch64ISD::URSHR_I;
18962     IsRightShift = true;
18963     break;
18964   case Intrinsic::aarch64_neon_sqshlu:
18965     Opcode = AArch64ISD::SQSHLU_I;
18966     IsRightShift = false;
18967     break;
18968   case Intrinsic::aarch64_neon_sshl:
18969   case Intrinsic::aarch64_neon_ushl:
18970     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
18971     // left shift for positive shift amounts. Below, we only replace the current
18972     // node with VSHL, if this condition is met.
18973     Opcode = AArch64ISD::VSHL;
18974     IsRightShift = false;
18975     break;
18976   }
18977 
18978   EVT VT = N->getValueType(0);
18979   SDValue Op = N->getOperand(1);
18980   SDLoc dl(N);
18981   if (VT == MVT::i64) {
18982     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op);
18983     VT = MVT::v1i64;
18984   }
18985 
18986   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
18987     Op = DAG.getNode(Opcode, dl, VT, Op,
18988                      DAG.getConstant(-ShiftAmount, dl, MVT::i32));
18989     if (N->getValueType(0) == MVT::i64)
18990       Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
18991                        DAG.getConstant(0, dl, MVT::i64));
18992     return Op;
18993   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
18994     Op = DAG.getNode(Opcode, dl, VT, Op,
18995                      DAG.getConstant(ShiftAmount, dl, MVT::i32));
18996     if (N->getValueType(0) == MVT::i64)
18997       Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
18998                        DAG.getConstant(0, dl, MVT::i64));
18999     return Op;
19000   }
19001 
19002   return SDValue();
19003 }
19004 
19005 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
19006 // the intrinsics must be legal and take an i32, this means there's almost
19007 // certainly going to be a zext in the DAG which we can eliminate.
19008 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
19009   SDValue AndN = N->getOperand(2);
19010   if (AndN.getOpcode() != ISD::AND)
19011     return SDValue();
19012 
19013   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
19014   if (!CMask || CMask->getZExtValue() != Mask)
19015     return SDValue();
19016 
19017   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
19018                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
19019 }
19020 
19021 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
19022                                            SelectionDAG &DAG) {
19023   SDLoc dl(N);
19024   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
19025                      DAG.getNode(Opc, dl,
19026                                  N->getOperand(1).getSimpleValueType(),
19027                                  N->getOperand(1)),
19028                      DAG.getConstant(0, dl, MVT::i64));
19029 }
19030 
19031 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
19032   SDLoc DL(N);
19033   SDValue Op1 = N->getOperand(1);
19034   SDValue Op2 = N->getOperand(2);
19035   EVT ScalarTy = Op2.getValueType();
19036   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
19037     ScalarTy = MVT::i32;
19038 
19039   // Lower index_vector(base, step) to mul(step step_vector(1)) + splat(base).
19040   SDValue StepVector = DAG.getStepVector(DL, N->getValueType(0));
19041   SDValue Step = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op2);
19042   SDValue Mul = DAG.getNode(ISD::MUL, DL, N->getValueType(0), StepVector, Step);
19043   SDValue Base = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op1);
19044   return DAG.getNode(ISD::ADD, DL, N->getValueType(0), Mul, Base);
19045 }
19046 
19047 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
19048   SDLoc dl(N);
19049   SDValue Scalar = N->getOperand(3);
19050   EVT ScalarTy = Scalar.getValueType();
19051 
19052   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
19053     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
19054 
19055   SDValue Passthru = N->getOperand(1);
19056   SDValue Pred = N->getOperand(2);
19057   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
19058                      Pred, Scalar, Passthru);
19059 }
19060 
19061 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
19062   SDLoc dl(N);
19063   LLVMContext &Ctx = *DAG.getContext();
19064   EVT VT = N->getValueType(0);
19065 
19066   assert(VT.isScalableVector() && "Expected a scalable vector.");
19067 
19068   // Current lowering only supports the SVE-ACLE types.
19069   if (VT.getSizeInBits().getKnownMinValue() != AArch64::SVEBitsPerBlock)
19070     return SDValue();
19071 
19072   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
19073   unsigned ByteSize = VT.getSizeInBits().getKnownMinValue() / 8;
19074   EVT ByteVT =
19075       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
19076 
19077   // Convert everything to the domain of EXT (i.e bytes).
19078   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
19079   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
19080   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
19081                             DAG.getConstant(ElemSize, dl, MVT::i32));
19082 
19083   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
19084   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
19085 }
19086 
19087 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
19088                                         TargetLowering::DAGCombinerInfo &DCI,
19089                                         SelectionDAG &DAG) {
19090   if (DCI.isBeforeLegalize())
19091     return SDValue();
19092 
19093   SDValue Comparator = N->getOperand(3);
19094   if (Comparator.getOpcode() == AArch64ISD::DUP ||
19095       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
19096     unsigned IID = getIntrinsicID(N);
19097     EVT VT = N->getValueType(0);
19098     EVT CmpVT = N->getOperand(2).getValueType();
19099     SDValue Pred = N->getOperand(1);
19100     SDValue Imm;
19101     SDLoc DL(N);
19102 
19103     switch (IID) {
19104     default:
19105       llvm_unreachable("Called with wrong intrinsic!");
19106       break;
19107 
19108     // Signed comparisons
19109     case Intrinsic::aarch64_sve_cmpeq_wide:
19110     case Intrinsic::aarch64_sve_cmpne_wide:
19111     case Intrinsic::aarch64_sve_cmpge_wide:
19112     case Intrinsic::aarch64_sve_cmpgt_wide:
19113     case Intrinsic::aarch64_sve_cmplt_wide:
19114     case Intrinsic::aarch64_sve_cmple_wide: {
19115       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
19116         int64_t ImmVal = CN->getSExtValue();
19117         if (ImmVal >= -16 && ImmVal <= 15)
19118           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
19119         else
19120           return SDValue();
19121       }
19122       break;
19123     }
19124     // Unsigned comparisons
19125     case Intrinsic::aarch64_sve_cmphs_wide:
19126     case Intrinsic::aarch64_sve_cmphi_wide:
19127     case Intrinsic::aarch64_sve_cmplo_wide:
19128     case Intrinsic::aarch64_sve_cmpls_wide:  {
19129       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
19130         uint64_t ImmVal = CN->getZExtValue();
19131         if (ImmVal <= 127)
19132           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
19133         else
19134           return SDValue();
19135       }
19136       break;
19137     }
19138     }
19139 
19140     if (!Imm)
19141       return SDValue();
19142 
19143     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
19144     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
19145                        N->getOperand(2), Splat, DAG.getCondCode(CC));
19146   }
19147 
19148   return SDValue();
19149 }
19150 
19151 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
19152                         AArch64CC::CondCode Cond) {
19153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19154 
19155   SDLoc DL(Op);
19156   assert(Op.getValueType().isScalableVector() &&
19157          TLI.isTypeLegal(Op.getValueType()) &&
19158          "Expected legal scalable vector type!");
19159   assert(Op.getValueType() == Pg.getValueType() &&
19160          "Expected same type for PTEST operands");
19161 
19162   // Ensure target specific opcodes are using legal type.
19163   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
19164   SDValue TVal = DAG.getConstant(1, DL, OutVT);
19165   SDValue FVal = DAG.getConstant(0, DL, OutVT);
19166 
19167   // Ensure operands have type nxv16i1.
19168   if (Op.getValueType() != MVT::nxv16i1) {
19169     if ((Cond == AArch64CC::ANY_ACTIVE || Cond == AArch64CC::NONE_ACTIVE) &&
19170         isZeroingInactiveLanes(Op))
19171       Pg = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, MVT::nxv16i1, Pg);
19172     else
19173       Pg = getSVEPredicateBitCast(MVT::nxv16i1, Pg, DAG);
19174     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, MVT::nxv16i1, Op);
19175   }
19176 
19177   // Set condition code (CC) flags.
19178   SDValue Test = DAG.getNode(
19179       Cond == AArch64CC::ANY_ACTIVE ? AArch64ISD::PTEST_ANY : AArch64ISD::PTEST,
19180       DL, MVT::Other, Pg, Op);
19181 
19182   // Convert CC to integer based on requested condition.
19183   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
19184   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
19185   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
19186   return DAG.getZExtOrTrunc(Res, DL, VT);
19187 }
19188 
19189 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
19190                                       SelectionDAG &DAG) {
19191   SDLoc DL(N);
19192 
19193   SDValue Pred = N->getOperand(1);
19194   SDValue VecToReduce = N->getOperand(2);
19195 
19196   // NOTE: The integer reduction's result type is not always linked to the
19197   // operand's element type so we construct it from the intrinsic's result type.
19198   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
19199   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
19200 
19201   // SVE reductions set the whole vector register with the first element
19202   // containing the reduction result, which we'll now extract.
19203   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
19204   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
19205                      Zero);
19206 }
19207 
19208 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
19209                                      SelectionDAG &DAG) {
19210   SDLoc DL(N);
19211 
19212   SDValue Pred = N->getOperand(1);
19213   SDValue VecToReduce = N->getOperand(2);
19214 
19215   EVT ReduceVT = VecToReduce.getValueType();
19216   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
19217 
19218   // SVE reductions set the whole vector register with the first element
19219   // containing the reduction result, which we'll now extract.
19220   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
19221   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
19222                      Zero);
19223 }
19224 
19225 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
19226                                             SelectionDAG &DAG) {
19227   SDLoc DL(N);
19228 
19229   SDValue Pred = N->getOperand(1);
19230   SDValue InitVal = N->getOperand(2);
19231   SDValue VecToReduce = N->getOperand(3);
19232   EVT ReduceVT = VecToReduce.getValueType();
19233 
19234   // Ordered reductions use the first lane of the result vector as the
19235   // reduction's initial value.
19236   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
19237   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
19238                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
19239 
19240   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
19241 
19242   // SVE reductions set the whole vector register with the first element
19243   // containing the reduction result, which we'll now extract.
19244   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
19245                      Zero);
19246 }
19247 
19248 // If a merged operation has no inactive lanes we can relax it to a predicated
19249 // or unpredicated operation, which potentially allows better isel (perhaps
19250 // using immediate forms) or relaxing register reuse requirements.
19251 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned Opc,
19252                                        SelectionDAG &DAG, bool UnpredOp = false,
19253                                        bool SwapOperands = false) {
19254   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
19255   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
19256   SDValue Pg = N->getOperand(1);
19257   SDValue Op1 = N->getOperand(SwapOperands ? 3 : 2);
19258   SDValue Op2 = N->getOperand(SwapOperands ? 2 : 3);
19259 
19260   // ISD way to specify an all active predicate.
19261   if (isAllActivePredicate(DAG, Pg)) {
19262     if (UnpredOp)
19263       return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Op1, Op2);
19264 
19265     return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Pg, Op1, Op2);
19266   }
19267 
19268   // FUTURE: SplatVector(true)
19269   return SDValue();
19270 }
19271 
19272 static SDValue performIntrinsicCombine(SDNode *N,
19273                                        TargetLowering::DAGCombinerInfo &DCI,
19274                                        const AArch64Subtarget *Subtarget) {
19275   SelectionDAG &DAG = DCI.DAG;
19276   unsigned IID = getIntrinsicID(N);
19277   switch (IID) {
19278   default:
19279     break;
19280   case Intrinsic::get_active_lane_mask: {
19281     SDValue Res = SDValue();
19282     EVT VT = N->getValueType(0);
19283     if (VT.isFixedLengthVector()) {
19284       // We can use the SVE whilelo instruction to lower this intrinsic by
19285       // creating the appropriate sequence of scalable vector operations and
19286       // then extracting a fixed-width subvector from the scalable vector.
19287 
19288       SDLoc DL(N);
19289       SDValue ID =
19290           DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, DL, MVT::i64);
19291 
19292       EVT WhileVT = EVT::getVectorVT(
19293           *DAG.getContext(), MVT::i1,
19294           ElementCount::getScalable(VT.getVectorNumElements()));
19295 
19296       // Get promoted scalable vector VT, i.e. promote nxv4i1 -> nxv4i32.
19297       EVT PromVT = getPromotedVTForPredicate(WhileVT);
19298 
19299       // Get the fixed-width equivalent of PromVT for extraction.
19300       EVT ExtVT =
19301           EVT::getVectorVT(*DAG.getContext(), PromVT.getVectorElementType(),
19302                            VT.getVectorElementCount());
19303 
19304       Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WhileVT, ID,
19305                         N->getOperand(1), N->getOperand(2));
19306       Res = DAG.getNode(ISD::SIGN_EXTEND, DL, PromVT, Res);
19307       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtVT, Res,
19308                         DAG.getConstant(0, DL, MVT::i64));
19309       Res = DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
19310     }
19311     return Res;
19312   }
19313   case Intrinsic::aarch64_neon_vcvtfxs2fp:
19314   case Intrinsic::aarch64_neon_vcvtfxu2fp:
19315     return tryCombineFixedPointConvert(N, DCI, DAG);
19316   case Intrinsic::aarch64_neon_saddv:
19317     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
19318   case Intrinsic::aarch64_neon_uaddv:
19319     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
19320   case Intrinsic::aarch64_neon_sminv:
19321     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
19322   case Intrinsic::aarch64_neon_uminv:
19323     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
19324   case Intrinsic::aarch64_neon_smaxv:
19325     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
19326   case Intrinsic::aarch64_neon_umaxv:
19327     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
19328   case Intrinsic::aarch64_neon_fmax:
19329     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
19330                        N->getOperand(1), N->getOperand(2));
19331   case Intrinsic::aarch64_neon_fmin:
19332     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
19333                        N->getOperand(1), N->getOperand(2));
19334   case Intrinsic::aarch64_neon_fmaxnm:
19335     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
19336                        N->getOperand(1), N->getOperand(2));
19337   case Intrinsic::aarch64_neon_fminnm:
19338     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
19339                        N->getOperand(1), N->getOperand(2));
19340   case Intrinsic::aarch64_neon_smull:
19341     return DAG.getNode(AArch64ISD::SMULL, SDLoc(N), N->getValueType(0),
19342                        N->getOperand(1), N->getOperand(2));
19343   case Intrinsic::aarch64_neon_umull:
19344     return DAG.getNode(AArch64ISD::UMULL, SDLoc(N), N->getValueType(0),
19345                        N->getOperand(1), N->getOperand(2));
19346   case Intrinsic::aarch64_neon_pmull:
19347     return DAG.getNode(AArch64ISD::PMULL, SDLoc(N), N->getValueType(0),
19348                        N->getOperand(1), N->getOperand(2));
19349   case Intrinsic::aarch64_neon_sqdmull:
19350     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
19351   case Intrinsic::aarch64_neon_sqshl:
19352   case Intrinsic::aarch64_neon_uqshl:
19353   case Intrinsic::aarch64_neon_sqshlu:
19354   case Intrinsic::aarch64_neon_srshl:
19355   case Intrinsic::aarch64_neon_urshl:
19356   case Intrinsic::aarch64_neon_sshl:
19357   case Intrinsic::aarch64_neon_ushl:
19358     return tryCombineShiftImm(IID, N, DAG);
19359   case Intrinsic::aarch64_neon_rshrn: {
19360     EVT VT = N->getOperand(1).getValueType();
19361     SDLoc DL(N);
19362     SDValue Imm =
19363         DAG.getConstant(1LLU << (N->getConstantOperandVal(2) - 1), DL, VT);
19364     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(1), Imm);
19365     SDValue Sht =
19366         DAG.getNode(ISD::SRL, DL, VT, Add,
19367                     DAG.getConstant(N->getConstantOperandVal(2), DL, VT));
19368     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), Sht);
19369   }
19370   case Intrinsic::aarch64_neon_sabd:
19371     return DAG.getNode(ISD::ABDS, SDLoc(N), N->getValueType(0),
19372                        N->getOperand(1), N->getOperand(2));
19373   case Intrinsic::aarch64_neon_uabd:
19374     return DAG.getNode(ISD::ABDU, SDLoc(N), N->getValueType(0),
19375                        N->getOperand(1), N->getOperand(2));
19376   case Intrinsic::aarch64_crc32b:
19377   case Intrinsic::aarch64_crc32cb:
19378     return tryCombineCRC32(0xff, N, DAG);
19379   case Intrinsic::aarch64_crc32h:
19380   case Intrinsic::aarch64_crc32ch:
19381     return tryCombineCRC32(0xffff, N, DAG);
19382   case Intrinsic::aarch64_sve_saddv:
19383     // There is no i64 version of SADDV because the sign is irrelevant.
19384     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
19385       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
19386     else
19387       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
19388   case Intrinsic::aarch64_sve_uaddv:
19389     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
19390   case Intrinsic::aarch64_sve_smaxv:
19391     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
19392   case Intrinsic::aarch64_sve_umaxv:
19393     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
19394   case Intrinsic::aarch64_sve_sminv:
19395     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
19396   case Intrinsic::aarch64_sve_uminv:
19397     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
19398   case Intrinsic::aarch64_sve_orv:
19399     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
19400   case Intrinsic::aarch64_sve_eorv:
19401     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
19402   case Intrinsic::aarch64_sve_andv:
19403     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
19404   case Intrinsic::aarch64_sve_index:
19405     return LowerSVEIntrinsicIndex(N, DAG);
19406   case Intrinsic::aarch64_sve_dup:
19407     return LowerSVEIntrinsicDUP(N, DAG);
19408   case Intrinsic::aarch64_sve_dup_x:
19409     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
19410                        N->getOperand(1));
19411   case Intrinsic::aarch64_sve_ext:
19412     return LowerSVEIntrinsicEXT(N, DAG);
19413   case Intrinsic::aarch64_sve_mul_u:
19414     return DAG.getNode(AArch64ISD::MUL_PRED, SDLoc(N), N->getValueType(0),
19415                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19416   case Intrinsic::aarch64_sve_smulh_u:
19417     return DAG.getNode(AArch64ISD::MULHS_PRED, SDLoc(N), N->getValueType(0),
19418                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19419   case Intrinsic::aarch64_sve_umulh_u:
19420     return DAG.getNode(AArch64ISD::MULHU_PRED, SDLoc(N), N->getValueType(0),
19421                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19422   case Intrinsic::aarch64_sve_smin_u:
19423     return DAG.getNode(AArch64ISD::SMIN_PRED, SDLoc(N), N->getValueType(0),
19424                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19425   case Intrinsic::aarch64_sve_umin_u:
19426     return DAG.getNode(AArch64ISD::UMIN_PRED, SDLoc(N), N->getValueType(0),
19427                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19428   case Intrinsic::aarch64_sve_smax_u:
19429     return DAG.getNode(AArch64ISD::SMAX_PRED, SDLoc(N), N->getValueType(0),
19430                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19431   case Intrinsic::aarch64_sve_umax_u:
19432     return DAG.getNode(AArch64ISD::UMAX_PRED, SDLoc(N), N->getValueType(0),
19433                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19434   case Intrinsic::aarch64_sve_lsl_u:
19435     return DAG.getNode(AArch64ISD::SHL_PRED, SDLoc(N), N->getValueType(0),
19436                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19437   case Intrinsic::aarch64_sve_lsr_u:
19438     return DAG.getNode(AArch64ISD::SRL_PRED, SDLoc(N), N->getValueType(0),
19439                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19440   case Intrinsic::aarch64_sve_asr_u:
19441     return DAG.getNode(AArch64ISD::SRA_PRED, SDLoc(N), N->getValueType(0),
19442                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19443   case Intrinsic::aarch64_sve_fadd_u:
19444     return DAG.getNode(AArch64ISD::FADD_PRED, SDLoc(N), N->getValueType(0),
19445                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19446   case Intrinsic::aarch64_sve_fdiv_u:
19447     return DAG.getNode(AArch64ISD::FDIV_PRED, SDLoc(N), N->getValueType(0),
19448                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19449   case Intrinsic::aarch64_sve_fmax_u:
19450     return DAG.getNode(AArch64ISD::FMAX_PRED, SDLoc(N), N->getValueType(0),
19451                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19452   case Intrinsic::aarch64_sve_fmaxnm_u:
19453     return DAG.getNode(AArch64ISD::FMAXNM_PRED, SDLoc(N), N->getValueType(0),
19454                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19455   case Intrinsic::aarch64_sve_fmla_u:
19456     return DAG.getNode(AArch64ISD::FMA_PRED, SDLoc(N), N->getValueType(0),
19457                        N->getOperand(1), N->getOperand(3), N->getOperand(4),
19458                        N->getOperand(2));
19459   case Intrinsic::aarch64_sve_fmin_u:
19460     return DAG.getNode(AArch64ISD::FMIN_PRED, SDLoc(N), N->getValueType(0),
19461                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19462   case Intrinsic::aarch64_sve_fminnm_u:
19463     return DAG.getNode(AArch64ISD::FMINNM_PRED, SDLoc(N), N->getValueType(0),
19464                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19465   case Intrinsic::aarch64_sve_fmul_u:
19466     return DAG.getNode(AArch64ISD::FMUL_PRED, SDLoc(N), N->getValueType(0),
19467                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19468   case Intrinsic::aarch64_sve_fsub_u:
19469     return DAG.getNode(AArch64ISD::FSUB_PRED, SDLoc(N), N->getValueType(0),
19470                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19471   case Intrinsic::aarch64_sve_add_u:
19472     return DAG.getNode(ISD::ADD, SDLoc(N), N->getValueType(0), N->getOperand(2),
19473                        N->getOperand(3));
19474   case Intrinsic::aarch64_sve_sub_u:
19475     return DAG.getNode(ISD::SUB, SDLoc(N), N->getValueType(0), N->getOperand(2),
19476                        N->getOperand(3));
19477   case Intrinsic::aarch64_sve_subr:
19478     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true, true);
19479   case Intrinsic::aarch64_sve_and_u:
19480     return DAG.getNode(ISD::AND, SDLoc(N), N->getValueType(0), N->getOperand(2),
19481                        N->getOperand(3));
19482   case Intrinsic::aarch64_sve_bic_u:
19483     return DAG.getNode(AArch64ISD::BIC, SDLoc(N), N->getValueType(0),
19484                        N->getOperand(2), N->getOperand(3));
19485   case Intrinsic::aarch64_sve_eor_u:
19486     return DAG.getNode(ISD::XOR, SDLoc(N), N->getValueType(0), N->getOperand(2),
19487                        N->getOperand(3));
19488   case Intrinsic::aarch64_sve_orr_u:
19489     return DAG.getNode(ISD::OR, SDLoc(N), N->getValueType(0), N->getOperand(2),
19490                        N->getOperand(3));
19491   case Intrinsic::aarch64_sve_sabd_u:
19492     return DAG.getNode(ISD::ABDS, SDLoc(N), N->getValueType(0),
19493                        N->getOperand(2), N->getOperand(3));
19494   case Intrinsic::aarch64_sve_uabd_u:
19495     return DAG.getNode(ISD::ABDU, SDLoc(N), N->getValueType(0),
19496                        N->getOperand(2), N->getOperand(3));
19497   case Intrinsic::aarch64_sve_sdiv_u:
19498     return DAG.getNode(AArch64ISD::SDIV_PRED, SDLoc(N), N->getValueType(0),
19499                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19500   case Intrinsic::aarch64_sve_udiv_u:
19501     return DAG.getNode(AArch64ISD::UDIV_PRED, SDLoc(N), N->getValueType(0),
19502                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19503   case Intrinsic::aarch64_sve_sqadd:
19504     return convertMergedOpToPredOp(N, ISD::SADDSAT, DAG, true);
19505   case Intrinsic::aarch64_sve_sqsub_u:
19506     return DAG.getNode(ISD::SSUBSAT, SDLoc(N), N->getValueType(0),
19507                        N->getOperand(2), N->getOperand(3));
19508   case Intrinsic::aarch64_sve_uqadd:
19509     return convertMergedOpToPredOp(N, ISD::UADDSAT, DAG, true);
19510   case Intrinsic::aarch64_sve_uqsub_u:
19511     return DAG.getNode(ISD::USUBSAT, SDLoc(N), N->getValueType(0),
19512                        N->getOperand(2), N->getOperand(3));
19513   case Intrinsic::aarch64_sve_sqadd_x:
19514     return DAG.getNode(ISD::SADDSAT, SDLoc(N), N->getValueType(0),
19515                        N->getOperand(1), N->getOperand(2));
19516   case Intrinsic::aarch64_sve_sqsub_x:
19517     return DAG.getNode(ISD::SSUBSAT, SDLoc(N), N->getValueType(0),
19518                        N->getOperand(1), N->getOperand(2));
19519   case Intrinsic::aarch64_sve_uqadd_x:
19520     return DAG.getNode(ISD::UADDSAT, SDLoc(N), N->getValueType(0),
19521                        N->getOperand(1), N->getOperand(2));
19522   case Intrinsic::aarch64_sve_uqsub_x:
19523     return DAG.getNode(ISD::USUBSAT, SDLoc(N), N->getValueType(0),
19524                        N->getOperand(1), N->getOperand(2));
19525   case Intrinsic::aarch64_sve_asrd:
19526     return DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, SDLoc(N), N->getValueType(0),
19527                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19528   case Intrinsic::aarch64_sve_cmphs:
19529     if (!N->getOperand(2).getValueType().isFloatingPoint())
19530       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19531                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
19532                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
19533     break;
19534   case Intrinsic::aarch64_sve_cmphi:
19535     if (!N->getOperand(2).getValueType().isFloatingPoint())
19536       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19537                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
19538                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
19539     break;
19540   case Intrinsic::aarch64_sve_fcmpge:
19541   case Intrinsic::aarch64_sve_cmpge:
19542     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19543                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
19544                        N->getOperand(3), DAG.getCondCode(ISD::SETGE));
19545     break;
19546   case Intrinsic::aarch64_sve_fcmpgt:
19547   case Intrinsic::aarch64_sve_cmpgt:
19548     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19549                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
19550                        N->getOperand(3), DAG.getCondCode(ISD::SETGT));
19551     break;
19552   case Intrinsic::aarch64_sve_fcmpeq:
19553   case Intrinsic::aarch64_sve_cmpeq:
19554     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19555                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
19556                        N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
19557     break;
19558   case Intrinsic::aarch64_sve_fcmpne:
19559   case Intrinsic::aarch64_sve_cmpne:
19560     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19561                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
19562                        N->getOperand(3), DAG.getCondCode(ISD::SETNE));
19563     break;
19564   case Intrinsic::aarch64_sve_fcmpuo:
19565     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
19566                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
19567                        N->getOperand(3), DAG.getCondCode(ISD::SETUO));
19568     break;
19569   case Intrinsic::aarch64_sve_fadda:
19570     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
19571   case Intrinsic::aarch64_sve_faddv:
19572     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
19573   case Intrinsic::aarch64_sve_fmaxnmv:
19574     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
19575   case Intrinsic::aarch64_sve_fmaxv:
19576     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
19577   case Intrinsic::aarch64_sve_fminnmv:
19578     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
19579   case Intrinsic::aarch64_sve_fminv:
19580     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
19581   case Intrinsic::aarch64_sve_sel:
19582     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
19583                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
19584   case Intrinsic::aarch64_sve_cmpeq_wide:
19585     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
19586   case Intrinsic::aarch64_sve_cmpne_wide:
19587     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
19588   case Intrinsic::aarch64_sve_cmpge_wide:
19589     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
19590   case Intrinsic::aarch64_sve_cmpgt_wide:
19591     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
19592   case Intrinsic::aarch64_sve_cmplt_wide:
19593     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
19594   case Intrinsic::aarch64_sve_cmple_wide:
19595     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
19596   case Intrinsic::aarch64_sve_cmphs_wide:
19597     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
19598   case Intrinsic::aarch64_sve_cmphi_wide:
19599     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
19600   case Intrinsic::aarch64_sve_cmplo_wide:
19601     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
19602   case Intrinsic::aarch64_sve_cmpls_wide:
19603     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
19604   case Intrinsic::aarch64_sve_ptest_any:
19605     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
19606                     AArch64CC::ANY_ACTIVE);
19607   case Intrinsic::aarch64_sve_ptest_first:
19608     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
19609                     AArch64CC::FIRST_ACTIVE);
19610   case Intrinsic::aarch64_sve_ptest_last:
19611     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
19612                     AArch64CC::LAST_ACTIVE);
19613   }
19614   return SDValue();
19615 }
19616 
19617 static bool isCheapToExtend(const SDValue &N) {
19618   unsigned OC = N->getOpcode();
19619   return OC == ISD::LOAD || OC == ISD::MLOAD ||
19620          ISD::isConstantSplatVectorAllZeros(N.getNode());
19621 }
19622 
19623 static SDValue
19624 performSignExtendSetCCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
19625                               SelectionDAG &DAG) {
19626   // If we have (sext (setcc A B)) and A and B are cheap to extend,
19627   // we can move the sext into the arguments and have the same result. For
19628   // example, if A and B are both loads, we can make those extending loads and
19629   // avoid an extra instruction. This pattern appears often in VLS code
19630   // generation where the inputs to the setcc have a different size to the
19631   // instruction that wants to use the result of the setcc.
19632   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
19633          N->getOperand(0)->getOpcode() == ISD::SETCC);
19634   const SDValue SetCC = N->getOperand(0);
19635 
19636   const SDValue CCOp0 = SetCC.getOperand(0);
19637   const SDValue CCOp1 = SetCC.getOperand(1);
19638   if (!CCOp0->getValueType(0).isInteger() ||
19639       !CCOp1->getValueType(0).isInteger())
19640     return SDValue();
19641 
19642   ISD::CondCode Code =
19643       cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get();
19644 
19645   ISD::NodeType ExtType =
19646       isSignedIntSetCC(Code) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19647 
19648   if (isCheapToExtend(SetCC.getOperand(0)) &&
19649       isCheapToExtend(SetCC.getOperand(1))) {
19650     const SDValue Ext1 =
19651         DAG.getNode(ExtType, SDLoc(N), N->getValueType(0), CCOp0);
19652     const SDValue Ext2 =
19653         DAG.getNode(ExtType, SDLoc(N), N->getValueType(0), CCOp1);
19654 
19655     return DAG.getSetCC(
19656         SDLoc(SetCC), N->getValueType(0), Ext1, Ext2,
19657         cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get());
19658   }
19659 
19660   return SDValue();
19661 }
19662 
19663 static SDValue performExtendCombine(SDNode *N,
19664                                     TargetLowering::DAGCombinerInfo &DCI,
19665                                     SelectionDAG &DAG) {
19666   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
19667   // we can convert that DUP into another extract_high (of a bigger DUP), which
19668   // helps the backend to decide that an sabdl2 would be useful, saving a real
19669   // extract_high operation.
19670   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
19671       (N->getOperand(0).getOpcode() == ISD::ABDU ||
19672        N->getOperand(0).getOpcode() == ISD::ABDS)) {
19673     SDNode *ABDNode = N->getOperand(0).getNode();
19674     SDValue NewABD =
19675         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
19676     if (!NewABD.getNode())
19677       return SDValue();
19678 
19679     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
19680   }
19681 
19682   if (N->getValueType(0).isFixedLengthVector() &&
19683       N->getOpcode() == ISD::SIGN_EXTEND &&
19684       N->getOperand(0)->getOpcode() == ISD::SETCC)
19685     return performSignExtendSetCCCombine(N, DCI, DAG);
19686 
19687   return SDValue();
19688 }
19689 
19690 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
19691                                SDValue SplatVal, unsigned NumVecElts) {
19692   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
19693   Align OrigAlignment = St.getAlign();
19694   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
19695 
19696   // Create scalar stores. This is at least as good as the code sequence for a
19697   // split unaligned store which is a dup.s, ext.b, and two stores.
19698   // Most of the time the three stores should be replaced by store pair
19699   // instructions (stp).
19700   SDLoc DL(&St);
19701   SDValue BasePtr = St.getBasePtr();
19702   uint64_t BaseOffset = 0;
19703 
19704   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
19705   SDValue NewST1 =
19706       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
19707                    OrigAlignment, St.getMemOperand()->getFlags());
19708 
19709   // As this in ISel, we will not merge this add which may degrade results.
19710   if (BasePtr->getOpcode() == ISD::ADD &&
19711       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
19712     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
19713     BasePtr = BasePtr->getOperand(0);
19714   }
19715 
19716   unsigned Offset = EltOffset;
19717   while (--NumVecElts) {
19718     Align Alignment = commonAlignment(OrigAlignment, Offset);
19719     SDValue OffsetPtr =
19720         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
19721                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
19722     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
19723                           PtrInfo.getWithOffset(Offset), Alignment,
19724                           St.getMemOperand()->getFlags());
19725     Offset += EltOffset;
19726   }
19727   return NewST1;
19728 }
19729 
19730 // Returns an SVE type that ContentTy can be trivially sign or zero extended
19731 // into.
19732 static MVT getSVEContainerType(EVT ContentTy) {
19733   assert(ContentTy.isSimple() && "No SVE containers for extended types");
19734 
19735   switch (ContentTy.getSimpleVT().SimpleTy) {
19736   default:
19737     llvm_unreachable("No known SVE container for this MVT type");
19738   case MVT::nxv2i8:
19739   case MVT::nxv2i16:
19740   case MVT::nxv2i32:
19741   case MVT::nxv2i64:
19742   case MVT::nxv2f32:
19743   case MVT::nxv2f64:
19744     return MVT::nxv2i64;
19745   case MVT::nxv4i8:
19746   case MVT::nxv4i16:
19747   case MVT::nxv4i32:
19748   case MVT::nxv4f32:
19749     return MVT::nxv4i32;
19750   case MVT::nxv8i8:
19751   case MVT::nxv8i16:
19752   case MVT::nxv8f16:
19753   case MVT::nxv8bf16:
19754     return MVT::nxv8i16;
19755   case MVT::nxv16i8:
19756     return MVT::nxv16i8;
19757   }
19758 }
19759 
19760 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
19761   SDLoc DL(N);
19762   EVT VT = N->getValueType(0);
19763 
19764   if (VT.getSizeInBits().getKnownMinValue() > AArch64::SVEBitsPerBlock)
19765     return SDValue();
19766 
19767   EVT ContainerVT = VT;
19768   if (ContainerVT.isInteger())
19769     ContainerVT = getSVEContainerType(ContainerVT);
19770 
19771   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
19772   SDValue Ops[] = { N->getOperand(0), // Chain
19773                     N->getOperand(2), // Pg
19774                     N->getOperand(3), // Base
19775                     DAG.getValueType(VT) };
19776 
19777   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
19778   SDValue LoadChain = SDValue(Load.getNode(), 1);
19779 
19780   if (ContainerVT.isInteger() && (VT != ContainerVT))
19781     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
19782 
19783   return DAG.getMergeValues({ Load, LoadChain }, DL);
19784 }
19785 
19786 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
19787   SDLoc DL(N);
19788   EVT VT = N->getValueType(0);
19789   EVT PtrTy = N->getOperand(3).getValueType();
19790 
19791   EVT LoadVT = VT;
19792   if (VT.isFloatingPoint())
19793     LoadVT = VT.changeTypeToInteger();
19794 
19795   auto *MINode = cast<MemIntrinsicSDNode>(N);
19796   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
19797   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
19798                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
19799                                 MINode->getOperand(2), PassThru,
19800                                 MINode->getMemoryVT(), MINode->getMemOperand(),
19801                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
19802 
19803    if (VT.isFloatingPoint()) {
19804      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
19805      return DAG.getMergeValues(Ops, DL);
19806    }
19807 
19808   return L;
19809 }
19810 
19811 template <unsigned Opcode>
19812 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
19813   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
19814                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
19815                 "Unsupported opcode.");
19816   SDLoc DL(N);
19817   EVT VT = N->getValueType(0);
19818 
19819   EVT LoadVT = VT;
19820   if (VT.isFloatingPoint())
19821     LoadVT = VT.changeTypeToInteger();
19822 
19823   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
19824   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
19825   SDValue LoadChain = SDValue(Load.getNode(), 1);
19826 
19827   if (VT.isFloatingPoint())
19828     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
19829 
19830   return DAG.getMergeValues({Load, LoadChain}, DL);
19831 }
19832 
19833 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
19834   SDLoc DL(N);
19835   SDValue Data = N->getOperand(2);
19836   EVT DataVT = Data.getValueType();
19837   EVT HwSrcVt = getSVEContainerType(DataVT);
19838   SDValue InputVT = DAG.getValueType(DataVT);
19839 
19840   if (DataVT.isFloatingPoint())
19841     InputVT = DAG.getValueType(HwSrcVt);
19842 
19843   SDValue SrcNew;
19844   if (Data.getValueType().isFloatingPoint())
19845     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
19846   else
19847     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
19848 
19849   SDValue Ops[] = { N->getOperand(0), // Chain
19850                     SrcNew,
19851                     N->getOperand(4), // Base
19852                     N->getOperand(3), // Pg
19853                     InputVT
19854                   };
19855 
19856   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
19857 }
19858 
19859 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
19860   SDLoc DL(N);
19861 
19862   SDValue Data = N->getOperand(2);
19863   EVT DataVT = Data.getValueType();
19864   EVT PtrTy = N->getOperand(4).getValueType();
19865 
19866   if (DataVT.isFloatingPoint())
19867     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
19868 
19869   auto *MINode = cast<MemIntrinsicSDNode>(N);
19870   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
19871                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
19872                             MINode->getMemoryVT(), MINode->getMemOperand(),
19873                             ISD::UNINDEXED, false, false);
19874 }
19875 
19876 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
19877 /// load store optimizer pass will merge them to store pair stores.  This should
19878 /// be better than a movi to create the vector zero followed by a vector store
19879 /// if the zero constant is not re-used, since one instructions and one register
19880 /// live range will be removed.
19881 ///
19882 /// For example, the final generated code should be:
19883 ///
19884 ///   stp xzr, xzr, [x0]
19885 ///
19886 /// instead of:
19887 ///
19888 ///   movi v0.2d, #0
19889 ///   str q0, [x0]
19890 ///
19891 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
19892   SDValue StVal = St.getValue();
19893   EVT VT = StVal.getValueType();
19894 
19895   // Avoid scalarizing zero splat stores for scalable vectors.
19896   if (VT.isScalableVector())
19897     return SDValue();
19898 
19899   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
19900   // 2, 3 or 4 i32 elements.
19901   int NumVecElts = VT.getVectorNumElements();
19902   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
19903          VT.getVectorElementType().getSizeInBits() == 64) ||
19904         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
19905          VT.getVectorElementType().getSizeInBits() == 32)))
19906     return SDValue();
19907 
19908   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
19909     return SDValue();
19910 
19911   // If the zero constant has more than one use then the vector store could be
19912   // better since the constant mov will be amortized and stp q instructions
19913   // should be able to be formed.
19914   if (!StVal.hasOneUse())
19915     return SDValue();
19916 
19917   // If the store is truncating then it's going down to i16 or smaller, which
19918   // means it can be implemented in a single store anyway.
19919   if (St.isTruncatingStore())
19920     return SDValue();
19921 
19922   // If the immediate offset of the address operand is too large for the stp
19923   // instruction, then bail out.
19924   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
19925     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
19926     if (Offset < -512 || Offset > 504)
19927       return SDValue();
19928   }
19929 
19930   for (int I = 0; I < NumVecElts; ++I) {
19931     SDValue EltVal = StVal.getOperand(I);
19932     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
19933       return SDValue();
19934   }
19935 
19936   // Use a CopyFromReg WZR/XZR here to prevent
19937   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
19938   SDLoc DL(&St);
19939   unsigned ZeroReg;
19940   EVT ZeroVT;
19941   if (VT.getVectorElementType().getSizeInBits() == 32) {
19942     ZeroReg = AArch64::WZR;
19943     ZeroVT = MVT::i32;
19944   } else {
19945     ZeroReg = AArch64::XZR;
19946     ZeroVT = MVT::i64;
19947   }
19948   SDValue SplatVal =
19949       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
19950   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
19951 }
19952 
19953 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
19954 /// value. The load store optimizer pass will merge them to store pair stores.
19955 /// This has better performance than a splat of the scalar followed by a split
19956 /// vector store. Even if the stores are not merged it is four stores vs a dup,
19957 /// followed by an ext.b and two stores.
19958 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
19959   SDValue StVal = St.getValue();
19960   EVT VT = StVal.getValueType();
19961 
19962   // Don't replace floating point stores, they possibly won't be transformed to
19963   // stp because of the store pair suppress pass.
19964   if (VT.isFloatingPoint())
19965     return SDValue();
19966 
19967   // We can express a splat as store pair(s) for 2 or 4 elements.
19968   unsigned NumVecElts = VT.getVectorNumElements();
19969   if (NumVecElts != 4 && NumVecElts != 2)
19970     return SDValue();
19971 
19972   // If the store is truncating then it's going down to i16 or smaller, which
19973   // means it can be implemented in a single store anyway.
19974   if (St.isTruncatingStore())
19975     return SDValue();
19976 
19977   // Check that this is a splat.
19978   // Make sure that each of the relevant vector element locations are inserted
19979   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
19980   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
19981   SDValue SplatVal;
19982   for (unsigned I = 0; I < NumVecElts; ++I) {
19983     // Check for insert vector elements.
19984     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
19985       return SDValue();
19986 
19987     // Check that same value is inserted at each vector element.
19988     if (I == 0)
19989       SplatVal = StVal.getOperand(1);
19990     else if (StVal.getOperand(1) != SplatVal)
19991       return SDValue();
19992 
19993     // Check insert element index.
19994     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
19995     if (!CIndex)
19996       return SDValue();
19997     uint64_t IndexVal = CIndex->getZExtValue();
19998     if (IndexVal >= NumVecElts)
19999       return SDValue();
20000     IndexNotInserted.reset(IndexVal);
20001 
20002     StVal = StVal.getOperand(0);
20003   }
20004   // Check that all vector element locations were inserted to.
20005   if (IndexNotInserted.any())
20006       return SDValue();
20007 
20008   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
20009 }
20010 
20011 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
20012                            SelectionDAG &DAG,
20013                            const AArch64Subtarget *Subtarget) {
20014 
20015   StoreSDNode *S = cast<StoreSDNode>(N);
20016   if (S->isVolatile() || S->isIndexed())
20017     return SDValue();
20018 
20019   SDValue StVal = S->getValue();
20020   EVT VT = StVal.getValueType();
20021 
20022   if (!VT.isFixedLengthVector())
20023     return SDValue();
20024 
20025   // If we get a splat of zeros, convert this vector store to a store of
20026   // scalars. They will be merged into store pairs of xzr thereby removing one
20027   // instruction and one register.
20028   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
20029     return ReplacedZeroSplat;
20030 
20031   // FIXME: The logic for deciding if an unaligned store should be split should
20032   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
20033   // a call to that function here.
20034 
20035   if (!Subtarget->isMisaligned128StoreSlow())
20036     return SDValue();
20037 
20038   // Don't split at -Oz.
20039   if (DAG.getMachineFunction().getFunction().hasMinSize())
20040     return SDValue();
20041 
20042   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
20043   // those up regresses performance on micro-benchmarks and olden/bh.
20044   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
20045     return SDValue();
20046 
20047   // Split unaligned 16B stores. They are terrible for performance.
20048   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
20049   // extensions can use this to mark that it does not want splitting to happen
20050   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
20051   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
20052   if (VT.getSizeInBits() != 128 || S->getAlign() >= Align(16) ||
20053       S->getAlign() <= Align(2))
20054     return SDValue();
20055 
20056   // If we get a splat of a scalar convert this vector store to a store of
20057   // scalars. They will be merged into store pairs thereby removing two
20058   // instructions.
20059   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
20060     return ReplacedSplat;
20061 
20062   SDLoc DL(S);
20063 
20064   // Split VT into two.
20065   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
20066   unsigned NumElts = HalfVT.getVectorNumElements();
20067   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
20068                                    DAG.getConstant(0, DL, MVT::i64));
20069   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
20070                                    DAG.getConstant(NumElts, DL, MVT::i64));
20071   SDValue BasePtr = S->getBasePtr();
20072   SDValue NewST1 =
20073       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
20074                    S->getAlign(), S->getMemOperand()->getFlags());
20075   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
20076                                   DAG.getConstant(8, DL, MVT::i64));
20077   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
20078                       S->getPointerInfo(), S->getAlign(),
20079                       S->getMemOperand()->getFlags());
20080 }
20081 
20082 static SDValue performSpliceCombine(SDNode *N, SelectionDAG &DAG) {
20083   assert(N->getOpcode() == AArch64ISD::SPLICE && "Unexepected Opcode!");
20084 
20085   // splice(pg, op1, undef) -> op1
20086   if (N->getOperand(2).isUndef())
20087     return N->getOperand(1);
20088 
20089   return SDValue();
20090 }
20091 
20092 static SDValue performUnpackCombine(SDNode *N, SelectionDAG &DAG,
20093                                     const AArch64Subtarget *Subtarget) {
20094   assert((N->getOpcode() == AArch64ISD::UUNPKHI ||
20095           N->getOpcode() == AArch64ISD::UUNPKLO) &&
20096          "Unexpected Opcode!");
20097 
20098   // uunpklo/hi undef -> undef
20099   if (N->getOperand(0).isUndef())
20100     return DAG.getUNDEF(N->getValueType(0));
20101 
20102   // If this is a masked load followed by an UUNPKLO, fold this into a masked
20103   // extending load.  We can do this even if this is already a masked
20104   // {z,}extload.
20105   if (N->getOperand(0).getOpcode() == ISD::MLOAD &&
20106       N->getOpcode() == AArch64ISD::UUNPKLO) {
20107     MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N->getOperand(0));
20108     SDValue Mask = MLD->getMask();
20109     SDLoc DL(N);
20110 
20111     if (MLD->isUnindexed() && MLD->getExtensionType() != ISD::SEXTLOAD &&
20112         SDValue(MLD, 0).hasOneUse() && Mask->getOpcode() == AArch64ISD::PTRUE &&
20113         (MLD->getPassThru()->isUndef() ||
20114          isZerosVector(MLD->getPassThru().getNode()))) {
20115       unsigned MinSVESize = Subtarget->getMinSVEVectorSizeInBits();
20116       unsigned PgPattern = Mask->getConstantOperandVal(0);
20117       EVT VT = N->getValueType(0);
20118 
20119       // Ensure we can double the size of the predicate pattern
20120       unsigned NumElts = getNumElementsFromSVEPredPattern(PgPattern);
20121       if (NumElts &&
20122           NumElts * VT.getVectorElementType().getSizeInBits() <= MinSVESize) {
20123         Mask =
20124             getPTrue(DAG, DL, VT.changeVectorElementType(MVT::i1), PgPattern);
20125         SDValue PassThru = DAG.getConstant(0, DL, VT);
20126         SDValue NewLoad = DAG.getMaskedLoad(
20127             VT, DL, MLD->getChain(), MLD->getBasePtr(), MLD->getOffset(), Mask,
20128             PassThru, MLD->getMemoryVT(), MLD->getMemOperand(),
20129             MLD->getAddressingMode(), ISD::ZEXTLOAD);
20130 
20131         DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), NewLoad.getValue(1));
20132 
20133         return NewLoad;
20134       }
20135     }
20136   }
20137 
20138   return SDValue();
20139 }
20140 
20141 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
20142   SDLoc DL(N);
20143   SDValue Op0 = N->getOperand(0);
20144   SDValue Op1 = N->getOperand(1);
20145   EVT ResVT = N->getValueType(0);
20146 
20147   // uzp1(x, undef) -> concat(truncate(x), undef)
20148   if (Op1.getOpcode() == ISD::UNDEF) {
20149     EVT BCVT = MVT::Other, HalfVT = MVT::Other;
20150     switch (ResVT.getSimpleVT().SimpleTy) {
20151     default:
20152       break;
20153     case MVT::v16i8:
20154       BCVT = MVT::v8i16;
20155       HalfVT = MVT::v8i8;
20156       break;
20157     case MVT::v8i16:
20158       BCVT = MVT::v4i32;
20159       HalfVT = MVT::v4i16;
20160       break;
20161     case MVT::v4i32:
20162       BCVT = MVT::v2i64;
20163       HalfVT = MVT::v2i32;
20164       break;
20165     }
20166     if (BCVT != MVT::Other) {
20167       SDValue BC = DAG.getBitcast(BCVT, Op0);
20168       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, BC);
20169       return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Trunc,
20170                          DAG.getUNDEF(HalfVT));
20171     }
20172   }
20173 
20174   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
20175   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
20176     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
20177       SDValue X = Op0.getOperand(0).getOperand(0);
20178       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
20179     }
20180   }
20181 
20182   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
20183   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
20184     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
20185       SDValue Z = Op1.getOperand(0).getOperand(1);
20186       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
20187     }
20188   }
20189 
20190   // uzp1(xtn x, xtn y) -> xtn(uzp1 (x, y))
20191   // Only implemented on little-endian subtargets.
20192   bool IsLittleEndian = DAG.getDataLayout().isLittleEndian();
20193 
20194   // This optimization only works on little endian.
20195   if (!IsLittleEndian)
20196     return SDValue();
20197 
20198   if (ResVT != MVT::v2i32 && ResVT != MVT::v4i16 && ResVT != MVT::v8i8)
20199     return SDValue();
20200 
20201   auto getSourceOp = [](SDValue Operand) -> SDValue {
20202     const unsigned Opcode = Operand.getOpcode();
20203     if (Opcode == ISD::TRUNCATE)
20204       return Operand->getOperand(0);
20205     if (Opcode == ISD::BITCAST &&
20206         Operand->getOperand(0).getOpcode() == ISD::TRUNCATE)
20207       return Operand->getOperand(0)->getOperand(0);
20208     return SDValue();
20209   };
20210 
20211   SDValue SourceOp0 = getSourceOp(Op0);
20212   SDValue SourceOp1 = getSourceOp(Op1);
20213 
20214   if (!SourceOp0 || !SourceOp1)
20215     return SDValue();
20216 
20217   if (SourceOp0.getValueType() != SourceOp1.getValueType() ||
20218       !SourceOp0.getValueType().isSimple())
20219     return SDValue();
20220 
20221   EVT ResultTy;
20222 
20223   switch (SourceOp0.getSimpleValueType().SimpleTy) {
20224   case MVT::v2i64:
20225     ResultTy = MVT::v4i32;
20226     break;
20227   case MVT::v4i32:
20228     ResultTy = MVT::v8i16;
20229     break;
20230   case MVT::v8i16:
20231     ResultTy = MVT::v16i8;
20232     break;
20233   default:
20234     return SDValue();
20235   }
20236 
20237   SDValue UzpOp0 = DAG.getNode(ISD::BITCAST, DL, ResultTy, SourceOp0);
20238   SDValue UzpOp1 = DAG.getNode(ISD::BITCAST, DL, ResultTy, SourceOp1);
20239   SDValue UzpResult =
20240       DAG.getNode(AArch64ISD::UZP1, DL, UzpOp0.getValueType(), UzpOp0, UzpOp1);
20241 
20242   EVT BitcastResultTy;
20243 
20244   switch (ResVT.getSimpleVT().SimpleTy) {
20245   case MVT::v2i32:
20246     BitcastResultTy = MVT::v2i64;
20247     break;
20248   case MVT::v4i16:
20249     BitcastResultTy = MVT::v4i32;
20250     break;
20251   case MVT::v8i8:
20252     BitcastResultTy = MVT::v8i16;
20253     break;
20254   default:
20255     llvm_unreachable("Should be one of {v2i32, v4i16, v8i8}");
20256   }
20257 
20258   return DAG.getNode(ISD::TRUNCATE, DL, ResVT,
20259                      DAG.getNode(ISD::BITCAST, DL, BitcastResultTy, UzpResult));
20260 }
20261 
20262 static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) {
20263   unsigned Opc = N->getOpcode();
20264 
20265   assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads
20266            Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) ||
20267           (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads
20268            Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) &&
20269          "Invalid opcode.");
20270 
20271   const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO ||
20272                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
20273   const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO ||
20274                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
20275   const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO ||
20276                         Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO ||
20277                         Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO ||
20278                         Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO;
20279 
20280   SDLoc DL(N);
20281   SDValue Chain = N->getOperand(0);
20282   SDValue Pg = N->getOperand(1);
20283   SDValue Base = N->getOperand(2);
20284   SDValue Offset = N->getOperand(3);
20285   SDValue Ty = N->getOperand(4);
20286 
20287   EVT ResVT = N->getValueType(0);
20288 
20289   const auto OffsetOpc = Offset.getOpcode();
20290   const bool OffsetIsZExt =
20291       OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU;
20292   const bool OffsetIsSExt =
20293       OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU;
20294 
20295   // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible.
20296   if (!Extended && (OffsetIsSExt || OffsetIsZExt)) {
20297     SDValue ExtPg = Offset.getOperand(0);
20298     VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode());
20299     EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType();
20300 
20301     // If the predicate for the sign- or zero-extended offset is the
20302     // same as the predicate used for this load and the sign-/zero-extension
20303     // was from a 32-bits...
20304     if (ExtPg == Pg && ExtFromEVT == MVT::i32) {
20305       SDValue UnextendedOffset = Offset.getOperand(1);
20306 
20307       unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true);
20308       if (Signed)
20309         NewOpc = getSignExtendedGatherOpcode(NewOpc);
20310 
20311       return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other},
20312                          {Chain, Pg, Base, UnextendedOffset, Ty});
20313     }
20314   }
20315 
20316   return SDValue();
20317 }
20318 
20319 /// Optimize a vector shift instruction and its operand if shifted out
20320 /// bits are not used.
20321 static SDValue performVectorShiftCombine(SDNode *N,
20322                                          const AArch64TargetLowering &TLI,
20323                                          TargetLowering::DAGCombinerInfo &DCI) {
20324   assert(N->getOpcode() == AArch64ISD::VASHR ||
20325          N->getOpcode() == AArch64ISD::VLSHR);
20326 
20327   SDValue Op = N->getOperand(0);
20328   unsigned OpScalarSize = Op.getScalarValueSizeInBits();
20329 
20330   unsigned ShiftImm = N->getConstantOperandVal(1);
20331   assert(OpScalarSize > ShiftImm && "Invalid shift imm");
20332 
20333   // Remove sign_extend_inreg (ashr(shl(x)) based on the number of sign bits.
20334   if (N->getOpcode() == AArch64ISD::VASHR &&
20335       Op.getOpcode() == AArch64ISD::VSHL &&
20336       N->getOperand(1) == Op.getOperand(1))
20337     if (DCI.DAG.ComputeNumSignBits(Op.getOperand(0)) > ShiftImm)
20338       return Op.getOperand(0);
20339 
20340   APInt ShiftedOutBits = APInt::getLowBitsSet(OpScalarSize, ShiftImm);
20341   APInt DemandedMask = ~ShiftedOutBits;
20342 
20343   if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
20344     return SDValue(N, 0);
20345 
20346   return SDValue();
20347 }
20348 
20349 static SDValue performSunpkloCombine(SDNode *N, SelectionDAG &DAG) {
20350   // sunpklo(sext(pred)) -> sext(extract_low_half(pred))
20351   // This transform works in partnership with performSetCCPunpkCombine to
20352   // remove unnecessary transfer of predicates into standard registers and back
20353   if (N->getOperand(0).getOpcode() == ISD::SIGN_EXTEND &&
20354       N->getOperand(0)->getOperand(0)->getValueType(0).getScalarType() ==
20355           MVT::i1) {
20356     SDValue CC = N->getOperand(0)->getOperand(0);
20357     auto VT = CC->getValueType(0).getHalfNumVectorElementsVT(*DAG.getContext());
20358     SDValue Unpk = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT, CC,
20359                                DAG.getVectorIdxConstant(0, SDLoc(N)));
20360     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), N->getValueType(0), Unpk);
20361   }
20362 
20363   return SDValue();
20364 }
20365 
20366 /// Target-specific DAG combine function for post-increment LD1 (lane) and
20367 /// post-increment LD1R.
20368 static SDValue performPostLD1Combine(SDNode *N,
20369                                      TargetLowering::DAGCombinerInfo &DCI,
20370                                      bool IsLaneOp) {
20371   if (DCI.isBeforeLegalizeOps())
20372     return SDValue();
20373 
20374   SelectionDAG &DAG = DCI.DAG;
20375   EVT VT = N->getValueType(0);
20376 
20377   if (!VT.is128BitVector() && !VT.is64BitVector())
20378     return SDValue();
20379 
20380   unsigned LoadIdx = IsLaneOp ? 1 : 0;
20381   SDNode *LD = N->getOperand(LoadIdx).getNode();
20382   // If it is not LOAD, can not do such combine.
20383   if (LD->getOpcode() != ISD::LOAD)
20384     return SDValue();
20385 
20386   // The vector lane must be a constant in the LD1LANE opcode.
20387   SDValue Lane;
20388   if (IsLaneOp) {
20389     Lane = N->getOperand(2);
20390     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
20391     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
20392       return SDValue();
20393   }
20394 
20395   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
20396   EVT MemVT = LoadSDN->getMemoryVT();
20397   // Check if memory operand is the same type as the vector element.
20398   if (MemVT != VT.getVectorElementType())
20399     return SDValue();
20400 
20401   // Check if there are other uses. If so, do not combine as it will introduce
20402   // an extra load.
20403   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
20404        ++UI) {
20405     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
20406       continue;
20407     if (*UI != N)
20408       return SDValue();
20409   }
20410 
20411   // If there is one use and it can splat the value, prefer that operation.
20412   // TODO: This could be expanded to more operations if they reliably use the
20413   // index variants.
20414   if (N->hasOneUse()) {
20415     unsigned UseOpc = N->use_begin()->getOpcode();
20416     if (UseOpc == ISD::FMUL || UseOpc == ISD::FMA)
20417       return SDValue();
20418   }
20419 
20420   SDValue Addr = LD->getOperand(1);
20421   SDValue Vector = N->getOperand(0);
20422   // Search for a use of the address operand that is an increment.
20423   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
20424        Addr.getNode()->use_end(); UI != UE; ++UI) {
20425     SDNode *User = *UI;
20426     if (User->getOpcode() != ISD::ADD
20427         || UI.getUse().getResNo() != Addr.getResNo())
20428       continue;
20429 
20430     // If the increment is a constant, it must match the memory ref size.
20431     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
20432     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
20433       uint32_t IncVal = CInc->getZExtValue();
20434       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
20435       if (IncVal != NumBytes)
20436         continue;
20437       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
20438     }
20439 
20440     // To avoid cycle construction make sure that neither the load nor the add
20441     // are predecessors to each other or the Vector.
20442     SmallPtrSet<const SDNode *, 32> Visited;
20443     SmallVector<const SDNode *, 16> Worklist;
20444     Visited.insert(Addr.getNode());
20445     Worklist.push_back(User);
20446     Worklist.push_back(LD);
20447     Worklist.push_back(Vector.getNode());
20448     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
20449         SDNode::hasPredecessorHelper(User, Visited, Worklist))
20450       continue;
20451 
20452     SmallVector<SDValue, 8> Ops;
20453     Ops.push_back(LD->getOperand(0));  // Chain
20454     if (IsLaneOp) {
20455       Ops.push_back(Vector);           // The vector to be inserted
20456       Ops.push_back(Lane);             // The lane to be inserted in the vector
20457     }
20458     Ops.push_back(Addr);
20459     Ops.push_back(Inc);
20460 
20461     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
20462     SDVTList SDTys = DAG.getVTList(Tys);
20463     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
20464     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
20465                                            MemVT,
20466                                            LoadSDN->getMemOperand());
20467 
20468     // Update the uses.
20469     SDValue NewResults[] = {
20470         SDValue(LD, 0),            // The result of load
20471         SDValue(UpdN.getNode(), 2) // Chain
20472     };
20473     DCI.CombineTo(LD, NewResults);
20474     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
20475     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
20476 
20477     break;
20478   }
20479   return SDValue();
20480 }
20481 
20482 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
20483 /// address translation.
20484 static bool performTBISimplification(SDValue Addr,
20485                                      TargetLowering::DAGCombinerInfo &DCI,
20486                                      SelectionDAG &DAG) {
20487   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
20488   KnownBits Known;
20489   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20490                                         !DCI.isBeforeLegalizeOps());
20491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20492   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
20493     DCI.CommitTargetLoweringOpt(TLO);
20494     return true;
20495   }
20496   return false;
20497 }
20498 
20499 static SDValue foldTruncStoreOfExt(SelectionDAG &DAG, SDNode *N) {
20500   assert((N->getOpcode() == ISD::STORE || N->getOpcode() == ISD::MSTORE) &&
20501          "Expected STORE dag node in input!");
20502 
20503   if (auto Store = dyn_cast<StoreSDNode>(N)) {
20504     if (!Store->isTruncatingStore() || Store->isIndexed())
20505       return SDValue();
20506     SDValue Ext = Store->getValue();
20507     auto ExtOpCode = Ext.getOpcode();
20508     if (ExtOpCode != ISD::ZERO_EXTEND && ExtOpCode != ISD::SIGN_EXTEND &&
20509         ExtOpCode != ISD::ANY_EXTEND)
20510       return SDValue();
20511     SDValue Orig = Ext->getOperand(0);
20512     if (Store->getMemoryVT() != Orig.getValueType())
20513       return SDValue();
20514     return DAG.getStore(Store->getChain(), SDLoc(Store), Orig,
20515                         Store->getBasePtr(), Store->getMemOperand());
20516   }
20517 
20518   return SDValue();
20519 }
20520 
20521 // Perform TBI simplification if supported by the target and try to break up
20522 // nontemporal loads larger than 256-bits loads for odd types so LDNPQ 256-bit
20523 // load instructions can be selected.
20524 static SDValue performLOADCombine(SDNode *N,
20525                                   TargetLowering::DAGCombinerInfo &DCI,
20526                                   SelectionDAG &DAG,
20527                                   const AArch64Subtarget *Subtarget) {
20528   if (Subtarget->supportsAddressTopByteIgnored())
20529     performTBISimplification(N->getOperand(1), DCI, DAG);
20530 
20531   LoadSDNode *LD = cast<LoadSDNode>(N);
20532   EVT MemVT = LD->getMemoryVT();
20533   if (LD->isVolatile() || !LD->isNonTemporal() || !Subtarget->isLittleEndian())
20534     return SDValue(N, 0);
20535 
20536   if (MemVT.isScalableVector() || MemVT.getSizeInBits() <= 256 ||
20537       MemVT.getSizeInBits() % 256 == 0 ||
20538       256 % MemVT.getScalarSizeInBits() != 0)
20539     return SDValue(N, 0);
20540 
20541   SDLoc DL(LD);
20542   SDValue Chain = LD->getChain();
20543   SDValue BasePtr = LD->getBasePtr();
20544   SDNodeFlags Flags = LD->getFlags();
20545   SmallVector<SDValue, 4> LoadOps;
20546   SmallVector<SDValue, 4> LoadOpsChain;
20547   // Replace any non temporal load over 256-bit with a series of 256 bit loads
20548   // and a scalar/vector load less than 256. This way we can utilize 256-bit
20549   // loads and reduce the amount of load instructions generated.
20550   MVT NewVT =
20551       MVT::getVectorVT(MemVT.getVectorElementType().getSimpleVT(),
20552                        256 / MemVT.getVectorElementType().getSizeInBits());
20553   unsigned Num256Loads = MemVT.getSizeInBits() / 256;
20554   // Create all 256-bit loads starting from offset 0 and up to Num256Loads-1*32.
20555   for (unsigned I = 0; I < Num256Loads; I++) {
20556     unsigned PtrOffset = I * 32;
20557     SDValue NewPtr = DAG.getMemBasePlusOffset(
20558         BasePtr, TypeSize::Fixed(PtrOffset), DL, Flags);
20559     Align NewAlign = commonAlignment(LD->getAlign(), PtrOffset);
20560     SDValue NewLoad = DAG.getLoad(
20561         NewVT, DL, Chain, NewPtr, LD->getPointerInfo().getWithOffset(PtrOffset),
20562         NewAlign, LD->getMemOperand()->getFlags(), LD->getAAInfo());
20563     LoadOps.push_back(NewLoad);
20564     LoadOpsChain.push_back(SDValue(cast<SDNode>(NewLoad), 1));
20565   }
20566 
20567   // Process remaining bits of the load operation.
20568   // This is done by creating an UNDEF vector to match the size of the
20569   // 256-bit loads and inserting the remaining load to it. We extract the
20570   // original load type at the end using EXTRACT_SUBVECTOR instruction.
20571   unsigned BitsRemaining = MemVT.getSizeInBits() % 256;
20572   unsigned PtrOffset = (MemVT.getSizeInBits() - BitsRemaining) / 8;
20573   MVT RemainingVT = MVT::getVectorVT(
20574       MemVT.getVectorElementType().getSimpleVT(),
20575       BitsRemaining / MemVT.getVectorElementType().getSizeInBits());
20576   SDValue NewPtr =
20577       DAG.getMemBasePlusOffset(BasePtr, TypeSize::Fixed(PtrOffset), DL, Flags);
20578   Align NewAlign = commonAlignment(LD->getAlign(), PtrOffset);
20579   SDValue RemainingLoad =
20580       DAG.getLoad(RemainingVT, DL, Chain, NewPtr,
20581                   LD->getPointerInfo().getWithOffset(PtrOffset), NewAlign,
20582                   LD->getMemOperand()->getFlags(), LD->getAAInfo());
20583   SDValue UndefVector = DAG.getUNDEF(NewVT);
20584   SDValue InsertIdx = DAG.getVectorIdxConstant(0, DL);
20585   SDValue ExtendedReminingLoad =
20586       DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT,
20587                   {UndefVector, RemainingLoad, InsertIdx});
20588   LoadOps.push_back(ExtendedReminingLoad);
20589   LoadOpsChain.push_back(SDValue(cast<SDNode>(RemainingLoad), 1));
20590   EVT ConcatVT =
20591       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20592                        LoadOps.size() * NewVT.getVectorNumElements());
20593   SDValue ConcatVectors =
20594       DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, LoadOps);
20595   // Extract the original vector type size.
20596   SDValue ExtractSubVector =
20597       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MemVT,
20598                   {ConcatVectors, DAG.getVectorIdxConstant(0, DL)});
20599   SDValue TokenFactor =
20600       DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoadOpsChain);
20601   return DAG.getMergeValues({ExtractSubVector, TokenFactor}, DL);
20602 }
20603 
20604 static EVT tryGetOriginalBoolVectorType(SDValue Op, int Depth = 0) {
20605   EVT VecVT = Op.getValueType();
20606   assert(VecVT.isVector() && VecVT.getVectorElementType() == MVT::i1 &&
20607          "Need boolean vector type.");
20608 
20609   if (Depth > 3)
20610     return MVT::INVALID_SIMPLE_VALUE_TYPE;
20611 
20612   // We can get the base type from a vector compare or truncate.
20613   if (Op.getOpcode() == ISD::SETCC || Op.getOpcode() == ISD::TRUNCATE)
20614     return Op.getOperand(0).getValueType();
20615 
20616   // If an operand is a bool vector, continue looking.
20617   EVT BaseVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
20618   for (SDValue Operand : Op->op_values()) {
20619     if (Operand.getValueType() != VecVT)
20620       continue;
20621 
20622     EVT OperandVT = tryGetOriginalBoolVectorType(Operand, Depth + 1);
20623     if (!BaseVT.isSimple())
20624       BaseVT = OperandVT;
20625     else if (OperandVT != BaseVT)
20626       return MVT::INVALID_SIMPLE_VALUE_TYPE;
20627   }
20628 
20629   return BaseVT;
20630 }
20631 
20632 // When converting a <N x iX> vector to <N x i1> to store or use as a scalar
20633 // iN, we can use a trick that extracts the i^th bit from the i^th element and
20634 // then performs a vector add to get a scalar bitmask. This requires that each
20635 // element's bits are either all 1 or all 0.
20636 static SDValue vectorToScalarBitmask(SDNode *N, SelectionDAG &DAG) {
20637   SDLoc DL(N);
20638   SDValue ComparisonResult(N, 0);
20639   EVT VecVT = ComparisonResult.getValueType();
20640   assert(VecVT.isVector() && "Must be a vector type");
20641 
20642   unsigned NumElts = VecVT.getVectorNumElements();
20643   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
20644     return SDValue();
20645 
20646   if (VecVT.getVectorElementType() != MVT::i1 &&
20647       !DAG.getTargetLoweringInfo().isTypeLegal(VecVT))
20648     return SDValue();
20649 
20650   // If we can find the original types to work on instead of a vector of i1,
20651   // we can avoid extend/extract conversion instructions.
20652   if (VecVT.getVectorElementType() == MVT::i1) {
20653     VecVT = tryGetOriginalBoolVectorType(ComparisonResult);
20654     if (!VecVT.isSimple()) {
20655       unsigned BitsPerElement = std::max(64 / NumElts, 8u); // >= 64-bit vector
20656       VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement), NumElts);
20657     }
20658   }
20659   VecVT = VecVT.changeVectorElementTypeToInteger();
20660 
20661   // Large vectors don't map directly to this conversion, so to avoid too many
20662   // edge cases, we don't apply it here. The conversion will likely still be
20663   // applied later via multiple smaller vectors, whose results are concatenated.
20664   if (VecVT.getSizeInBits() > 128)
20665     return SDValue();
20666 
20667   // Ensure that all elements' bits are either 0s or 1s.
20668   ComparisonResult = DAG.getSExtOrTrunc(ComparisonResult, DL, VecVT);
20669 
20670   SmallVector<SDValue, 16> MaskConstants;
20671   if (VecVT == MVT::v16i8) {
20672     // v16i8 is a special case, as we need to split it into two halves and
20673     // combine, perform the mask+addition twice, and then combine them.
20674     for (unsigned Half = 0; Half < 2; ++Half) {
20675       for (unsigned MaskBit = 1; MaskBit <= 128; MaskBit *= 2) {
20676         MaskConstants.push_back(DAG.getConstant(MaskBit, DL, MVT::i32));
20677       }
20678     }
20679     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, MaskConstants);
20680     SDValue RepresentativeBits =
20681         DAG.getNode(ISD::AND, DL, VecVT, ComparisonResult, Mask);
20682 
20683     EVT HalfVT = VecVT.getHalfNumVectorElementsVT(*DAG.getContext());
20684     unsigned NumElementsInHalf = HalfVT.getVectorNumElements();
20685 
20686     SDValue LowHalf =
20687         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, RepresentativeBits,
20688                     DAG.getConstant(0, DL, MVT::i64));
20689     SDValue HighHalf =
20690         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, RepresentativeBits,
20691                     DAG.getConstant(NumElementsInHalf, DL, MVT::i64));
20692 
20693     SDValue ReducedLowBits =
20694         DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i16, LowHalf);
20695     SDValue ReducedHighBits =
20696         DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i16, HighHalf);
20697 
20698     SDValue ShiftedHighBits =
20699         DAG.getNode(ISD::SHL, DL, MVT::i16, ReducedHighBits,
20700                     DAG.getConstant(NumElementsInHalf, DL, MVT::i32));
20701     return DAG.getNode(ISD::OR, DL, MVT::i16, ShiftedHighBits, ReducedLowBits);
20702   }
20703 
20704   // All other vector sizes.
20705   unsigned MaxBitMask = 1u << (VecVT.getVectorNumElements() - 1);
20706   for (unsigned MaskBit = 1; MaskBit <= MaxBitMask; MaskBit *= 2) {
20707     MaskConstants.push_back(DAG.getConstant(MaskBit, DL, MVT::i64));
20708   }
20709 
20710   SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, MaskConstants);
20711   SDValue RepresentativeBits =
20712       DAG.getNode(ISD::AND, DL, VecVT, ComparisonResult, Mask);
20713   EVT ResultVT = MVT::getIntegerVT(std::max<unsigned>(
20714       NumElts, VecVT.getVectorElementType().getSizeInBits()));
20715   return DAG.getNode(ISD::VECREDUCE_ADD, DL, ResultVT, RepresentativeBits);
20716 }
20717 
20718 static SDValue combineBoolVectorAndTruncateStore(SelectionDAG &DAG,
20719                                                  StoreSDNode *Store) {
20720   if (!Store->isTruncatingStore())
20721     return SDValue();
20722 
20723   SDLoc DL(Store);
20724   SDValue VecOp = Store->getValue();
20725   EVT VT = VecOp.getValueType();
20726   EVT MemVT = Store->getMemoryVT();
20727 
20728   if (!MemVT.isVector() || !VT.isVector() ||
20729       MemVT.getVectorElementType() != MVT::i1)
20730     return SDValue();
20731 
20732   // If we are storing a vector that we are currently building, let
20733   // `scalarizeVectorStore()` handle this more efficiently.
20734   if (VecOp.getOpcode() == ISD::BUILD_VECTOR)
20735     return SDValue();
20736 
20737   VecOp = DAG.getNode(ISD::TRUNCATE, DL, MemVT, VecOp);
20738   SDValue VectorBits = vectorToScalarBitmask(VecOp.getNode(), DAG);
20739   if (!VectorBits)
20740     return SDValue();
20741 
20742   EVT StoreVT =
20743       EVT::getIntegerVT(*DAG.getContext(), MemVT.getStoreSizeInBits());
20744   SDValue ExtendedBits = DAG.getZExtOrTrunc(VectorBits, DL, StoreVT);
20745   return DAG.getStore(Store->getChain(), DL, ExtendedBits, Store->getBasePtr(),
20746                       Store->getMemOperand());
20747 }
20748 
20749 static SDValue performSTORECombine(SDNode *N,
20750                                    TargetLowering::DAGCombinerInfo &DCI,
20751                                    SelectionDAG &DAG,
20752                                    const AArch64Subtarget *Subtarget) {
20753   StoreSDNode *ST = cast<StoreSDNode>(N);
20754   SDValue Chain = ST->getChain();
20755   SDValue Value = ST->getValue();
20756   SDValue Ptr = ST->getBasePtr();
20757   EVT ValueVT = Value.getValueType();
20758 
20759   auto hasValidElementTypeForFPTruncStore = [](EVT VT) {
20760     EVT EltVT = VT.getVectorElementType();
20761     return EltVT == MVT::f32 || EltVT == MVT::f64;
20762   };
20763 
20764   // If this is an FP_ROUND followed by a store, fold this into a truncating
20765   // store. We can do this even if this is already a truncstore.
20766   // We purposefully don't care about legality of the nodes here as we know
20767   // they can be split down into something legal.
20768   if (DCI.isBeforeLegalizeOps() && Value.getOpcode() == ISD::FP_ROUND &&
20769       Value.getNode()->hasOneUse() && ST->isUnindexed() &&
20770       Subtarget->useSVEForFixedLengthVectors() &&
20771       ValueVT.isFixedLengthVector() &&
20772       ValueVT.getFixedSizeInBits() >= Subtarget->getMinSVEVectorSizeInBits() &&
20773       hasValidElementTypeForFPTruncStore(Value.getOperand(0).getValueType()))
20774     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
20775                              ST->getMemoryVT(), ST->getMemOperand());
20776 
20777   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
20778     return Split;
20779 
20780   if (Subtarget->supportsAddressTopByteIgnored() &&
20781       performTBISimplification(N->getOperand(2), DCI, DAG))
20782     return SDValue(N, 0);
20783 
20784   if (SDValue Store = foldTruncStoreOfExt(DAG, N))
20785     return Store;
20786 
20787   if (SDValue Store = combineBoolVectorAndTruncateStore(DAG, ST))
20788     return Store;
20789 
20790   return SDValue();
20791 }
20792 
20793 static SDValue performMSTORECombine(SDNode *N,
20794                                     TargetLowering::DAGCombinerInfo &DCI,
20795                                     SelectionDAG &DAG,
20796                                     const AArch64Subtarget *Subtarget) {
20797   MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
20798   SDValue Value = MST->getValue();
20799   SDValue Mask = MST->getMask();
20800   SDLoc DL(N);
20801 
20802   // If this is a UZP1 followed by a masked store, fold this into a masked
20803   // truncating store.  We can do this even if this is already a masked
20804   // truncstore.
20805   if (Value.getOpcode() == AArch64ISD::UZP1 && Value->hasOneUse() &&
20806       MST->isUnindexed() && Mask->getOpcode() == AArch64ISD::PTRUE &&
20807       Value.getValueType().isInteger()) {
20808     Value = Value.getOperand(0);
20809     if (Value.getOpcode() == ISD::BITCAST) {
20810       EVT HalfVT =
20811           Value.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
20812       EVT InVT = Value.getOperand(0).getValueType();
20813 
20814       if (HalfVT.widenIntegerVectorElementType(*DAG.getContext()) == InVT) {
20815         unsigned MinSVESize = Subtarget->getMinSVEVectorSizeInBits();
20816         unsigned PgPattern = Mask->getConstantOperandVal(0);
20817 
20818         // Ensure we can double the size of the predicate pattern
20819         unsigned NumElts = getNumElementsFromSVEPredPattern(PgPattern);
20820         if (NumElts && NumElts * InVT.getVectorElementType().getSizeInBits() <=
20821                            MinSVESize) {
20822           Mask = getPTrue(DAG, DL, InVT.changeVectorElementType(MVT::i1),
20823                           PgPattern);
20824           return DAG.getMaskedStore(MST->getChain(), DL, Value.getOperand(0),
20825                                     MST->getBasePtr(), MST->getOffset(), Mask,
20826                                     MST->getMemoryVT(), MST->getMemOperand(),
20827                                     MST->getAddressingMode(),
20828                                     /*IsTruncating=*/true);
20829         }
20830       }
20831     }
20832   }
20833 
20834   return SDValue();
20835 }
20836 
20837 /// \return true if part of the index was folded into the Base.
20838 static bool foldIndexIntoBase(SDValue &BasePtr, SDValue &Index, SDValue Scale,
20839                               SDLoc DL, SelectionDAG &DAG) {
20840   // This function assumes a vector of i64 indices.
20841   EVT IndexVT = Index.getValueType();
20842   if (!IndexVT.isVector() || IndexVT.getVectorElementType() != MVT::i64)
20843     return false;
20844 
20845   // Simplify:
20846   //   BasePtr = Ptr
20847   //   Index = X + splat(Offset)
20848   // ->
20849   //   BasePtr = Ptr + Offset * scale.
20850   //   Index = X
20851   if (Index.getOpcode() == ISD::ADD) {
20852     if (auto Offset = DAG.getSplatValue(Index.getOperand(1))) {
20853       Offset = DAG.getNode(ISD::MUL, DL, MVT::i64, Offset, Scale);
20854       BasePtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, Offset);
20855       Index = Index.getOperand(0);
20856       return true;
20857     }
20858   }
20859 
20860   // Simplify:
20861   //   BasePtr = Ptr
20862   //   Index = (X + splat(Offset)) << splat(Shift)
20863   // ->
20864   //   BasePtr = Ptr + (Offset << Shift) * scale)
20865   //   Index = X << splat(shift)
20866   if (Index.getOpcode() == ISD::SHL &&
20867       Index.getOperand(0).getOpcode() == ISD::ADD) {
20868     SDValue Add = Index.getOperand(0);
20869     SDValue ShiftOp = Index.getOperand(1);
20870     SDValue OffsetOp = Add.getOperand(1);
20871     if (auto Shift = DAG.getSplatValue(ShiftOp))
20872       if (auto Offset = DAG.getSplatValue(OffsetOp)) {
20873         Offset = DAG.getNode(ISD::SHL, DL, MVT::i64, Offset, Shift);
20874         Offset = DAG.getNode(ISD::MUL, DL, MVT::i64, Offset, Scale);
20875         BasePtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, Offset);
20876         Index = DAG.getNode(ISD::SHL, DL, Index.getValueType(),
20877                             Add.getOperand(0), ShiftOp);
20878         return true;
20879       }
20880   }
20881 
20882   return false;
20883 }
20884 
20885 // Analyse the specified address returning true if a more optimal addressing
20886 // mode is available. When returning true all parameters are updated to reflect
20887 // their recommended values.
20888 static bool findMoreOptimalIndexType(const MaskedGatherScatterSDNode *N,
20889                                      SDValue &BasePtr, SDValue &Index,
20890                                      SelectionDAG &DAG) {
20891   // Try to iteratively fold parts of the index into the base pointer to
20892   // simplify the index as much as possible.
20893   bool Changed = false;
20894   while (foldIndexIntoBase(BasePtr, Index, N->getScale(), SDLoc(N), DAG))
20895     Changed = true;
20896 
20897   // Only consider element types that are pointer sized as smaller types can
20898   // be easily promoted.
20899   EVT IndexVT = Index.getValueType();
20900   if (IndexVT.getVectorElementType() != MVT::i64 || IndexVT == MVT::nxv2i64)
20901     return Changed;
20902 
20903   // Can indices be trivially shrunk?
20904   EVT DataVT = N->getOperand(1).getValueType();
20905   // Don't attempt to shrink the index for fixed vectors of 64 bit data since it
20906   // will later be re-extended to 64 bits in legalization
20907   if (DataVT.isFixedLengthVector() && DataVT.getScalarSizeInBits() == 64)
20908     return Changed;
20909   if (ISD::isVectorShrinkable(Index.getNode(), 32, N->isIndexSigned())) {
20910     EVT NewIndexVT = IndexVT.changeVectorElementType(MVT::i32);
20911     Index = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NewIndexVT, Index);
20912     return true;
20913   }
20914 
20915   // Match:
20916   //   Index = step(const)
20917   int64_t Stride = 0;
20918   if (Index.getOpcode() == ISD::STEP_VECTOR) {
20919     Stride = cast<ConstantSDNode>(Index.getOperand(0))->getSExtValue();
20920   }
20921   // Match:
20922   //   Index = step(const) << shift(const)
20923   else if (Index.getOpcode() == ISD::SHL &&
20924            Index.getOperand(0).getOpcode() == ISD::STEP_VECTOR) {
20925     SDValue RHS = Index.getOperand(1);
20926     if (auto *Shift =
20927             dyn_cast_or_null<ConstantSDNode>(DAG.getSplatValue(RHS))) {
20928       int64_t Step = (int64_t)Index.getOperand(0).getConstantOperandVal(1);
20929       Stride = Step << Shift->getZExtValue();
20930     }
20931   }
20932 
20933   // Return early because no supported pattern is found.
20934   if (Stride == 0)
20935     return Changed;
20936 
20937   if (Stride < std::numeric_limits<int32_t>::min() ||
20938       Stride > std::numeric_limits<int32_t>::max())
20939     return Changed;
20940 
20941   const auto &Subtarget = DAG.getSubtarget<AArch64Subtarget>();
20942   unsigned MaxVScale =
20943       Subtarget.getMaxSVEVectorSizeInBits() / AArch64::SVEBitsPerBlock;
20944   int64_t LastElementOffset =
20945       IndexVT.getVectorMinNumElements() * Stride * MaxVScale;
20946 
20947   if (LastElementOffset < std::numeric_limits<int32_t>::min() ||
20948       LastElementOffset > std::numeric_limits<int32_t>::max())
20949     return Changed;
20950 
20951   EVT NewIndexVT = IndexVT.changeVectorElementType(MVT::i32);
20952   // Stride does not scale explicitly by 'Scale', because it happens in
20953   // the gather/scatter addressing mode.
20954   Index = DAG.getStepVector(SDLoc(N), NewIndexVT, APInt(32, Stride));
20955   return true;
20956 }
20957 
20958 static SDValue performMaskedGatherScatterCombine(
20959     SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) {
20960   MaskedGatherScatterSDNode *MGS = cast<MaskedGatherScatterSDNode>(N);
20961   assert(MGS && "Can only combine gather load or scatter store nodes");
20962 
20963   if (!DCI.isBeforeLegalize())
20964     return SDValue();
20965 
20966   SDLoc DL(MGS);
20967   SDValue Chain = MGS->getChain();
20968   SDValue Scale = MGS->getScale();
20969   SDValue Index = MGS->getIndex();
20970   SDValue Mask = MGS->getMask();
20971   SDValue BasePtr = MGS->getBasePtr();
20972   ISD::MemIndexType IndexType = MGS->getIndexType();
20973 
20974   if (!findMoreOptimalIndexType(MGS, BasePtr, Index, DAG))
20975     return SDValue();
20976 
20977   // Here we catch such cases early and change MGATHER's IndexType to allow
20978   // the use of an Index that's more legalisation friendly.
20979   if (auto *MGT = dyn_cast<MaskedGatherSDNode>(MGS)) {
20980     SDValue PassThru = MGT->getPassThru();
20981     SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
20982     return DAG.getMaskedGather(
20983         DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
20984         Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
20985   }
20986   auto *MSC = cast<MaskedScatterSDNode>(MGS);
20987   SDValue Data = MSC->getValue();
20988   SDValue Ops[] = {Chain, Data, Mask, BasePtr, Index, Scale};
20989   return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(), DL,
20990                               Ops, MSC->getMemOperand(), IndexType,
20991                               MSC->isTruncatingStore());
20992 }
20993 
20994 /// Target-specific DAG combine function for NEON load/store intrinsics
20995 /// to merge base address updates.
20996 static SDValue performNEONPostLDSTCombine(SDNode *N,
20997                                           TargetLowering::DAGCombinerInfo &DCI,
20998                                           SelectionDAG &DAG) {
20999   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21000     return SDValue();
21001 
21002   unsigned AddrOpIdx = N->getNumOperands() - 1;
21003   SDValue Addr = N->getOperand(AddrOpIdx);
21004 
21005   // Search for a use of the address operand that is an increment.
21006   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
21007        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
21008     SDNode *User = *UI;
21009     if (User->getOpcode() != ISD::ADD ||
21010         UI.getUse().getResNo() != Addr.getResNo())
21011       continue;
21012 
21013     // Check that the add is independent of the load/store.  Otherwise, folding
21014     // it would create a cycle.
21015     SmallPtrSet<const SDNode *, 32> Visited;
21016     SmallVector<const SDNode *, 16> Worklist;
21017     Visited.insert(Addr.getNode());
21018     Worklist.push_back(N);
21019     Worklist.push_back(User);
21020     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
21021         SDNode::hasPredecessorHelper(User, Visited, Worklist))
21022       continue;
21023 
21024     // Find the new opcode for the updating load/store.
21025     bool IsStore = false;
21026     bool IsLaneOp = false;
21027     bool IsDupOp = false;
21028     unsigned NewOpc = 0;
21029     unsigned NumVecs = 0;
21030     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21031     switch (IntNo) {
21032     default: llvm_unreachable("unexpected intrinsic for Neon base update");
21033     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
21034       NumVecs = 2; break;
21035     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
21036       NumVecs = 3; break;
21037     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
21038       NumVecs = 4; break;
21039     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
21040       NumVecs = 2; IsStore = true; break;
21041     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
21042       NumVecs = 3; IsStore = true; break;
21043     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
21044       NumVecs = 4; IsStore = true; break;
21045     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
21046       NumVecs = 2; break;
21047     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
21048       NumVecs = 3; break;
21049     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
21050       NumVecs = 4; break;
21051     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
21052       NumVecs = 2; IsStore = true; break;
21053     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
21054       NumVecs = 3; IsStore = true; break;
21055     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
21056       NumVecs = 4; IsStore = true; break;
21057     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
21058       NumVecs = 2; IsDupOp = true; break;
21059     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
21060       NumVecs = 3; IsDupOp = true; break;
21061     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
21062       NumVecs = 4; IsDupOp = true; break;
21063     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
21064       NumVecs = 2; IsLaneOp = true; break;
21065     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
21066       NumVecs = 3; IsLaneOp = true; break;
21067     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
21068       NumVecs = 4; IsLaneOp = true; break;
21069     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
21070       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
21071     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
21072       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
21073     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
21074       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
21075     }
21076 
21077     EVT VecTy;
21078     if (IsStore)
21079       VecTy = N->getOperand(2).getValueType();
21080     else
21081       VecTy = N->getValueType(0);
21082 
21083     // If the increment is a constant, it must match the memory ref size.
21084     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
21085     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
21086       uint32_t IncVal = CInc->getZExtValue();
21087       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
21088       if (IsLaneOp || IsDupOp)
21089         NumBytes /= VecTy.getVectorNumElements();
21090       if (IncVal != NumBytes)
21091         continue;
21092       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
21093     }
21094     SmallVector<SDValue, 8> Ops;
21095     Ops.push_back(N->getOperand(0)); // Incoming chain
21096     // Load lane and store have vector list as input.
21097     if (IsLaneOp || IsStore)
21098       for (unsigned i = 2; i < AddrOpIdx; ++i)
21099         Ops.push_back(N->getOperand(i));
21100     Ops.push_back(Addr); // Base register
21101     Ops.push_back(Inc);
21102 
21103     // Return Types.
21104     EVT Tys[6];
21105     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
21106     unsigned n;
21107     for (n = 0; n < NumResultVecs; ++n)
21108       Tys[n] = VecTy;
21109     Tys[n++] = MVT::i64;  // Type of write back register
21110     Tys[n] = MVT::Other;  // Type of the chain
21111     SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
21112 
21113     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
21114     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
21115                                            MemInt->getMemoryVT(),
21116                                            MemInt->getMemOperand());
21117 
21118     // Update the uses.
21119     std::vector<SDValue> NewResults;
21120     for (unsigned i = 0; i < NumResultVecs; ++i) {
21121       NewResults.push_back(SDValue(UpdN.getNode(), i));
21122     }
21123     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
21124     DCI.CombineTo(N, NewResults);
21125     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
21126 
21127     break;
21128   }
21129   return SDValue();
21130 }
21131 
21132 // Checks to see if the value is the prescribed width and returns information
21133 // about its extension mode.
21134 static
21135 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
21136   ExtType = ISD::NON_EXTLOAD;
21137   switch(V.getNode()->getOpcode()) {
21138   default:
21139     return false;
21140   case ISD::LOAD: {
21141     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
21142     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
21143        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
21144       ExtType = LoadNode->getExtensionType();
21145       return true;
21146     }
21147     return false;
21148   }
21149   case ISD::AssertSext: {
21150     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
21151     if ((TypeNode->getVT() == MVT::i8 && width == 8)
21152        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
21153       ExtType = ISD::SEXTLOAD;
21154       return true;
21155     }
21156     return false;
21157   }
21158   case ISD::AssertZext: {
21159     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
21160     if ((TypeNode->getVT() == MVT::i8 && width == 8)
21161        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
21162       ExtType = ISD::ZEXTLOAD;
21163       return true;
21164     }
21165     return false;
21166   }
21167   case ISD::Constant:
21168   case ISD::TargetConstant: {
21169     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
21170            1LL << (width - 1);
21171   }
21172   }
21173 
21174   return true;
21175 }
21176 
21177 // This function does a whole lot of voodoo to determine if the tests are
21178 // equivalent without and with a mask. Essentially what happens is that given a
21179 // DAG resembling:
21180 //
21181 //  +-------------+ +-------------+ +-------------+ +-------------+
21182 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
21183 //  +-------------+ +-------------+ +-------------+ +-------------+
21184 //           |           |           |               |
21185 //           V           V           |    +----------+
21186 //          +-------------+  +----+  |    |
21187 //          |     ADD     |  |0xff|  |    |
21188 //          +-------------+  +----+  |    |
21189 //                  |           |    |    |
21190 //                  V           V    |    |
21191 //                 +-------------+   |    |
21192 //                 |     AND     |   |    |
21193 //                 +-------------+   |    |
21194 //                      |            |    |
21195 //                      +-----+      |    |
21196 //                            |      |    |
21197 //                            V      V    V
21198 //                           +-------------+
21199 //                           |     CMP     |
21200 //                           +-------------+
21201 //
21202 // The AND node may be safely removed for some combinations of inputs. In
21203 // particular we need to take into account the extension type of the Input,
21204 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
21205 // width of the input (this can work for any width inputs, the above graph is
21206 // specific to 8 bits.
21207 //
21208 // The specific equations were worked out by generating output tables for each
21209 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
21210 // problem was simplified by working with 4 bit inputs, which means we only
21211 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
21212 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
21213 // patterns present in both extensions (0,7). For every distinct set of
21214 // AddConstant and CompConstants bit patterns we can consider the masked and
21215 // unmasked versions to be equivalent if the result of this function is true for
21216 // all 16 distinct bit patterns of for the current extension type of Input (w0).
21217 //
21218 //   sub      w8, w0, w1
21219 //   and      w10, w8, #0x0f
21220 //   cmp      w8, w2
21221 //   cset     w9, AArch64CC
21222 //   cmp      w10, w2
21223 //   cset     w11, AArch64CC
21224 //   cmp      w9, w11
21225 //   cset     w0, eq
21226 //   ret
21227 //
21228 // Since the above function shows when the outputs are equivalent it defines
21229 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
21230 // would be expensive to run during compiles. The equations below were written
21231 // in a test harness that confirmed they gave equivalent outputs to the above
21232 // for all inputs function, so they can be used determine if the removal is
21233 // legal instead.
21234 //
21235 // isEquivalentMaskless() is the code for testing if the AND can be removed
21236 // factored out of the DAG recognition as the DAG can take several forms.
21237 
21238 static bool isEquivalentMaskless(unsigned CC, unsigned width,
21239                                  ISD::LoadExtType ExtType, int AddConstant,
21240                                  int CompConstant) {
21241   // By being careful about our equations and only writing the in term
21242   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
21243   // make them generally applicable to all bit widths.
21244   int MaxUInt = (1 << width);
21245 
21246   // For the purposes of these comparisons sign extending the type is
21247   // equivalent to zero extending the add and displacing it by half the integer
21248   // width. Provided we are careful and make sure our equations are valid over
21249   // the whole range we can just adjust the input and avoid writing equations
21250   // for sign extended inputs.
21251   if (ExtType == ISD::SEXTLOAD)
21252     AddConstant -= (1 << (width-1));
21253 
21254   switch(CC) {
21255   case AArch64CC::LE:
21256   case AArch64CC::GT:
21257     if ((AddConstant == 0) ||
21258         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
21259         (AddConstant >= 0 && CompConstant < 0) ||
21260         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
21261       return true;
21262     break;
21263   case AArch64CC::LT:
21264   case AArch64CC::GE:
21265     if ((AddConstant == 0) ||
21266         (AddConstant >= 0 && CompConstant <= 0) ||
21267         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
21268       return true;
21269     break;
21270   case AArch64CC::HI:
21271   case AArch64CC::LS:
21272     if ((AddConstant >= 0 && CompConstant < 0) ||
21273        (AddConstant <= 0 && CompConstant >= -1 &&
21274         CompConstant < AddConstant + MaxUInt))
21275       return true;
21276    break;
21277   case AArch64CC::PL:
21278   case AArch64CC::MI:
21279     if ((AddConstant == 0) ||
21280         (AddConstant > 0 && CompConstant <= 0) ||
21281         (AddConstant < 0 && CompConstant <= AddConstant))
21282       return true;
21283     break;
21284   case AArch64CC::LO:
21285   case AArch64CC::HS:
21286     if ((AddConstant >= 0 && CompConstant <= 0) ||
21287         (AddConstant <= 0 && CompConstant >= 0 &&
21288          CompConstant <= AddConstant + MaxUInt))
21289       return true;
21290     break;
21291   case AArch64CC::EQ:
21292   case AArch64CC::NE:
21293     if ((AddConstant > 0 && CompConstant < 0) ||
21294         (AddConstant < 0 && CompConstant >= 0 &&
21295          CompConstant < AddConstant + MaxUInt) ||
21296         (AddConstant >= 0 && CompConstant >= 0 &&
21297          CompConstant >= AddConstant) ||
21298         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
21299       return true;
21300     break;
21301   case AArch64CC::VS:
21302   case AArch64CC::VC:
21303   case AArch64CC::AL:
21304   case AArch64CC::NV:
21305     return true;
21306   case AArch64CC::Invalid:
21307     break;
21308   }
21309 
21310   return false;
21311 }
21312 
21313 // (X & C) >u Mask --> (X & (C & (~Mask)) != 0
21314 // (X & C) <u Pow2 --> (X & (C & ~(Pow2-1)) == 0
21315 static SDValue performSubsToAndsCombine(SDNode *N, SDNode *SubsNode,
21316                                         SDNode *AndNode, SelectionDAG &DAG,
21317                                         unsigned CCIndex, unsigned CmpIndex,
21318                                         unsigned CC) {
21319   ConstantSDNode *SubsC = dyn_cast<ConstantSDNode>(SubsNode->getOperand(1));
21320   if (!SubsC)
21321     return SDValue();
21322 
21323   APInt SubsAP = SubsC->getAPIntValue();
21324   if (CC == AArch64CC::HI) {
21325     if (!SubsAP.isMask())
21326       return SDValue();
21327   } else if (CC == AArch64CC::LO) {
21328     if (!SubsAP.isPowerOf2())
21329       return SDValue();
21330   } else
21331     return SDValue();
21332 
21333   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(AndNode->getOperand(1));
21334   if (!AndC)
21335     return SDValue();
21336 
21337   APInt MaskAP = CC == AArch64CC::HI ? SubsAP : (SubsAP - 1);
21338 
21339   SDLoc DL(N);
21340   APInt AndSMask = (~MaskAP) & AndC->getAPIntValue();
21341   SDValue ANDS = DAG.getNode(
21342       AArch64ISD::ANDS, DL, SubsNode->getVTList(), AndNode->getOperand(0),
21343       DAG.getConstant(AndSMask, DL, SubsC->getValueType(0)));
21344   SDValue AArch64_CC =
21345       DAG.getConstant(CC == AArch64CC::HI ? AArch64CC::NE : AArch64CC::EQ, DL,
21346                       N->getOperand(CCIndex)->getValueType(0));
21347 
21348   // For now, only performCSELCombine and performBRCONDCombine call this
21349   // function. And both of them pass 2 for CCIndex, 3 for CmpIndex with 4
21350   // operands. So just init the ops direct to simplify the code. If we have some
21351   // other case with different CCIndex, CmpIndex, we need to use for loop to
21352   // rewrite the code here.
21353   // TODO: Do we need to assert number of operand is 4 here?
21354   assert((CCIndex == 2 && CmpIndex == 3) &&
21355          "Expected CCIndex to be 2 and CmpIndex to be 3.");
21356   SDValue Ops[] = {N->getOperand(0), N->getOperand(1), AArch64_CC,
21357                    ANDS.getValue(1)};
21358   return DAG.getNode(N->getOpcode(), N, N->getVTList(), Ops);
21359 }
21360 
21361 static
21362 SDValue performCONDCombine(SDNode *N,
21363                            TargetLowering::DAGCombinerInfo &DCI,
21364                            SelectionDAG &DAG, unsigned CCIndex,
21365                            unsigned CmpIndex) {
21366   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
21367   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
21368   unsigned CondOpcode = SubsNode->getOpcode();
21369 
21370   if (CondOpcode != AArch64ISD::SUBS || SubsNode->hasAnyUseOfValue(0))
21371     return SDValue();
21372 
21373   // There is a SUBS feeding this condition. Is it fed by a mask we can
21374   // use?
21375 
21376   SDNode *AndNode = SubsNode->getOperand(0).getNode();
21377   unsigned MaskBits = 0;
21378 
21379   if (AndNode->getOpcode() != ISD::AND)
21380     return SDValue();
21381 
21382   if (SDValue Val = performSubsToAndsCombine(N, SubsNode, AndNode, DAG, CCIndex,
21383                                              CmpIndex, CC))
21384     return Val;
21385 
21386   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
21387     uint32_t CNV = CN->getZExtValue();
21388     if (CNV == 255)
21389       MaskBits = 8;
21390     else if (CNV == 65535)
21391       MaskBits = 16;
21392   }
21393 
21394   if (!MaskBits)
21395     return SDValue();
21396 
21397   SDValue AddValue = AndNode->getOperand(0);
21398 
21399   if (AddValue.getOpcode() != ISD::ADD)
21400     return SDValue();
21401 
21402   // The basic dag structure is correct, grab the inputs and validate them.
21403 
21404   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
21405   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
21406   SDValue SubsInputValue = SubsNode->getOperand(1);
21407 
21408   // The mask is present and the provenance of all the values is a smaller type,
21409   // lets see if the mask is superfluous.
21410 
21411   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
21412       !isa<ConstantSDNode>(SubsInputValue.getNode()))
21413     return SDValue();
21414 
21415   ISD::LoadExtType ExtType;
21416 
21417   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
21418       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
21419       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
21420     return SDValue();
21421 
21422   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
21423                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
21424                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
21425     return SDValue();
21426 
21427   // The AND is not necessary, remove it.
21428 
21429   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
21430                                SubsNode->getValueType(1));
21431   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
21432 
21433   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
21434   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
21435 
21436   return SDValue(N, 0);
21437 }
21438 
21439 // Optimize compare with zero and branch.
21440 static SDValue performBRCONDCombine(SDNode *N,
21441                                     TargetLowering::DAGCombinerInfo &DCI,
21442                                     SelectionDAG &DAG) {
21443   MachineFunction &MF = DAG.getMachineFunction();
21444   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
21445   // will not be produced, as they are conditional branch instructions that do
21446   // not set flags.
21447   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
21448     return SDValue();
21449 
21450   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
21451     N = NV.getNode();
21452   SDValue Chain = N->getOperand(0);
21453   SDValue Dest = N->getOperand(1);
21454   SDValue CCVal = N->getOperand(2);
21455   SDValue Cmp = N->getOperand(3);
21456 
21457   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
21458   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
21459   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
21460     return SDValue();
21461 
21462   unsigned CmpOpc = Cmp.getOpcode();
21463   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
21464     return SDValue();
21465 
21466   // Only attempt folding if there is only one use of the flag and no use of the
21467   // value.
21468   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
21469     return SDValue();
21470 
21471   SDValue LHS = Cmp.getOperand(0);
21472   SDValue RHS = Cmp.getOperand(1);
21473 
21474   assert(LHS.getValueType() == RHS.getValueType() &&
21475          "Expected the value type to be the same for both operands!");
21476   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
21477     return SDValue();
21478 
21479   if (isNullConstant(LHS))
21480     std::swap(LHS, RHS);
21481 
21482   if (!isNullConstant(RHS))
21483     return SDValue();
21484 
21485   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
21486       LHS.getOpcode() == ISD::SRL)
21487     return SDValue();
21488 
21489   // Fold the compare into the branch instruction.
21490   SDValue BR;
21491   if (CC == AArch64CC::EQ)
21492     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
21493   else
21494     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
21495 
21496   // Do not add new nodes to DAG combiner worklist.
21497   DCI.CombineTo(N, BR, false);
21498 
21499   return SDValue();
21500 }
21501 
21502 static SDValue foldCSELofCTTZ(SDNode *N, SelectionDAG &DAG) {
21503   unsigned CC = N->getConstantOperandVal(2);
21504   SDValue SUBS = N->getOperand(3);
21505   SDValue Zero, CTTZ;
21506 
21507   if (CC == AArch64CC::EQ && SUBS.getOpcode() == AArch64ISD::SUBS) {
21508     Zero = N->getOperand(0);
21509     CTTZ = N->getOperand(1);
21510   } else if (CC == AArch64CC::NE && SUBS.getOpcode() == AArch64ISD::SUBS) {
21511     Zero = N->getOperand(1);
21512     CTTZ = N->getOperand(0);
21513   } else
21514     return SDValue();
21515 
21516   if ((CTTZ.getOpcode() != ISD::CTTZ && CTTZ.getOpcode() != ISD::TRUNCATE) ||
21517       (CTTZ.getOpcode() == ISD::TRUNCATE &&
21518        CTTZ.getOperand(0).getOpcode() != ISD::CTTZ))
21519     return SDValue();
21520 
21521   assert((CTTZ.getValueType() == MVT::i32 || CTTZ.getValueType() == MVT::i64) &&
21522          "Illegal type in CTTZ folding");
21523 
21524   if (!isNullConstant(Zero) || !isNullConstant(SUBS.getOperand(1)))
21525     return SDValue();
21526 
21527   SDValue X = CTTZ.getOpcode() == ISD::TRUNCATE
21528                   ? CTTZ.getOperand(0).getOperand(0)
21529                   : CTTZ.getOperand(0);
21530 
21531   if (X != SUBS.getOperand(0))
21532     return SDValue();
21533 
21534   unsigned BitWidth = CTTZ.getOpcode() == ISD::TRUNCATE
21535                           ? CTTZ.getOperand(0).getValueSizeInBits()
21536                           : CTTZ.getValueSizeInBits();
21537   SDValue BitWidthMinusOne =
21538       DAG.getConstant(BitWidth - 1, SDLoc(N), CTTZ.getValueType());
21539   return DAG.getNode(ISD::AND, SDLoc(N), CTTZ.getValueType(), CTTZ,
21540                      BitWidthMinusOne);
21541 }
21542 
21543 // (CSEL l r EQ (CMP (CSEL x y cc2 cond) x)) => (CSEL l r cc2 cond)
21544 // (CSEL l r EQ (CMP (CSEL x y cc2 cond) y)) => (CSEL l r !cc2 cond)
21545 // Where x and y are constants and x != y
21546 
21547 // (CSEL l r NE (CMP (CSEL x y cc2 cond) x)) => (CSEL l r !cc2 cond)
21548 // (CSEL l r NE (CMP (CSEL x y cc2 cond) y)) => (CSEL l r cc2 cond)
21549 // Where x and y are constants and x != y
21550 static SDValue foldCSELOfCSEL(SDNode *Op, SelectionDAG &DAG) {
21551   SDValue L = Op->getOperand(0);
21552   SDValue R = Op->getOperand(1);
21553   AArch64CC::CondCode OpCC =
21554       static_cast<AArch64CC::CondCode>(Op->getConstantOperandVal(2));
21555 
21556   SDValue OpCmp = Op->getOperand(3);
21557   if (!isCMP(OpCmp))
21558     return SDValue();
21559 
21560   SDValue CmpLHS = OpCmp.getOperand(0);
21561   SDValue CmpRHS = OpCmp.getOperand(1);
21562 
21563   if (CmpRHS.getOpcode() == AArch64ISD::CSEL)
21564     std::swap(CmpLHS, CmpRHS);
21565   else if (CmpLHS.getOpcode() != AArch64ISD::CSEL)
21566     return SDValue();
21567 
21568   SDValue X = CmpLHS->getOperand(0);
21569   SDValue Y = CmpLHS->getOperand(1);
21570   if (!isa<ConstantSDNode>(X) || !isa<ConstantSDNode>(Y) || X == Y) {
21571     return SDValue();
21572   }
21573 
21574   // If one of the constant is opaque constant, x,y sdnode is still different
21575   // but the real value maybe the same. So check APInt here to make sure the
21576   // code is correct.
21577   ConstantSDNode *CX = cast<ConstantSDNode>(X);
21578   ConstantSDNode *CY = cast<ConstantSDNode>(Y);
21579   if (CX->getAPIntValue() == CY->getAPIntValue())
21580     return SDValue();
21581 
21582   AArch64CC::CondCode CC =
21583       static_cast<AArch64CC::CondCode>(CmpLHS->getConstantOperandVal(2));
21584   SDValue Cond = CmpLHS->getOperand(3);
21585 
21586   if (CmpRHS == Y)
21587     CC = AArch64CC::getInvertedCondCode(CC);
21588   else if (CmpRHS != X)
21589     return SDValue();
21590 
21591   if (OpCC == AArch64CC::NE)
21592     CC = AArch64CC::getInvertedCondCode(CC);
21593   else if (OpCC != AArch64CC::EQ)
21594     return SDValue();
21595 
21596   SDLoc DL(Op);
21597   EVT VT = Op->getValueType(0);
21598 
21599   SDValue CCValue = DAG.getConstant(CC, DL, MVT::i32);
21600   return DAG.getNode(AArch64ISD::CSEL, DL, VT, L, R, CCValue, Cond);
21601 }
21602 
21603 // Optimize CSEL instructions
21604 static SDValue performCSELCombine(SDNode *N,
21605                                   TargetLowering::DAGCombinerInfo &DCI,
21606                                   SelectionDAG &DAG) {
21607   // CSEL x, x, cc -> x
21608   if (N->getOperand(0) == N->getOperand(1))
21609     return N->getOperand(0);
21610 
21611   if (SDValue R = foldCSELOfCSEL(N, DAG))
21612     return R;
21613 
21614   // CSEL 0, cttz(X), eq(X, 0) -> AND cttz bitwidth-1
21615   // CSEL cttz(X), 0, ne(X, 0) -> AND cttz bitwidth-1
21616   if (SDValue Folded = foldCSELofCTTZ(N, DAG))
21617 		return Folded;
21618 
21619   return performCONDCombine(N, DCI, DAG, 2, 3);
21620 }
21621 
21622 // Try to re-use an already extended operand of a vector SetCC feeding a
21623 // extended select. Doing so avoids requiring another full extension of the
21624 // SET_CC result when lowering the select.
21625 static SDValue tryToWidenSetCCOperands(SDNode *Op, SelectionDAG &DAG) {
21626   EVT Op0MVT = Op->getOperand(0).getValueType();
21627   if (!Op0MVT.isVector() || Op->use_empty())
21628     return SDValue();
21629 
21630   // Make sure that all uses of Op are VSELECTs with result matching types where
21631   // the result type has a larger element type than the SetCC operand.
21632   SDNode *FirstUse = *Op->use_begin();
21633   if (FirstUse->getOpcode() != ISD::VSELECT)
21634     return SDValue();
21635   EVT UseMVT = FirstUse->getValueType(0);
21636   if (UseMVT.getScalarSizeInBits() <= Op0MVT.getScalarSizeInBits())
21637     return SDValue();
21638   if (any_of(Op->uses(), [&UseMVT](const SDNode *N) {
21639         return N->getOpcode() != ISD::VSELECT || N->getValueType(0) != UseMVT;
21640       }))
21641     return SDValue();
21642 
21643   APInt V;
21644   if (!ISD::isConstantSplatVector(Op->getOperand(1).getNode(), V))
21645     return SDValue();
21646 
21647   SDLoc DL(Op);
21648   SDValue Op0ExtV;
21649   SDValue Op1ExtV;
21650   ISD::CondCode CC = cast<CondCodeSDNode>(Op->getOperand(2))->get();
21651   // Check if the first operand of the SET_CC is already extended. If it is,
21652   // split the SET_CC and re-use the extended version of the operand.
21653   SDNode *Op0SExt = DAG.getNodeIfExists(ISD::SIGN_EXTEND, DAG.getVTList(UseMVT),
21654                                         Op->getOperand(0));
21655   SDNode *Op0ZExt = DAG.getNodeIfExists(ISD::ZERO_EXTEND, DAG.getVTList(UseMVT),
21656                                         Op->getOperand(0));
21657   if (Op0SExt && (isSignedIntSetCC(CC) || isIntEqualitySetCC(CC))) {
21658     Op0ExtV = SDValue(Op0SExt, 0);
21659     Op1ExtV = DAG.getNode(ISD::SIGN_EXTEND, DL, UseMVT, Op->getOperand(1));
21660   } else if (Op0ZExt && (isUnsignedIntSetCC(CC) || isIntEqualitySetCC(CC))) {
21661     Op0ExtV = SDValue(Op0ZExt, 0);
21662     Op1ExtV = DAG.getNode(ISD::ZERO_EXTEND, DL, UseMVT, Op->getOperand(1));
21663   } else
21664     return SDValue();
21665 
21666   return DAG.getNode(ISD::SETCC, DL, UseMVT.changeVectorElementType(MVT::i1),
21667                      Op0ExtV, Op1ExtV, Op->getOperand(2));
21668 }
21669 
21670 static SDValue
21671 performVecReduceBitwiseCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
21672                                SelectionDAG &DAG) {
21673   SDValue Vec = N->getOperand(0);
21674   if (DCI.isBeforeLegalize() &&
21675       Vec.getValueType().getVectorElementType() == MVT::i1 &&
21676       Vec.getValueType().isFixedLengthVector() &&
21677       Vec.getValueType().isPow2VectorType()) {
21678     SDLoc DL(N);
21679     return getVectorBitwiseReduce(N->getOpcode(), Vec, N->getValueType(0), DL,
21680                                   DAG);
21681   }
21682 
21683   return SDValue();
21684 }
21685 
21686 static SDValue performSETCCCombine(SDNode *N,
21687                                    TargetLowering::DAGCombinerInfo &DCI,
21688                                    SelectionDAG &DAG) {
21689   assert(N->getOpcode() == ISD::SETCC && "Unexpected opcode!");
21690   SDValue LHS = N->getOperand(0);
21691   SDValue RHS = N->getOperand(1);
21692   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
21693   SDLoc DL(N);
21694   EVT VT = N->getValueType(0);
21695 
21696   if (SDValue V = tryToWidenSetCCOperands(N, DAG))
21697     return V;
21698 
21699   // setcc (csel 0, 1, cond, X), 1, ne ==> csel 0, 1, !cond, X
21700   if (Cond == ISD::SETNE && isOneConstant(RHS) &&
21701       LHS->getOpcode() == AArch64ISD::CSEL &&
21702       isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
21703       LHS->hasOneUse()) {
21704     // Invert CSEL's condition.
21705     auto *OpCC = cast<ConstantSDNode>(LHS.getOperand(2));
21706     auto OldCond = static_cast<AArch64CC::CondCode>(OpCC->getZExtValue());
21707     auto NewCond = getInvertedCondCode(OldCond);
21708 
21709     // csel 0, 1, !cond, X
21710     SDValue CSEL =
21711         DAG.getNode(AArch64ISD::CSEL, DL, LHS.getValueType(), LHS.getOperand(0),
21712                     LHS.getOperand(1), DAG.getConstant(NewCond, DL, MVT::i32),
21713                     LHS.getOperand(3));
21714     return DAG.getZExtOrTrunc(CSEL, DL, VT);
21715   }
21716 
21717   // setcc (srl x, imm), 0, ne ==> setcc (and x, (-1 << imm)), 0, ne
21718   if (Cond == ISD::SETNE && isNullConstant(RHS) &&
21719       LHS->getOpcode() == ISD::SRL && isa<ConstantSDNode>(LHS->getOperand(1)) &&
21720       LHS->getConstantOperandVal(1) < VT.getScalarSizeInBits() &&
21721       LHS->hasOneUse()) {
21722     EVT TstVT = LHS->getValueType(0);
21723     if (TstVT.isScalarInteger() && TstVT.getFixedSizeInBits() <= 64) {
21724       // this pattern will get better opt in emitComparison
21725       uint64_t TstImm = -1ULL << LHS->getConstantOperandVal(1);
21726       SDValue TST = DAG.getNode(ISD::AND, DL, TstVT, LHS->getOperand(0),
21727                                 DAG.getConstant(TstImm, DL, TstVT));
21728       return DAG.getNode(ISD::SETCC, DL, VT, TST, RHS, N->getOperand(2));
21729     }
21730   }
21731 
21732   // setcc (iN (bitcast (vNi1 X))), 0, (eq|ne)
21733   //   ==> setcc (iN (zext (i1 (vecreduce_or (vNi1 X))))), 0, (eq|ne)
21734   // setcc (iN (bitcast (vNi1 X))), -1, (eq|ne)
21735   //   ==> setcc (iN (sext (i1 (vecreduce_and (vNi1 X))))), -1, (eq|ne)
21736   if (DCI.isBeforeLegalize() && VT.isScalarInteger() &&
21737       (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
21738       (isNullConstant(RHS) || isAllOnesConstant(RHS)) &&
21739       LHS->getOpcode() == ISD::BITCAST) {
21740     EVT ToVT = LHS->getValueType(0);
21741     EVT FromVT = LHS->getOperand(0).getValueType();
21742     if (FromVT.isFixedLengthVector() &&
21743         FromVT.getVectorElementType() == MVT::i1) {
21744       bool IsNull = isNullConstant(RHS);
21745       LHS = DAG.getNode(IsNull ? ISD::VECREDUCE_OR : ISD::VECREDUCE_AND,
21746                         DL, MVT::i1, LHS->getOperand(0));
21747       LHS = DAG.getNode(IsNull ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND, DL, ToVT,
21748                         LHS);
21749       return DAG.getSetCC(DL, VT, LHS, RHS, Cond);
21750     }
21751   }
21752 
21753   // Try to perform the memcmp when the result is tested for [in]equality with 0
21754   if (SDValue V = performOrXorChainCombine(N, DAG))
21755     return V;
21756 
21757   return SDValue();
21758 }
21759 
21760 // Replace a flag-setting operator (eg ANDS) with the generic version
21761 // (eg AND) if the flag is unused.
21762 static SDValue performFlagSettingCombine(SDNode *N,
21763                                          TargetLowering::DAGCombinerInfo &DCI,
21764                                          unsigned GenericOpcode) {
21765   SDLoc DL(N);
21766   SDValue LHS = N->getOperand(0);
21767   SDValue RHS = N->getOperand(1);
21768   EVT VT = N->getValueType(0);
21769 
21770   // If the flag result isn't used, convert back to a generic opcode.
21771   if (!N->hasAnyUseOfValue(1)) {
21772     SDValue Res = DCI.DAG.getNode(GenericOpcode, DL, VT, N->ops());
21773     return DCI.DAG.getMergeValues({Res, DCI.DAG.getConstant(0, DL, MVT::i32)},
21774                                   DL);
21775   }
21776 
21777   // Combine identical generic nodes into this node, re-using the result.
21778   if (SDNode *Generic = DCI.DAG.getNodeIfExists(
21779           GenericOpcode, DCI.DAG.getVTList(VT), {LHS, RHS}))
21780     DCI.CombineTo(Generic, SDValue(N, 0));
21781 
21782   return SDValue();
21783 }
21784 
21785 static SDValue performSetCCPunpkCombine(SDNode *N, SelectionDAG &DAG) {
21786   // setcc_merge_zero pred
21787   //   (sign_extend (extract_subvector (setcc_merge_zero ... pred ...))), 0, ne
21788   //   => extract_subvector (inner setcc_merge_zero)
21789   SDValue Pred = N->getOperand(0);
21790   SDValue LHS = N->getOperand(1);
21791   SDValue RHS = N->getOperand(2);
21792   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
21793 
21794   if (Cond != ISD::SETNE || !isZerosVector(RHS.getNode()) ||
21795       LHS->getOpcode() != ISD::SIGN_EXTEND)
21796     return SDValue();
21797 
21798   SDValue Extract = LHS->getOperand(0);
21799   if (Extract->getOpcode() != ISD::EXTRACT_SUBVECTOR ||
21800       Extract->getValueType(0) != N->getValueType(0) ||
21801       Extract->getConstantOperandVal(1) != 0)
21802     return SDValue();
21803 
21804   SDValue InnerSetCC = Extract->getOperand(0);
21805   if (InnerSetCC->getOpcode() != AArch64ISD::SETCC_MERGE_ZERO)
21806     return SDValue();
21807 
21808   // By this point we've effectively got
21809   // zero_inactive_lanes_and_trunc_i1(sext_i1(A)). If we can prove A's inactive
21810   // lanes are already zero then the trunc(sext()) sequence is redundant and we
21811   // can operate on A directly.
21812   SDValue InnerPred = InnerSetCC.getOperand(0);
21813   if (Pred.getOpcode() == AArch64ISD::PTRUE &&
21814       InnerPred.getOpcode() == AArch64ISD::PTRUE &&
21815       Pred.getConstantOperandVal(0) == InnerPred.getConstantOperandVal(0) &&
21816       Pred->getConstantOperandVal(0) >= AArch64SVEPredPattern::vl1 &&
21817       Pred->getConstantOperandVal(0) <= AArch64SVEPredPattern::vl256)
21818     return Extract;
21819 
21820   return SDValue();
21821 }
21822 
21823 static SDValue
21824 performSetccMergeZeroCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
21825   assert(N->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
21826          "Unexpected opcode!");
21827 
21828   SelectionDAG &DAG = DCI.DAG;
21829   SDValue Pred = N->getOperand(0);
21830   SDValue LHS = N->getOperand(1);
21831   SDValue RHS = N->getOperand(2);
21832   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
21833 
21834   if (SDValue V = performSetCCPunpkCombine(N, DAG))
21835     return V;
21836 
21837   if (Cond == ISD::SETNE && isZerosVector(RHS.getNode()) &&
21838       LHS->getOpcode() == ISD::SIGN_EXTEND &&
21839       LHS->getOperand(0)->getValueType(0) == N->getValueType(0)) {
21840     //    setcc_merge_zero(
21841     //       pred, extend(setcc_merge_zero(pred, ...)), != splat(0))
21842     // => setcc_merge_zero(pred, ...)
21843     if (LHS->getOperand(0)->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
21844         LHS->getOperand(0)->getOperand(0) == Pred)
21845       return LHS->getOperand(0);
21846 
21847     //    setcc_merge_zero(
21848     //        all_active, extend(nxvNi1 ...), != splat(0))
21849     // -> nxvNi1 ...
21850     if (isAllActivePredicate(DAG, Pred))
21851       return LHS->getOperand(0);
21852 
21853     //    setcc_merge_zero(
21854     //        pred, extend(nxvNi1 ...), != splat(0))
21855     // -> nxvNi1 and(pred, ...)
21856     if (DCI.isAfterLegalizeDAG())
21857       // Do this after legalization to allow more folds on setcc_merge_zero
21858       // to be recognized.
21859       return DAG.getNode(ISD::AND, SDLoc(N), N->getValueType(0),
21860                          LHS->getOperand(0), Pred);
21861   }
21862 
21863   return SDValue();
21864 }
21865 
21866 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
21867 // as well as whether the test should be inverted.  This code is required to
21868 // catch these cases (as opposed to standard dag combines) because
21869 // AArch64ISD::TBZ is matched during legalization.
21870 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
21871                                  SelectionDAG &DAG) {
21872 
21873   if (!Op->hasOneUse())
21874     return Op;
21875 
21876   // We don't handle undef/constant-fold cases below, as they should have
21877   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
21878   // etc.)
21879 
21880   // (tbz (trunc x), b) -> (tbz x, b)
21881   // This case is just here to enable more of the below cases to be caught.
21882   if (Op->getOpcode() == ISD::TRUNCATE &&
21883       Bit < Op->getValueType(0).getSizeInBits()) {
21884     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21885   }
21886 
21887   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
21888   if (Op->getOpcode() == ISD::ANY_EXTEND &&
21889       Bit < Op->getOperand(0).getValueSizeInBits()) {
21890     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21891   }
21892 
21893   if (Op->getNumOperands() != 2)
21894     return Op;
21895 
21896   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
21897   if (!C)
21898     return Op;
21899 
21900   switch (Op->getOpcode()) {
21901   default:
21902     return Op;
21903 
21904   // (tbz (and x, m), b) -> (tbz x, b)
21905   case ISD::AND:
21906     if ((C->getZExtValue() >> Bit) & 1)
21907       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21908     return Op;
21909 
21910   // (tbz (shl x, c), b) -> (tbz x, b-c)
21911   case ISD::SHL:
21912     if (C->getZExtValue() <= Bit &&
21913         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
21914       Bit = Bit - C->getZExtValue();
21915       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21916     }
21917     return Op;
21918 
21919   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
21920   case ISD::SRA:
21921     Bit = Bit + C->getZExtValue();
21922     if (Bit >= Op->getValueType(0).getSizeInBits())
21923       Bit = Op->getValueType(0).getSizeInBits() - 1;
21924     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21925 
21926   // (tbz (srl x, c), b) -> (tbz x, b+c)
21927   case ISD::SRL:
21928     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
21929       Bit = Bit + C->getZExtValue();
21930       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21931     }
21932     return Op;
21933 
21934   // (tbz (xor x, -1), b) -> (tbnz x, b)
21935   case ISD::XOR:
21936     if ((C->getZExtValue() >> Bit) & 1)
21937       Invert = !Invert;
21938     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
21939   }
21940 }
21941 
21942 // Optimize test single bit zero/non-zero and branch.
21943 static SDValue performTBZCombine(SDNode *N,
21944                                  TargetLowering::DAGCombinerInfo &DCI,
21945                                  SelectionDAG &DAG) {
21946   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
21947   bool Invert = false;
21948   SDValue TestSrc = N->getOperand(1);
21949   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
21950 
21951   if (TestSrc == NewTestSrc)
21952     return SDValue();
21953 
21954   unsigned NewOpc = N->getOpcode();
21955   if (Invert) {
21956     if (NewOpc == AArch64ISD::TBZ)
21957       NewOpc = AArch64ISD::TBNZ;
21958     else {
21959       assert(NewOpc == AArch64ISD::TBNZ);
21960       NewOpc = AArch64ISD::TBZ;
21961     }
21962   }
21963 
21964   SDLoc DL(N);
21965   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
21966                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
21967 }
21968 
21969 // Swap vselect operands where it may allow a predicated operation to achieve
21970 // the `sel`.
21971 //
21972 //     (vselect (setcc ( condcode) (_) (_)) (a)          (op (a) (b)))
21973 //  => (vselect (setcc (!condcode) (_) (_)) (op (a) (b)) (a))
21974 static SDValue trySwapVSelectOperands(SDNode *N, SelectionDAG &DAG) {
21975   auto SelectA = N->getOperand(1);
21976   auto SelectB = N->getOperand(2);
21977   auto NTy = N->getValueType(0);
21978 
21979   if (!NTy.isScalableVector())
21980     return SDValue();
21981   SDValue SetCC = N->getOperand(0);
21982   if (SetCC.getOpcode() != ISD::SETCC || !SetCC.hasOneUse())
21983     return SDValue();
21984 
21985   switch (SelectB.getOpcode()) {
21986   default:
21987     return SDValue();
21988   case ISD::FMUL:
21989   case ISD::FSUB:
21990   case ISD::FADD:
21991     break;
21992   }
21993   if (SelectA != SelectB.getOperand(0))
21994     return SDValue();
21995 
21996   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
21997   ISD::CondCode InverseCC =
21998       ISD::getSetCCInverse(CC, SetCC.getOperand(0).getValueType());
21999   auto InverseSetCC =
22000       DAG.getSetCC(SDLoc(SetCC), SetCC.getValueType(), SetCC.getOperand(0),
22001                    SetCC.getOperand(1), InverseCC);
22002 
22003   return DAG.getNode(ISD::VSELECT, SDLoc(N), NTy,
22004                      {InverseSetCC, SelectB, SelectA});
22005 }
22006 
22007 // vselect (v1i1 setcc) ->
22008 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
22009 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
22010 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
22011 // such VSELECT.
22012 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
22013   if (auto SwapResult = trySwapVSelectOperands(N, DAG))
22014     return SwapResult;
22015 
22016   SDValue N0 = N->getOperand(0);
22017   EVT CCVT = N0.getValueType();
22018 
22019   if (isAllActivePredicate(DAG, N0))
22020     return N->getOperand(1);
22021 
22022   if (isAllInactivePredicate(N0))
22023     return N->getOperand(2);
22024 
22025   // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform
22026   // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
22027   // supported types.
22028   SDValue SetCC = N->getOperand(0);
22029   if (SetCC.getOpcode() == ISD::SETCC &&
22030       SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) {
22031     SDValue CmpLHS = SetCC.getOperand(0);
22032     EVT VT = CmpLHS.getValueType();
22033     SDNode *CmpRHS = SetCC.getOperand(1).getNode();
22034     SDNode *SplatLHS = N->getOperand(1).getNode();
22035     SDNode *SplatRHS = N->getOperand(2).getNode();
22036     APInt SplatLHSVal;
22037     if (CmpLHS.getValueType() == N->getOperand(1).getValueType() &&
22038         VT.isSimple() &&
22039         is_contained(ArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
22040                                MVT::v2i32, MVT::v4i32, MVT::v2i64}),
22041                      VT.getSimpleVT().SimpleTy) &&
22042         ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) &&
22043         SplatLHSVal.isOne() && ISD::isConstantSplatVectorAllOnes(CmpRHS) &&
22044         ISD::isConstantSplatVectorAllOnes(SplatRHS)) {
22045       unsigned NumElts = VT.getVectorNumElements();
22046       SmallVector<SDValue, 8> Ops(
22047           NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N),
22048                                    VT.getScalarType()));
22049       SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops);
22050 
22051       auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val);
22052       auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1));
22053       return Or;
22054     }
22055   }
22056 
22057   if (N0.getOpcode() != ISD::SETCC ||
22058       CCVT.getVectorElementCount() != ElementCount::getFixed(1) ||
22059       CCVT.getVectorElementType() != MVT::i1)
22060     return SDValue();
22061 
22062   EVT ResVT = N->getValueType(0);
22063   EVT CmpVT = N0.getOperand(0).getValueType();
22064   // Only combine when the result type is of the same size as the compared
22065   // operands.
22066   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
22067     return SDValue();
22068 
22069   SDValue IfTrue = N->getOperand(1);
22070   SDValue IfFalse = N->getOperand(2);
22071   SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
22072                        N0.getOperand(0), N0.getOperand(1),
22073                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
22074   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
22075                      IfTrue, IfFalse);
22076 }
22077 
22078 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
22079 /// the compare-mask instructions rather than going via NZCV, even if LHS and
22080 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
22081 /// with a vector one followed by a DUP shuffle on the result.
22082 static SDValue performSelectCombine(SDNode *N,
22083                                     TargetLowering::DAGCombinerInfo &DCI) {
22084   SelectionDAG &DAG = DCI.DAG;
22085   SDValue N0 = N->getOperand(0);
22086   EVT ResVT = N->getValueType(0);
22087 
22088   if (N0.getOpcode() != ISD::SETCC)
22089     return SDValue();
22090 
22091   if (ResVT.isScalableVT())
22092     return SDValue();
22093 
22094   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
22095   // scalar SetCCResultType. We also don't expect vectors, because we assume
22096   // that selects fed by vector SETCCs are canonicalized to VSELECT.
22097   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
22098          "Scalar-SETCC feeding SELECT has unexpected result type!");
22099 
22100   // If NumMaskElts == 0, the comparison is larger than select result. The
22101   // largest real NEON comparison is 64-bits per lane, which means the result is
22102   // at most 32-bits and an illegal vector. Just bail out for now.
22103   EVT SrcVT = N0.getOperand(0).getValueType();
22104 
22105   // Don't try to do this optimization when the setcc itself has i1 operands.
22106   // There are no legal vectors of i1, so this would be pointless.
22107   if (SrcVT == MVT::i1)
22108     return SDValue();
22109 
22110   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
22111   if (!ResVT.isVector() || NumMaskElts == 0)
22112     return SDValue();
22113 
22114   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
22115   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
22116 
22117   // Also bail out if the vector CCVT isn't the same size as ResVT.
22118   // This can happen if the SETCC operand size doesn't divide the ResVT size
22119   // (e.g., f64 vs v3f32).
22120   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
22121     return SDValue();
22122 
22123   // Make sure we didn't create illegal types, if we're not supposed to.
22124   assert(DCI.isBeforeLegalize() ||
22125          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
22126 
22127   // First perform a vector comparison, where lane 0 is the one we're interested
22128   // in.
22129   SDLoc DL(N0);
22130   SDValue LHS =
22131       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
22132   SDValue RHS =
22133       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
22134   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
22135 
22136   // Now duplicate the comparison mask we want across all other lanes.
22137   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
22138   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
22139   Mask = DAG.getNode(ISD::BITCAST, DL,
22140                      ResVT.changeVectorElementTypeToInteger(), Mask);
22141 
22142   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
22143 }
22144 
22145 static SDValue performDUPCombine(SDNode *N,
22146                                  TargetLowering::DAGCombinerInfo &DCI) {
22147   EVT VT = N->getValueType(0);
22148   // If "v2i32 DUP(x)" and "v4i32 DUP(x)" both exist, use an extract from the
22149   // 128bit vector version.
22150   if (VT.is64BitVector() && DCI.isAfterLegalizeDAG()) {
22151     EVT LVT = VT.getDoubleNumVectorElementsVT(*DCI.DAG.getContext());
22152     SmallVector<SDValue> Ops(N->ops());
22153     if (SDNode *LN = DCI.DAG.getNodeIfExists(N->getOpcode(),
22154                                              DCI.DAG.getVTList(LVT), Ops)) {
22155       SDLoc DL(N);
22156       return DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SDValue(LN, 0),
22157                              DCI.DAG.getConstant(0, DL, MVT::i64));
22158     }
22159   }
22160 
22161   if (N->getOpcode() == AArch64ISD::DUP)
22162     return performPostLD1Combine(N, DCI, false);
22163 
22164   return SDValue();
22165 }
22166 
22167 /// Get rid of unnecessary NVCASTs (that don't change the type).
22168 static SDValue performNVCASTCombine(SDNode *N) {
22169   if (N->getValueType(0) == N->getOperand(0).getValueType())
22170     return N->getOperand(0);
22171 
22172   return SDValue();
22173 }
22174 
22175 // If all users of the globaladdr are of the form (globaladdr + constant), find
22176 // the smallest constant, fold it into the globaladdr's offset and rewrite the
22177 // globaladdr as (globaladdr + constant) - constant.
22178 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
22179                                            const AArch64Subtarget *Subtarget,
22180                                            const TargetMachine &TM) {
22181   auto *GN = cast<GlobalAddressSDNode>(N);
22182   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
22183       AArch64II::MO_NO_FLAG)
22184     return SDValue();
22185 
22186   uint64_t MinOffset = -1ull;
22187   for (SDNode *N : GN->uses()) {
22188     if (N->getOpcode() != ISD::ADD)
22189       return SDValue();
22190     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
22191     if (!C)
22192       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22193     if (!C)
22194       return SDValue();
22195     MinOffset = std::min(MinOffset, C->getZExtValue());
22196   }
22197   uint64_t Offset = MinOffset + GN->getOffset();
22198 
22199   // Require that the new offset is larger than the existing one. Otherwise, we
22200   // can end up oscillating between two possible DAGs, for example,
22201   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
22202   if (Offset <= uint64_t(GN->getOffset()))
22203     return SDValue();
22204 
22205   // Check whether folding this offset is legal. It must not go out of bounds of
22206   // the referenced object to avoid violating the code model, and must be
22207   // smaller than 2^20 because this is the largest offset expressible in all
22208   // object formats. (The IMAGE_REL_ARM64_PAGEBASE_REL21 relocation in COFF
22209   // stores an immediate signed 21 bit offset.)
22210   //
22211   // This check also prevents us from folding negative offsets, which will end
22212   // up being treated in the same way as large positive ones. They could also
22213   // cause code model violations, and aren't really common enough to matter.
22214   if (Offset >= (1 << 20))
22215     return SDValue();
22216 
22217   const GlobalValue *GV = GN->getGlobal();
22218   Type *T = GV->getValueType();
22219   if (!T->isSized() ||
22220       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
22221     return SDValue();
22222 
22223   SDLoc DL(GN);
22224   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
22225   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
22226                      DAG.getConstant(MinOffset, DL, MVT::i64));
22227 }
22228 
22229 static SDValue performCTLZCombine(SDNode *N, SelectionDAG &DAG,
22230                                   const AArch64Subtarget *Subtarget) {
22231   SDValue BR = N->getOperand(0);
22232   if (!Subtarget->hasCSSC() || BR.getOpcode() != ISD::BITREVERSE ||
22233       !BR.getValueType().isScalarInteger())
22234     return SDValue();
22235 
22236   SDLoc DL(N);
22237   return DAG.getNode(ISD::CTTZ, DL, BR.getValueType(), BR.getOperand(0));
22238 }
22239 
22240 // Turns the vector of indices into a vector of byte offstes by scaling Offset
22241 // by (BitWidth / 8).
22242 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
22243                                           SDLoc DL, unsigned BitWidth) {
22244   assert(Offset.getValueType().isScalableVector() &&
22245          "This method is only for scalable vectors of offsets");
22246 
22247   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
22248   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
22249 
22250   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
22251 }
22252 
22253 /// Check if the value of \p OffsetInBytes can be used as an immediate for
22254 /// the gather load/prefetch and scatter store instructions with vector base and
22255 /// immediate offset addressing mode:
22256 ///
22257 ///      [<Zn>.[S|D]{, #<imm>}]
22258 ///
22259 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
22260 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
22261                                                   unsigned ScalarSizeInBytes) {
22262   // The immediate is not a multiple of the scalar size.
22263   if (OffsetInBytes % ScalarSizeInBytes)
22264     return false;
22265 
22266   // The immediate is out of range.
22267   if (OffsetInBytes / ScalarSizeInBytes > 31)
22268     return false;
22269 
22270   return true;
22271 }
22272 
22273 /// Check if the value of \p Offset represents a valid immediate for the SVE
22274 /// gather load/prefetch and scatter store instructiona with vector base and
22275 /// immediate offset addressing mode:
22276 ///
22277 ///      [<Zn>.[S|D]{, #<imm>}]
22278 ///
22279 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
22280 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
22281                                            unsigned ScalarSizeInBytes) {
22282   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
22283   return OffsetConst && isValidImmForSVEVecImmAddrMode(
22284                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
22285 }
22286 
22287 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
22288                                           unsigned Opcode,
22289                                           bool OnlyPackedOffsets = true) {
22290   const SDValue Src = N->getOperand(2);
22291   const EVT SrcVT = Src->getValueType(0);
22292   assert(SrcVT.isScalableVector() &&
22293          "Scatter stores are only possible for SVE vectors");
22294 
22295   SDLoc DL(N);
22296   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
22297 
22298   // Make sure that source data will fit into an SVE register
22299   if (SrcVT.getSizeInBits().getKnownMinValue() > AArch64::SVEBitsPerBlock)
22300     return SDValue();
22301 
22302   // For FPs, ACLE only supports _packed_ single and double precision types.
22303   if (SrcElVT.isFloatingPoint())
22304     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
22305       return SDValue();
22306 
22307   // Depending on the addressing mode, this is either a pointer or a vector of
22308   // pointers (that fits into one register)
22309   SDValue Base = N->getOperand(4);
22310   // Depending on the addressing mode, this is either a single offset or a
22311   // vector of offsets  (that fits into one register)
22312   SDValue Offset = N->getOperand(5);
22313 
22314   // For "scalar + vector of indices", just scale the indices. This only
22315   // applies to non-temporal scatters because there's no instruction that takes
22316   // indicies.
22317   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
22318     Offset =
22319         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
22320     Opcode = AArch64ISD::SSTNT1_PRED;
22321   }
22322 
22323   // In the case of non-temporal gather loads there's only one SVE instruction
22324   // per data-size: "scalar + vector", i.e.
22325   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
22326   // Since we do have intrinsics that allow the arguments to be in a different
22327   // order, we may need to swap them to match the spec.
22328   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
22329     std::swap(Base, Offset);
22330 
22331   // SST1_IMM requires that the offset is an immediate that is:
22332   //    * a multiple of #SizeInBytes,
22333   //    * in the range [0, 31 x #SizeInBytes],
22334   // where #SizeInBytes is the size in bytes of the stored items. For
22335   // immediates outside that range and non-immediate scalar offsets use SST1 or
22336   // SST1_UXTW instead.
22337   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
22338     if (!isValidImmForSVEVecImmAddrMode(Offset,
22339                                         SrcVT.getScalarSizeInBits() / 8)) {
22340       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
22341         Opcode = AArch64ISD::SST1_UXTW_PRED;
22342       else
22343         Opcode = AArch64ISD::SST1_PRED;
22344 
22345       std::swap(Base, Offset);
22346     }
22347   }
22348 
22349   auto &TLI = DAG.getTargetLoweringInfo();
22350   if (!TLI.isTypeLegal(Base.getValueType()))
22351     return SDValue();
22352 
22353   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
22354   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
22355   // nxv2i64. Legalize accordingly.
22356   if (!OnlyPackedOffsets &&
22357       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
22358     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
22359 
22360   if (!TLI.isTypeLegal(Offset.getValueType()))
22361     return SDValue();
22362 
22363   // Source value type that is representable in hardware
22364   EVT HwSrcVt = getSVEContainerType(SrcVT);
22365 
22366   // Keep the original type of the input data to store - this is needed to be
22367   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
22368   // FP values we want the integer equivalent, so just use HwSrcVt.
22369   SDValue InputVT = DAG.getValueType(SrcVT);
22370   if (SrcVT.isFloatingPoint())
22371     InputVT = DAG.getValueType(HwSrcVt);
22372 
22373   SDVTList VTs = DAG.getVTList(MVT::Other);
22374   SDValue SrcNew;
22375 
22376   if (Src.getValueType().isFloatingPoint())
22377     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
22378   else
22379     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
22380 
22381   SDValue Ops[] = {N->getOperand(0), // Chain
22382                    SrcNew,
22383                    N->getOperand(3), // Pg
22384                    Base,
22385                    Offset,
22386                    InputVT};
22387 
22388   return DAG.getNode(Opcode, DL, VTs, Ops);
22389 }
22390 
22391 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
22392                                         unsigned Opcode,
22393                                         bool OnlyPackedOffsets = true) {
22394   const EVT RetVT = N->getValueType(0);
22395   assert(RetVT.isScalableVector() &&
22396          "Gather loads are only possible for SVE vectors");
22397 
22398   SDLoc DL(N);
22399 
22400   // Make sure that the loaded data will fit into an SVE register
22401   if (RetVT.getSizeInBits().getKnownMinValue() > AArch64::SVEBitsPerBlock)
22402     return SDValue();
22403 
22404   // Depending on the addressing mode, this is either a pointer or a vector of
22405   // pointers (that fits into one register)
22406   SDValue Base = N->getOperand(3);
22407   // Depending on the addressing mode, this is either a single offset or a
22408   // vector of offsets  (that fits into one register)
22409   SDValue Offset = N->getOperand(4);
22410 
22411   // For "scalar + vector of indices", just scale the indices. This only
22412   // applies to non-temporal gathers because there's no instruction that takes
22413   // indicies.
22414   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
22415     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
22416                                         RetVT.getScalarSizeInBits());
22417     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
22418   }
22419 
22420   // In the case of non-temporal gather loads there's only one SVE instruction
22421   // per data-size: "scalar + vector", i.e.
22422   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
22423   // Since we do have intrinsics that allow the arguments to be in a different
22424   // order, we may need to swap them to match the spec.
22425   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
22426       Offset.getValueType().isVector())
22427     std::swap(Base, Offset);
22428 
22429   // GLD{FF}1_IMM requires that the offset is an immediate that is:
22430   //    * a multiple of #SizeInBytes,
22431   //    * in the range [0, 31 x #SizeInBytes],
22432   // where #SizeInBytes is the size in bytes of the loaded items. For
22433   // immediates outside that range and non-immediate scalar offsets use
22434   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
22435   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
22436       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
22437     if (!isValidImmForSVEVecImmAddrMode(Offset,
22438                                         RetVT.getScalarSizeInBits() / 8)) {
22439       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
22440         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
22441                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
22442                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
22443       else
22444         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
22445                      ? AArch64ISD::GLD1_MERGE_ZERO
22446                      : AArch64ISD::GLDFF1_MERGE_ZERO;
22447 
22448       std::swap(Base, Offset);
22449     }
22450   }
22451 
22452   auto &TLI = DAG.getTargetLoweringInfo();
22453   if (!TLI.isTypeLegal(Base.getValueType()))
22454     return SDValue();
22455 
22456   // Some gather load variants allow unpacked offsets, but only as nxv2i32
22457   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
22458   // nxv2i64. Legalize accordingly.
22459   if (!OnlyPackedOffsets &&
22460       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
22461     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
22462 
22463   // Return value type that is representable in hardware
22464   EVT HwRetVt = getSVEContainerType(RetVT);
22465 
22466   // Keep the original output value type around - this is needed to be able to
22467   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
22468   // values we want the integer equivalent, so just use HwRetVT.
22469   SDValue OutVT = DAG.getValueType(RetVT);
22470   if (RetVT.isFloatingPoint())
22471     OutVT = DAG.getValueType(HwRetVt);
22472 
22473   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
22474   SDValue Ops[] = {N->getOperand(0), // Chain
22475                    N->getOperand(2), // Pg
22476                    Base, Offset, OutVT};
22477 
22478   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
22479   SDValue LoadChain = SDValue(Load.getNode(), 1);
22480 
22481   if (RetVT.isInteger() && (RetVT != HwRetVt))
22482     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
22483 
22484   // If the original return value was FP, bitcast accordingly. Doing it here
22485   // means that we can avoid adding TableGen patterns for FPs.
22486   if (RetVT.isFloatingPoint())
22487     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
22488 
22489   return DAG.getMergeValues({Load, LoadChain}, DL);
22490 }
22491 
22492 static SDValue
22493 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
22494                               SelectionDAG &DAG) {
22495   SDLoc DL(N);
22496   SDValue Src = N->getOperand(0);
22497   unsigned Opc = Src->getOpcode();
22498 
22499   // Sign extend of an unsigned unpack -> signed unpack
22500   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
22501 
22502     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
22503                                                : AArch64ISD::SUNPKLO;
22504 
22505     // Push the sign extend to the operand of the unpack
22506     // This is necessary where, for example, the operand of the unpack
22507     // is another unpack:
22508     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
22509     // ->
22510     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
22511     // ->
22512     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
22513     SDValue ExtOp = Src->getOperand(0);
22514     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
22515     EVT EltTy = VT.getVectorElementType();
22516     (void)EltTy;
22517 
22518     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
22519            "Sign extending from an invalid type");
22520 
22521     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
22522 
22523     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
22524                               ExtOp, DAG.getValueType(ExtVT));
22525 
22526     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
22527   }
22528 
22529   if (DCI.isBeforeLegalizeOps())
22530     return SDValue();
22531 
22532   if (!EnableCombineMGatherIntrinsics)
22533     return SDValue();
22534 
22535   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
22536   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
22537   unsigned NewOpc;
22538   unsigned MemVTOpNum = 4;
22539   switch (Opc) {
22540   case AArch64ISD::LD1_MERGE_ZERO:
22541     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
22542     MemVTOpNum = 3;
22543     break;
22544   case AArch64ISD::LDNF1_MERGE_ZERO:
22545     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
22546     MemVTOpNum = 3;
22547     break;
22548   case AArch64ISD::LDFF1_MERGE_ZERO:
22549     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
22550     MemVTOpNum = 3;
22551     break;
22552   case AArch64ISD::GLD1_MERGE_ZERO:
22553     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
22554     break;
22555   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
22556     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
22557     break;
22558   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
22559     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
22560     break;
22561   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
22562     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
22563     break;
22564   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
22565     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
22566     break;
22567   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
22568     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
22569     break;
22570   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
22571     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
22572     break;
22573   case AArch64ISD::GLDFF1_MERGE_ZERO:
22574     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
22575     break;
22576   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
22577     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
22578     break;
22579   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
22580     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
22581     break;
22582   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
22583     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
22584     break;
22585   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
22586     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
22587     break;
22588   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
22589     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
22590     break;
22591   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
22592     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
22593     break;
22594   case AArch64ISD::GLDNT1_MERGE_ZERO:
22595     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
22596     break;
22597   default:
22598     return SDValue();
22599   }
22600 
22601   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
22602   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
22603 
22604   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
22605     return SDValue();
22606 
22607   EVT DstVT = N->getValueType(0);
22608   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
22609 
22610   SmallVector<SDValue, 5> Ops;
22611   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
22612     Ops.push_back(Src->getOperand(I));
22613 
22614   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
22615   DCI.CombineTo(N, ExtLoad);
22616   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
22617 
22618   // Return N so it doesn't get rechecked
22619   return SDValue(N, 0);
22620 }
22621 
22622 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
22623 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
22624 /// != nxv2i32) do not need legalization.
22625 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
22626   const unsigned OffsetPos = 4;
22627   SDValue Offset = N->getOperand(OffsetPos);
22628 
22629   // Not an unpacked vector, bail out.
22630   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
22631     return SDValue();
22632 
22633   // Extend the unpacked offset vector to 64-bit lanes.
22634   SDLoc DL(N);
22635   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
22636   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
22637   // Replace the offset operand with the 64-bit one.
22638   Ops[OffsetPos] = Offset;
22639 
22640   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
22641 }
22642 
22643 /// Combines a node carrying the intrinsic
22644 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
22645 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
22646 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
22647 /// sve gather prefetch instruction with vector plus immediate addressing mode.
22648 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
22649                                                unsigned ScalarSizeInBytes) {
22650   const unsigned ImmPos = 4, OffsetPos = 3;
22651   // No need to combine the node if the immediate is valid...
22652   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
22653     return SDValue();
22654 
22655   // ...otherwise swap the offset base with the offset...
22656   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
22657   std::swap(Ops[ImmPos], Ops[OffsetPos]);
22658   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
22659   // `aarch64_sve_prfb_gather_uxtw_index`.
22660   SDLoc DL(N);
22661   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
22662                            MVT::i64);
22663 
22664   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
22665 }
22666 
22667 // Return true if the vector operation can guarantee only the first lane of its
22668 // result contains data, with all bits in other lanes set to zero.
22669 static bool isLanes1toNKnownZero(SDValue Op) {
22670   switch (Op.getOpcode()) {
22671   default:
22672     return false;
22673   case AArch64ISD::ANDV_PRED:
22674   case AArch64ISD::EORV_PRED:
22675   case AArch64ISD::FADDA_PRED:
22676   case AArch64ISD::FADDV_PRED:
22677   case AArch64ISD::FMAXNMV_PRED:
22678   case AArch64ISD::FMAXV_PRED:
22679   case AArch64ISD::FMINNMV_PRED:
22680   case AArch64ISD::FMINV_PRED:
22681   case AArch64ISD::ORV_PRED:
22682   case AArch64ISD::SADDV_PRED:
22683   case AArch64ISD::SMAXV_PRED:
22684   case AArch64ISD::SMINV_PRED:
22685   case AArch64ISD::UADDV_PRED:
22686   case AArch64ISD::UMAXV_PRED:
22687   case AArch64ISD::UMINV_PRED:
22688     return true;
22689   }
22690 }
22691 
22692 static SDValue removeRedundantInsertVectorElt(SDNode *N) {
22693   assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Unexpected node!");
22694   SDValue InsertVec = N->getOperand(0);
22695   SDValue InsertElt = N->getOperand(1);
22696   SDValue InsertIdx = N->getOperand(2);
22697 
22698   // We only care about inserts into the first element...
22699   if (!isNullConstant(InsertIdx))
22700     return SDValue();
22701   // ...of a zero'd vector...
22702   if (!ISD::isConstantSplatVectorAllZeros(InsertVec.getNode()))
22703     return SDValue();
22704   // ...where the inserted data was previously extracted...
22705   if (InsertElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22706     return SDValue();
22707 
22708   SDValue ExtractVec = InsertElt.getOperand(0);
22709   SDValue ExtractIdx = InsertElt.getOperand(1);
22710 
22711   // ...from the first element of a vector.
22712   if (!isNullConstant(ExtractIdx))
22713     return SDValue();
22714 
22715   // If we get here we are effectively trying to zero lanes 1-N of a vector.
22716 
22717   // Ensure there's no type conversion going on.
22718   if (N->getValueType(0) != ExtractVec.getValueType())
22719     return SDValue();
22720 
22721   if (!isLanes1toNKnownZero(ExtractVec))
22722     return SDValue();
22723 
22724   // The explicit zeroing is redundant.
22725   return ExtractVec;
22726 }
22727 
22728 static SDValue
22729 performInsertVectorEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
22730   if (SDValue Res = removeRedundantInsertVectorElt(N))
22731     return Res;
22732 
22733   return performPostLD1Combine(N, DCI, true);
22734 }
22735 
22736 static SDValue performSVESpliceCombine(SDNode *N, SelectionDAG &DAG) {
22737   EVT Ty = N->getValueType(0);
22738   if (Ty.isInteger())
22739     return SDValue();
22740 
22741   EVT IntTy = Ty.changeVectorElementTypeToInteger();
22742   EVT ExtIntTy = getPackedSVEVectorVT(IntTy.getVectorElementCount());
22743   if (ExtIntTy.getVectorElementType().getScalarSizeInBits() <
22744       IntTy.getVectorElementType().getScalarSizeInBits())
22745     return SDValue();
22746 
22747   SDLoc DL(N);
22748   SDValue LHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(0)),
22749                                      DL, ExtIntTy);
22750   SDValue RHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(1)),
22751                                      DL, ExtIntTy);
22752   SDValue Idx = N->getOperand(2);
22753   SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ExtIntTy, LHS, RHS, Idx);
22754   SDValue Trunc = DAG.getAnyExtOrTrunc(Splice, DL, IntTy);
22755   return DAG.getBitcast(Ty, Trunc);
22756 }
22757 
22758 static SDValue performFPExtendCombine(SDNode *N, SelectionDAG &DAG,
22759                                       TargetLowering::DAGCombinerInfo &DCI,
22760                                       const AArch64Subtarget *Subtarget) {
22761   SDValue N0 = N->getOperand(0);
22762   EVT VT = N->getValueType(0);
22763 
22764   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
22765   if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::FP_ROUND)
22766     return SDValue();
22767 
22768   auto hasValidElementTypeForFPExtLoad = [](EVT VT) {
22769     EVT EltVT = VT.getVectorElementType();
22770     return EltVT == MVT::f32 || EltVT == MVT::f64;
22771   };
22772 
22773   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
22774   // We purposefully don't care about legality of the nodes here as we know
22775   // they can be split down into something legal.
22776   if (DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(N0.getNode()) &&
22777       N0.hasOneUse() && Subtarget->useSVEForFixedLengthVectors() &&
22778       VT.isFixedLengthVector() && hasValidElementTypeForFPExtLoad(VT) &&
22779       VT.getFixedSizeInBits() >= Subtarget->getMinSVEVectorSizeInBits()) {
22780     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
22781     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
22782                                      LN0->getChain(), LN0->getBasePtr(),
22783                                      N0.getValueType(), LN0->getMemOperand());
22784     DCI.CombineTo(N, ExtLoad);
22785     DCI.CombineTo(
22786         N0.getNode(),
22787         DAG.getNode(ISD::FP_ROUND, SDLoc(N0), N0.getValueType(), ExtLoad,
22788                     DAG.getIntPtrConstant(1, SDLoc(N0), /*isTarget=*/true)),
22789         ExtLoad.getValue(1));
22790     return SDValue(N, 0); // Return N so it doesn't get rechecked!
22791   }
22792 
22793   return SDValue();
22794 }
22795 
22796 static SDValue performBSPExpandForSVE(SDNode *N, SelectionDAG &DAG,
22797                                       const AArch64Subtarget *Subtarget) {
22798   EVT VT = N->getValueType(0);
22799 
22800   // Don't expand for NEON, SVE2 or SME
22801   if (!VT.isScalableVector() || Subtarget->hasSVE2() || Subtarget->hasSME())
22802     return SDValue();
22803 
22804   SDLoc DL(N);
22805 
22806   SDValue Mask = N->getOperand(0);
22807   SDValue In1 = N->getOperand(1);
22808   SDValue In2 = N->getOperand(2);
22809 
22810   SDValue InvMask = DAG.getNOT(DL, Mask, VT);
22811   SDValue Sel = DAG.getNode(ISD::AND, DL, VT, Mask, In1);
22812   SDValue SelInv = DAG.getNode(ISD::AND, DL, VT, InvMask, In2);
22813   return DAG.getNode(ISD::OR, DL, VT, Sel, SelInv);
22814 }
22815 
22816 static SDValue performDupLane128Combine(SDNode *N, SelectionDAG &DAG) {
22817   EVT VT = N->getValueType(0);
22818 
22819   SDValue Insert = N->getOperand(0);
22820   if (Insert.getOpcode() != ISD::INSERT_SUBVECTOR)
22821     return SDValue();
22822 
22823   if (!Insert.getOperand(0).isUndef())
22824     return SDValue();
22825 
22826   uint64_t IdxInsert = Insert.getConstantOperandVal(2);
22827   uint64_t IdxDupLane = N->getConstantOperandVal(1);
22828   if (IdxInsert != 0 || IdxDupLane != 0)
22829     return SDValue();
22830 
22831   SDValue Bitcast = Insert.getOperand(1);
22832   if (Bitcast.getOpcode() != ISD::BITCAST)
22833     return SDValue();
22834 
22835   SDValue Subvec = Bitcast.getOperand(0);
22836   EVT SubvecVT = Subvec.getValueType();
22837   if (!SubvecVT.is128BitVector())
22838     return SDValue();
22839   EVT NewSubvecVT =
22840       getPackedSVEVectorVT(Subvec.getValueType().getVectorElementType());
22841 
22842   SDLoc DL(N);
22843   SDValue NewInsert =
22844       DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewSubvecVT,
22845                   DAG.getUNDEF(NewSubvecVT), Subvec, Insert->getOperand(2));
22846   SDValue NewDuplane128 = DAG.getNode(AArch64ISD::DUPLANE128, DL, NewSubvecVT,
22847                                       NewInsert, N->getOperand(1));
22848   return DAG.getNode(ISD::BITCAST, DL, VT, NewDuplane128);
22849 }
22850 
22851 // Try to combine mull with uzp1.
22852 static SDValue tryCombineMULLWithUZP1(SDNode *N,
22853                                       TargetLowering::DAGCombinerInfo &DCI,
22854                                       SelectionDAG &DAG) {
22855   if (DCI.isBeforeLegalizeOps())
22856     return SDValue();
22857 
22858   SDValue LHS = N->getOperand(0);
22859   SDValue RHS = N->getOperand(1);
22860 
22861   SDValue ExtractHigh;
22862   SDValue ExtractLow;
22863   SDValue TruncHigh;
22864   SDValue TruncLow;
22865   SDLoc DL(N);
22866 
22867   // Check the operands are trunc and extract_high.
22868   if (isEssentiallyExtractHighSubvector(LHS) &&
22869       RHS.getOpcode() == ISD::TRUNCATE) {
22870     TruncHigh = RHS;
22871     if (LHS.getOpcode() == ISD::BITCAST)
22872       ExtractHigh = LHS.getOperand(0);
22873     else
22874       ExtractHigh = LHS;
22875   } else if (isEssentiallyExtractHighSubvector(RHS) &&
22876              LHS.getOpcode() == ISD::TRUNCATE) {
22877     TruncHigh = LHS;
22878     if (LHS.getOpcode() == ISD::BITCAST)
22879       ExtractHigh = RHS.getOperand(0);
22880     else
22881       ExtractHigh = RHS;
22882   } else
22883     return SDValue();
22884 
22885   // If the truncate's operand is BUILD_VECTOR with DUP, do not combine the op
22886   // with uzp1.
22887   // You can see the regressions on test/CodeGen/AArch64/aarch64-smull.ll
22888   SDValue TruncHighOp = TruncHigh.getOperand(0);
22889   EVT TruncHighOpVT = TruncHighOp.getValueType();
22890   if (TruncHighOp.getOpcode() == AArch64ISD::DUP ||
22891       DAG.isSplatValue(TruncHighOp, false))
22892     return SDValue();
22893 
22894   // Check there is other extract_high with same source vector.
22895   // For example,
22896   //
22897   //    t18: v4i16 = extract_subvector t2, Constant:i64<0>
22898   //    t12: v4i16 = truncate t11
22899   //  t31: v4i32 = AArch64ISD::SMULL t18, t12
22900   //    t23: v4i16 = extract_subvector t2, Constant:i64<4>
22901   //    t16: v4i16 = truncate t15
22902   //  t30: v4i32 = AArch64ISD::SMULL t23, t1
22903   //
22904   // This dagcombine assumes the two extract_high uses same source vector in
22905   // order to detect the pair of the mull. If they have different source vector,
22906   // this code will not work.
22907   bool HasFoundMULLow = true;
22908   SDValue ExtractHighSrcVec = ExtractHigh.getOperand(0);
22909   if (ExtractHighSrcVec->use_size() != 2)
22910     HasFoundMULLow = false;
22911 
22912   // Find ExtractLow.
22913   for (SDNode *User : ExtractHighSrcVec.getNode()->uses()) {
22914     if (User == ExtractHigh.getNode())
22915       continue;
22916 
22917     if (User->getOpcode() != ISD::EXTRACT_SUBVECTOR ||
22918         !isNullConstant(User->getOperand(1))) {
22919       HasFoundMULLow = false;
22920       break;
22921     }
22922 
22923     ExtractLow.setNode(User);
22924   }
22925 
22926   if (!ExtractLow || !ExtractLow->hasOneUse())
22927     HasFoundMULLow = false;
22928 
22929   // Check ExtractLow's user.
22930   if (HasFoundMULLow) {
22931     SDNode *ExtractLowUser = *ExtractLow.getNode()->use_begin();
22932     if (ExtractLowUser->getOpcode() != N->getOpcode())
22933       HasFoundMULLow = false;
22934 
22935     if (ExtractLowUser->getOperand(0) == ExtractLow) {
22936       if (ExtractLowUser->getOperand(1).getOpcode() == ISD::TRUNCATE)
22937         TruncLow = ExtractLowUser->getOperand(1);
22938       else
22939         HasFoundMULLow = false;
22940     } else {
22941       if (ExtractLowUser->getOperand(0).getOpcode() == ISD::TRUNCATE)
22942         TruncLow = ExtractLowUser->getOperand(0);
22943       else
22944         HasFoundMULLow = false;
22945     }
22946   }
22947 
22948   // If the truncate's operand is BUILD_VECTOR with DUP, do not combine the op
22949   // with uzp1.
22950   // You can see the regressions on test/CodeGen/AArch64/aarch64-smull.ll
22951   EVT TruncHighVT = TruncHigh.getValueType();
22952   EVT UZP1VT = TruncHighVT.getDoubleNumVectorElementsVT(*DAG.getContext());
22953   SDValue TruncLowOp =
22954       HasFoundMULLow ? TruncLow.getOperand(0) : DAG.getUNDEF(UZP1VT);
22955   EVT TruncLowOpVT = TruncLowOp.getValueType();
22956   if (HasFoundMULLow && (TruncLowOp.getOpcode() == AArch64ISD::DUP ||
22957                          DAG.isSplatValue(TruncLowOp, false)))
22958     return SDValue();
22959 
22960   // Create uzp1, extract_high and extract_low.
22961   if (TruncHighOpVT != UZP1VT)
22962     TruncHighOp = DAG.getNode(ISD::BITCAST, DL, UZP1VT, TruncHighOp);
22963   if (TruncLowOpVT != UZP1VT)
22964     TruncLowOp = DAG.getNode(ISD::BITCAST, DL, UZP1VT, TruncLowOp);
22965 
22966   SDValue UZP1 =
22967       DAG.getNode(AArch64ISD::UZP1, DL, UZP1VT, TruncLowOp, TruncHighOp);
22968   SDValue HighIdxCst =
22969       DAG.getConstant(TruncHighVT.getVectorNumElements(), DL, MVT::i64);
22970   SDValue NewTruncHigh =
22971       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, TruncHighVT, UZP1, HighIdxCst);
22972   DAG.ReplaceAllUsesWith(TruncHigh, NewTruncHigh);
22973 
22974   if (HasFoundMULLow) {
22975     EVT TruncLowVT = TruncLow.getValueType();
22976     SDValue NewTruncLow = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, TruncLowVT,
22977                                       UZP1, ExtractLow.getOperand(1));
22978     DAG.ReplaceAllUsesWith(TruncLow, NewTruncLow);
22979   }
22980 
22981   return SDValue(N, 0);
22982 }
22983 
22984 static SDValue performMULLCombine(SDNode *N,
22985                                   TargetLowering::DAGCombinerInfo &DCI,
22986                                   SelectionDAG &DAG) {
22987   if (SDValue Val =
22988           tryCombineLongOpWithDup(Intrinsic::not_intrinsic, N, DCI, DAG))
22989     return Val;
22990 
22991   if (SDValue Val = tryCombineMULLWithUZP1(N, DCI, DAG))
22992     return Val;
22993 
22994   return SDValue();
22995 }
22996 
22997 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
22998                                                  DAGCombinerInfo &DCI) const {
22999   SelectionDAG &DAG = DCI.DAG;
23000   switch (N->getOpcode()) {
23001   default:
23002     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
23003     break;
23004   case ISD::VECREDUCE_AND:
23005   case ISD::VECREDUCE_OR:
23006   case ISD::VECREDUCE_XOR:
23007     return performVecReduceBitwiseCombine(N, DCI, DAG);
23008   case ISD::ADD:
23009   case ISD::SUB:
23010     return performAddSubCombine(N, DCI);
23011   case ISD::BUILD_VECTOR:
23012     return performBuildVectorCombine(N, DCI, DAG);
23013   case ISD::TRUNCATE:
23014     return performTruncateCombine(N, DAG);
23015   case AArch64ISD::ANDS:
23016     return performFlagSettingCombine(N, DCI, ISD::AND);
23017   case AArch64ISD::ADC:
23018     if (auto R = foldOverflowCheck(N, DAG, /* IsAdd */ true))
23019       return R;
23020     return foldADCToCINC(N, DAG);
23021   case AArch64ISD::SBC:
23022     return foldOverflowCheck(N, DAG, /* IsAdd */ false);
23023   case AArch64ISD::ADCS:
23024     if (auto R = foldOverflowCheck(N, DAG, /* IsAdd */ true))
23025       return R;
23026     return performFlagSettingCombine(N, DCI, AArch64ISD::ADC);
23027   case AArch64ISD::SBCS:
23028     if (auto R = foldOverflowCheck(N, DAG, /* IsAdd */ false))
23029       return R;
23030     return performFlagSettingCombine(N, DCI, AArch64ISD::SBC);
23031   case ISD::XOR:
23032     return performXorCombine(N, DAG, DCI, Subtarget);
23033   case ISD::MUL:
23034     return performMulCombine(N, DAG, DCI, Subtarget);
23035   case ISD::SINT_TO_FP:
23036   case ISD::UINT_TO_FP:
23037     return performIntToFpCombine(N, DAG, Subtarget);
23038   case ISD::FP_TO_SINT:
23039   case ISD::FP_TO_UINT:
23040   case ISD::FP_TO_SINT_SAT:
23041   case ISD::FP_TO_UINT_SAT:
23042     return performFpToIntCombine(N, DAG, DCI, Subtarget);
23043   case ISD::FDIV:
23044     return performFDivCombine(N, DAG, DCI, Subtarget);
23045   case ISD::OR:
23046     return performORCombine(N, DCI, Subtarget, *this);
23047   case ISD::AND:
23048     return performANDCombine(N, DCI);
23049   case ISD::FADD:
23050     return performFADDCombine(N, DCI);
23051   case ISD::INTRINSIC_WO_CHAIN:
23052     return performIntrinsicCombine(N, DCI, Subtarget);
23053   case ISD::ANY_EXTEND:
23054   case ISD::ZERO_EXTEND:
23055   case ISD::SIGN_EXTEND:
23056     return performExtendCombine(N, DCI, DAG);
23057   case ISD::SIGN_EXTEND_INREG:
23058     return performSignExtendInRegCombine(N, DCI, DAG);
23059   case ISD::CONCAT_VECTORS:
23060     return performConcatVectorsCombine(N, DCI, DAG);
23061   case ISD::EXTRACT_SUBVECTOR:
23062     return performExtractSubvectorCombine(N, DCI, DAG);
23063   case ISD::INSERT_SUBVECTOR:
23064     return performInsertSubvectorCombine(N, DCI, DAG);
23065   case ISD::SELECT:
23066     return performSelectCombine(N, DCI);
23067   case ISD::VSELECT:
23068     return performVSelectCombine(N, DCI.DAG);
23069   case ISD::SETCC:
23070     return performSETCCCombine(N, DCI, DAG);
23071   case ISD::LOAD:
23072     return performLOADCombine(N, DCI, DAG, Subtarget);
23073   case ISD::STORE:
23074     return performSTORECombine(N, DCI, DAG, Subtarget);
23075   case ISD::MSTORE:
23076     return performMSTORECombine(N, DCI, DAG, Subtarget);
23077   case ISD::MGATHER:
23078   case ISD::MSCATTER:
23079     return performMaskedGatherScatterCombine(N, DCI, DAG);
23080   case ISD::VECTOR_SPLICE:
23081     return performSVESpliceCombine(N, DAG);
23082   case ISD::FP_EXTEND:
23083     return performFPExtendCombine(N, DAG, DCI, Subtarget);
23084   case AArch64ISD::BRCOND:
23085     return performBRCONDCombine(N, DCI, DAG);
23086   case AArch64ISD::TBNZ:
23087   case AArch64ISD::TBZ:
23088     return performTBZCombine(N, DCI, DAG);
23089   case AArch64ISD::CSEL:
23090     return performCSELCombine(N, DCI, DAG);
23091   case AArch64ISD::DUP:
23092   case AArch64ISD::DUPLANE8:
23093   case AArch64ISD::DUPLANE16:
23094   case AArch64ISD::DUPLANE32:
23095   case AArch64ISD::DUPLANE64:
23096     return performDUPCombine(N, DCI);
23097   case AArch64ISD::DUPLANE128:
23098     return performDupLane128Combine(N, DAG);
23099   case AArch64ISD::NVCAST:
23100     return performNVCASTCombine(N);
23101   case AArch64ISD::SPLICE:
23102     return performSpliceCombine(N, DAG);
23103   case AArch64ISD::UUNPKLO:
23104   case AArch64ISD::UUNPKHI:
23105     return performUnpackCombine(N, DAG, Subtarget);
23106   case AArch64ISD::UZP1:
23107     return performUzpCombine(N, DAG);
23108   case AArch64ISD::SETCC_MERGE_ZERO:
23109     return performSetccMergeZeroCombine(N, DCI);
23110   case AArch64ISD::REINTERPRET_CAST:
23111     return performReinterpretCastCombine(N);
23112   case AArch64ISD::GLD1_MERGE_ZERO:
23113   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
23114   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
23115   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
23116   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
23117   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
23118   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
23119   case AArch64ISD::GLD1S_MERGE_ZERO:
23120   case AArch64ISD::GLD1S_SCALED_MERGE_ZERO:
23121   case AArch64ISD::GLD1S_UXTW_MERGE_ZERO:
23122   case AArch64ISD::GLD1S_SXTW_MERGE_ZERO:
23123   case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO:
23124   case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO:
23125   case AArch64ISD::GLD1S_IMM_MERGE_ZERO:
23126     return performGLD1Combine(N, DAG);
23127   case AArch64ISD::VASHR:
23128   case AArch64ISD::VLSHR:
23129     return performVectorShiftCombine(N, *this, DCI);
23130   case AArch64ISD::SUNPKLO:
23131     return performSunpkloCombine(N, DAG);
23132   case AArch64ISD::BSP:
23133     return performBSPExpandForSVE(N, DAG, Subtarget);
23134   case ISD::INSERT_VECTOR_ELT:
23135     return performInsertVectorEltCombine(N, DCI);
23136   case ISD::EXTRACT_VECTOR_ELT:
23137     return performExtractVectorEltCombine(N, DCI, Subtarget);
23138   case ISD::VECREDUCE_ADD:
23139     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
23140   case AArch64ISD::UADDV:
23141     return performUADDVCombine(N, DAG);
23142   case AArch64ISD::SMULL:
23143   case AArch64ISD::UMULL:
23144   case AArch64ISD::PMULL:
23145     return performMULLCombine(N, DCI, DAG);
23146   case ISD::INTRINSIC_VOID:
23147   case ISD::INTRINSIC_W_CHAIN:
23148     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
23149     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
23150       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
23151     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
23152       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
23153     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
23154       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
23155     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
23156       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
23157     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
23158     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
23159     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
23160     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
23161     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
23162     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
23163     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
23164     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
23165       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
23166     case Intrinsic::aarch64_neon_ld2:
23167     case Intrinsic::aarch64_neon_ld3:
23168     case Intrinsic::aarch64_neon_ld4:
23169     case Intrinsic::aarch64_neon_ld1x2:
23170     case Intrinsic::aarch64_neon_ld1x3:
23171     case Intrinsic::aarch64_neon_ld1x4:
23172     case Intrinsic::aarch64_neon_ld2lane:
23173     case Intrinsic::aarch64_neon_ld3lane:
23174     case Intrinsic::aarch64_neon_ld4lane:
23175     case Intrinsic::aarch64_neon_ld2r:
23176     case Intrinsic::aarch64_neon_ld3r:
23177     case Intrinsic::aarch64_neon_ld4r:
23178     case Intrinsic::aarch64_neon_st2:
23179     case Intrinsic::aarch64_neon_st3:
23180     case Intrinsic::aarch64_neon_st4:
23181     case Intrinsic::aarch64_neon_st1x2:
23182     case Intrinsic::aarch64_neon_st1x3:
23183     case Intrinsic::aarch64_neon_st1x4:
23184     case Intrinsic::aarch64_neon_st2lane:
23185     case Intrinsic::aarch64_neon_st3lane:
23186     case Intrinsic::aarch64_neon_st4lane:
23187       return performNEONPostLDSTCombine(N, DCI, DAG);
23188     case Intrinsic::aarch64_sve_ldnt1:
23189       return performLDNT1Combine(N, DAG);
23190     case Intrinsic::aarch64_sve_ld1rq:
23191       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
23192     case Intrinsic::aarch64_sve_ld1ro:
23193       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
23194     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
23195       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
23196     case Intrinsic::aarch64_sve_ldnt1_gather:
23197       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
23198     case Intrinsic::aarch64_sve_ldnt1_gather_index:
23199       return performGatherLoadCombine(N, DAG,
23200                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
23201     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
23202       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
23203     case Intrinsic::aarch64_sve_ld1:
23204       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
23205     case Intrinsic::aarch64_sve_ldnf1:
23206       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
23207     case Intrinsic::aarch64_sve_ldff1:
23208       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
23209     case Intrinsic::aarch64_sve_st1:
23210       return performST1Combine(N, DAG);
23211     case Intrinsic::aarch64_sve_stnt1:
23212       return performSTNT1Combine(N, DAG);
23213     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
23214       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
23215     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
23216       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
23217     case Intrinsic::aarch64_sve_stnt1_scatter:
23218       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
23219     case Intrinsic::aarch64_sve_stnt1_scatter_index:
23220       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
23221     case Intrinsic::aarch64_sve_ld1_gather:
23222       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
23223     case Intrinsic::aarch64_sve_ld1_gather_index:
23224       return performGatherLoadCombine(N, DAG,
23225                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
23226     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
23227       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
23228                                       /*OnlyPackedOffsets=*/false);
23229     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
23230       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
23231                                       /*OnlyPackedOffsets=*/false);
23232     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
23233       return performGatherLoadCombine(N, DAG,
23234                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
23235                                       /*OnlyPackedOffsets=*/false);
23236     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
23237       return performGatherLoadCombine(N, DAG,
23238                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
23239                                       /*OnlyPackedOffsets=*/false);
23240     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
23241       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
23242     case Intrinsic::aarch64_sve_ldff1_gather:
23243       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
23244     case Intrinsic::aarch64_sve_ldff1_gather_index:
23245       return performGatherLoadCombine(N, DAG,
23246                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
23247     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
23248       return performGatherLoadCombine(N, DAG,
23249                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
23250                                       /*OnlyPackedOffsets=*/false);
23251     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
23252       return performGatherLoadCombine(N, DAG,
23253                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
23254                                       /*OnlyPackedOffsets=*/false);
23255     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
23256       return performGatherLoadCombine(N, DAG,
23257                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
23258                                       /*OnlyPackedOffsets=*/false);
23259     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
23260       return performGatherLoadCombine(N, DAG,
23261                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
23262                                       /*OnlyPackedOffsets=*/false);
23263     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
23264       return performGatherLoadCombine(N, DAG,
23265                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
23266     case Intrinsic::aarch64_sve_st1_scatter:
23267       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
23268     case Intrinsic::aarch64_sve_st1_scatter_index:
23269       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
23270     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
23271       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
23272                                         /*OnlyPackedOffsets=*/false);
23273     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
23274       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
23275                                         /*OnlyPackedOffsets=*/false);
23276     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
23277       return performScatterStoreCombine(N, DAG,
23278                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
23279                                         /*OnlyPackedOffsets=*/false);
23280     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
23281       return performScatterStoreCombine(N, DAG,
23282                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
23283                                         /*OnlyPackedOffsets=*/false);
23284     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
23285       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
23286     case Intrinsic::aarch64_rndr:
23287     case Intrinsic::aarch64_rndrrs: {
23288       unsigned IntrinsicID =
23289           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23290       auto Register =
23291           (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR
23292                                                   : AArch64SysReg::RNDRRS);
23293       SDLoc DL(N);
23294       SDValue A = DAG.getNode(
23295           AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other),
23296           N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64));
23297       SDValue B = DAG.getNode(
23298           AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32),
23299           DAG.getConstant(0, DL, MVT::i32),
23300           DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1));
23301       return DAG.getMergeValues(
23302           {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL);
23303     }
23304     default:
23305       break;
23306     }
23307     break;
23308   case ISD::GlobalAddress:
23309     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
23310   case ISD::CTLZ:
23311     return performCTLZCombine(N, DAG, Subtarget);
23312   }
23313   return SDValue();
23314 }
23315 
23316 // Check if the return value is used as only a return value, as otherwise
23317 // we can't perform a tail-call. In particular, we need to check for
23318 // target ISD nodes that are returns and any other "odd" constructs
23319 // that the generic analysis code won't necessarily catch.
23320 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
23321                                                SDValue &Chain) const {
23322   if (N->getNumValues() != 1)
23323     return false;
23324   if (!N->hasNUsesOfValue(1, 0))
23325     return false;
23326 
23327   SDValue TCChain = Chain;
23328   SDNode *Copy = *N->use_begin();
23329   if (Copy->getOpcode() == ISD::CopyToReg) {
23330     // If the copy has a glue operand, we conservatively assume it isn't safe to
23331     // perform a tail call.
23332     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
23333         MVT::Glue)
23334       return false;
23335     TCChain = Copy->getOperand(0);
23336   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
23337     return false;
23338 
23339   bool HasRet = false;
23340   for (SDNode *Node : Copy->uses()) {
23341     if (Node->getOpcode() != AArch64ISD::RET_GLUE)
23342       return false;
23343     HasRet = true;
23344   }
23345 
23346   if (!HasRet)
23347     return false;
23348 
23349   Chain = TCChain;
23350   return true;
23351 }
23352 
23353 // Return whether the an instruction can potentially be optimized to a tail
23354 // call. This will cause the optimizers to attempt to move, or duplicate,
23355 // return instructions to help enable tail call optimizations for this
23356 // instruction.
23357 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
23358   return CI->isTailCall();
23359 }
23360 
23361 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *N, SDNode *Op,
23362                                                    SDValue &Base,
23363                                                    SDValue &Offset,
23364                                                    SelectionDAG &DAG) const {
23365   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
23366     return false;
23367 
23368   // Non-null if there is exactly one user of the loaded value (ignoring chain).
23369   SDNode *ValOnlyUser = nullptr;
23370   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
23371        ++UI) {
23372     if (UI.getUse().getResNo() == 1)
23373       continue; // Ignore chain.
23374     if (ValOnlyUser == nullptr)
23375       ValOnlyUser = *UI;
23376     else {
23377       ValOnlyUser = nullptr; // Multiple non-chain uses, bail out.
23378       break;
23379     }
23380   }
23381 
23382   auto IsUndefOrZero = [](SDValue V) {
23383     return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
23384   };
23385 
23386   // If the only user of the value is a scalable vector splat, it is
23387   // preferable to do a replicating load (ld1r*).
23388   if (ValOnlyUser && ValOnlyUser->getValueType(0).isScalableVector() &&
23389       (ValOnlyUser->getOpcode() == ISD::SPLAT_VECTOR ||
23390        (ValOnlyUser->getOpcode() == AArch64ISD::DUP_MERGE_PASSTHRU &&
23391         IsUndefOrZero(ValOnlyUser->getOperand(2)))))
23392     return false;
23393 
23394   Base = Op->getOperand(0);
23395   // All of the indexed addressing mode instructions take a signed
23396   // 9 bit immediate offset.
23397   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
23398     int64_t RHSC = RHS->getSExtValue();
23399     if (Op->getOpcode() == ISD::SUB)
23400       RHSC = -(uint64_t)RHSC;
23401     if (!isInt<9>(RHSC))
23402       return false;
23403     // Always emit pre-inc/post-inc addressing mode. Use negated constant offset
23404     // when dealing with subtraction.
23405     Offset = DAG.getConstant(RHSC, SDLoc(N), RHS->getValueType(0));
23406     return true;
23407   }
23408   return false;
23409 }
23410 
23411 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
23412                                                       SDValue &Offset,
23413                                                       ISD::MemIndexedMode &AM,
23414                                                       SelectionDAG &DAG) const {
23415   EVT VT;
23416   SDValue Ptr;
23417   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
23418     VT = LD->getMemoryVT();
23419     Ptr = LD->getBasePtr();
23420   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
23421     VT = ST->getMemoryVT();
23422     Ptr = ST->getBasePtr();
23423   } else
23424     return false;
23425 
23426   if (!getIndexedAddressParts(N, Ptr.getNode(), Base, Offset, DAG))
23427     return false;
23428   AM = ISD::PRE_INC;
23429   return true;
23430 }
23431 
23432 bool AArch64TargetLowering::getPostIndexedAddressParts(
23433     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
23434     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
23435   EVT VT;
23436   SDValue Ptr;
23437   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
23438     VT = LD->getMemoryVT();
23439     Ptr = LD->getBasePtr();
23440   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
23441     VT = ST->getMemoryVT();
23442     Ptr = ST->getBasePtr();
23443   } else
23444     return false;
23445 
23446   if (!getIndexedAddressParts(N, Op, Base, Offset, DAG))
23447     return false;
23448   // Post-indexing updates the base, so it's not a valid transform
23449   // if that's not the same as the load's pointer.
23450   if (Ptr != Base)
23451     return false;
23452   AM = ISD::POST_INC;
23453   return true;
23454 }
23455 
23456 static void replaceBoolVectorBitcast(SDNode *N,
23457                                      SmallVectorImpl<SDValue> &Results,
23458                                      SelectionDAG &DAG) {
23459   SDLoc DL(N);
23460   SDValue Op = N->getOperand(0);
23461   EVT VT = N->getValueType(0);
23462   [[maybe_unused]] EVT SrcVT = Op.getValueType();
23463   assert(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
23464          "Must be bool vector.");
23465 
23466   // Special handling for Clang's __builtin_convertvector. For vectors with <8
23467   // elements, it adds a vector concatenation with undef(s). If we encounter
23468   // this here, we can skip the concat.
23469   if (Op.getOpcode() == ISD::CONCAT_VECTORS && !Op.getOperand(0).isUndef()) {
23470     bool AllUndef = true;
23471     for (unsigned I = 1; I < Op.getNumOperands(); ++I)
23472       AllUndef &= Op.getOperand(I).isUndef();
23473 
23474     if (AllUndef)
23475       Op = Op.getOperand(0);
23476   }
23477 
23478   SDValue VectorBits = vectorToScalarBitmask(Op.getNode(), DAG);
23479   if (VectorBits)
23480     Results.push_back(DAG.getZExtOrTrunc(VectorBits, DL, VT));
23481 }
23482 
23483 static void CustomNonLegalBITCASTResults(SDNode *N,
23484                                          SmallVectorImpl<SDValue> &Results,
23485                                          SelectionDAG &DAG, EVT ExtendVT,
23486                                          EVT CastVT) {
23487   SDLoc DL(N);
23488   SDValue Op = N->getOperand(0);
23489   EVT VT = N->getValueType(0);
23490 
23491   // Use SCALAR_TO_VECTOR for lane zero
23492   SDValue Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtendVT, Op);
23493   SDValue CastVal = DAG.getNode(ISD::BITCAST, DL, CastVT, Vec);
23494   SDValue IdxZero = DAG.getVectorIdxConstant(0, DL);
23495   Results.push_back(
23496       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, CastVal, IdxZero));
23497   return;
23498 }
23499 
23500 void AArch64TargetLowering::ReplaceBITCASTResults(
23501     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
23502   SDLoc DL(N);
23503   SDValue Op = N->getOperand(0);
23504   EVT VT = N->getValueType(0);
23505   EVT SrcVT = Op.getValueType();
23506 
23507   if (VT == MVT::v2i16 && SrcVT == MVT::i32) {
23508     CustomNonLegalBITCASTResults(N, Results, DAG, MVT::v2i32, MVT::v4i16);
23509     return;
23510   }
23511 
23512   if (VT == MVT::v4i8 && SrcVT == MVT::i32) {
23513     CustomNonLegalBITCASTResults(N, Results, DAG, MVT::v2i32, MVT::v8i8);
23514     return;
23515   }
23516 
23517   if (VT == MVT::v2i8 && SrcVT == MVT::i16) {
23518     CustomNonLegalBITCASTResults(N, Results, DAG, MVT::v4i16, MVT::v8i8);
23519     return;
23520   }
23521 
23522   if (VT.isScalableVector() && !isTypeLegal(VT) && isTypeLegal(SrcVT)) {
23523     assert(!VT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
23524            "Expected fp->int bitcast!");
23525 
23526     // Bitcasting between unpacked vector types of different element counts is
23527     // not a NOP because the live elements are laid out differently.
23528     //                01234567
23529     // e.g. nxv2i32 = XX??XX??
23530     //      nxv4f16 = X?X?X?X?
23531     if (VT.getVectorElementCount() != SrcVT.getVectorElementCount())
23532       return;
23533 
23534     SDValue CastResult = getSVESafeBitCast(getSVEContainerType(VT), Op, DAG);
23535     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, CastResult));
23536     return;
23537   }
23538 
23539   if (SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1)
23540     return replaceBoolVectorBitcast(N, Results, DAG);
23541 
23542   if (VT != MVT::i16 || (SrcVT != MVT::f16 && SrcVT != MVT::bf16))
23543     return;
23544 
23545   Op = DAG.getTargetInsertSubreg(AArch64::hsub, DL, MVT::f32,
23546                                  DAG.getUNDEF(MVT::i32), Op);
23547   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
23548   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
23549 }
23550 
23551 static void ReplaceAddWithADDP(SDNode *N, SmallVectorImpl<SDValue> &Results,
23552                                SelectionDAG &DAG,
23553                                const AArch64Subtarget *Subtarget) {
23554   EVT VT = N->getValueType(0);
23555   if (!VT.is256BitVector() ||
23556       (VT.getScalarType().isFloatingPoint() &&
23557        !N->getFlags().hasAllowReassociation()) ||
23558       (VT.getScalarType() == MVT::f16 && !Subtarget->hasFullFP16()))
23559     return;
23560 
23561   SDValue X = N->getOperand(0);
23562   auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(1));
23563   if (!Shuf) {
23564     Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0));
23565     X = N->getOperand(1);
23566     if (!Shuf)
23567       return;
23568   }
23569 
23570   if (Shuf->getOperand(0) != X || !Shuf->getOperand(1)->isUndef())
23571     return;
23572 
23573   // Check the mask is 1,0,3,2,5,4,...
23574   ArrayRef<int> Mask = Shuf->getMask();
23575   for (int I = 0, E = Mask.size(); I < E; I++)
23576     if (Mask[I] != (I % 2 == 0 ? I + 1 : I - 1))
23577       return;
23578 
23579   SDLoc DL(N);
23580   auto LoHi = DAG.SplitVector(X, DL);
23581   assert(LoHi.first.getValueType() == LoHi.second.getValueType());
23582   SDValue Addp = DAG.getNode(AArch64ISD::ADDP, N, LoHi.first.getValueType(),
23583                              LoHi.first, LoHi.second);
23584 
23585   // Shuffle the elements back into order.
23586   SmallVector<int> NMask;
23587   for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I < E; I++) {
23588     NMask.push_back(I);
23589     NMask.push_back(I);
23590   }
23591   Results.push_back(
23592       DAG.getVectorShuffle(VT, DL,
23593                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Addp,
23594                                        DAG.getUNDEF(LoHi.first.getValueType())),
23595                            DAG.getUNDEF(VT), NMask));
23596 }
23597 
23598 static void ReplaceReductionResults(SDNode *N,
23599                                     SmallVectorImpl<SDValue> &Results,
23600                                     SelectionDAG &DAG, unsigned InterOp,
23601                                     unsigned AcrossOp) {
23602   EVT LoVT, HiVT;
23603   SDValue Lo, Hi;
23604   SDLoc dl(N);
23605   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
23606   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
23607   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
23608   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
23609   Results.push_back(SplitVal);
23610 }
23611 
23612 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
23613     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
23614   SDValue In = N->getOperand(0);
23615   EVT InVT = In.getValueType();
23616 
23617   // Common code will handle these just fine.
23618   if (!InVT.isScalableVector() || !InVT.isInteger())
23619     return;
23620 
23621   SDLoc DL(N);
23622   EVT VT = N->getValueType(0);
23623 
23624   // The following checks bail if this is not a halving operation.
23625 
23626   ElementCount ResEC = VT.getVectorElementCount();
23627 
23628   if (InVT.getVectorElementCount() != (ResEC * 2))
23629     return;
23630 
23631   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
23632   if (!CIndex)
23633     return;
23634 
23635   unsigned Index = CIndex->getZExtValue();
23636   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
23637     return;
23638 
23639   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
23640   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
23641 
23642   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
23643   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
23644 }
23645 
23646 // Create an even/odd pair of X registers holding integer value V.
23647 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
23648   SDLoc dl(V.getNode());
23649   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
23650   SDValue VHi = DAG.getAnyExtOrTrunc(
23651       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
23652       dl, MVT::i64);
23653   if (DAG.getDataLayout().isBigEndian())
23654     std::swap (VLo, VHi);
23655   SDValue RegClass =
23656       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
23657   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
23658   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
23659   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
23660   return SDValue(
23661       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
23662 }
23663 
23664 static void ReplaceCMP_SWAP_128Results(SDNode *N,
23665                                        SmallVectorImpl<SDValue> &Results,
23666                                        SelectionDAG &DAG,
23667                                        const AArch64Subtarget *Subtarget) {
23668   assert(N->getValueType(0) == MVT::i128 &&
23669          "AtomicCmpSwap on types less than 128 should be legal");
23670 
23671   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
23672   if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
23673     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
23674     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
23675     SDValue Ops[] = {
23676         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
23677         createGPRPairNode(DAG, N->getOperand(3)), // Store value
23678         N->getOperand(1), // Ptr
23679         N->getOperand(0), // Chain in
23680     };
23681 
23682     unsigned Opcode;
23683     switch (MemOp->getMergedOrdering()) {
23684     case AtomicOrdering::Monotonic:
23685       Opcode = AArch64::CASPX;
23686       break;
23687     case AtomicOrdering::Acquire:
23688       Opcode = AArch64::CASPAX;
23689       break;
23690     case AtomicOrdering::Release:
23691       Opcode = AArch64::CASPLX;
23692       break;
23693     case AtomicOrdering::AcquireRelease:
23694     case AtomicOrdering::SequentiallyConsistent:
23695       Opcode = AArch64::CASPALX;
23696       break;
23697     default:
23698       llvm_unreachable("Unexpected ordering!");
23699     }
23700 
23701     MachineSDNode *CmpSwap = DAG.getMachineNode(
23702         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
23703     DAG.setNodeMemRefs(CmpSwap, {MemOp});
23704 
23705     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
23706     if (DAG.getDataLayout().isBigEndian())
23707       std::swap(SubReg1, SubReg2);
23708     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
23709                                             SDValue(CmpSwap, 0));
23710     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
23711                                             SDValue(CmpSwap, 0));
23712     Results.push_back(
23713         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
23714     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
23715     return;
23716   }
23717 
23718   unsigned Opcode;
23719   switch (MemOp->getMergedOrdering()) {
23720   case AtomicOrdering::Monotonic:
23721     Opcode = AArch64::CMP_SWAP_128_MONOTONIC;
23722     break;
23723   case AtomicOrdering::Acquire:
23724     Opcode = AArch64::CMP_SWAP_128_ACQUIRE;
23725     break;
23726   case AtomicOrdering::Release:
23727     Opcode = AArch64::CMP_SWAP_128_RELEASE;
23728     break;
23729   case AtomicOrdering::AcquireRelease:
23730   case AtomicOrdering::SequentiallyConsistent:
23731     Opcode = AArch64::CMP_SWAP_128;
23732     break;
23733   default:
23734     llvm_unreachable("Unexpected ordering!");
23735   }
23736 
23737   SDLoc DL(N);
23738   auto Desired = DAG.SplitScalar(N->getOperand(2), DL, MVT::i64, MVT::i64);
23739   auto New = DAG.SplitScalar(N->getOperand(3), DL, MVT::i64, MVT::i64);
23740   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
23741                    New.first,        New.second,    N->getOperand(0)};
23742   SDNode *CmpSwap = DAG.getMachineNode(
23743       Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other),
23744       Ops);
23745   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
23746 
23747   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
23748                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
23749   Results.push_back(SDValue(CmpSwap, 3));
23750 }
23751 
23752 static unsigned getAtomicLoad128Opcode(unsigned ISDOpcode,
23753                                        AtomicOrdering Ordering) {
23754   // ATOMIC_LOAD_CLR only appears when lowering ATOMIC_LOAD_AND (see
23755   // LowerATOMIC_LOAD_AND). We can't take that approach with 128-bit, because
23756   // the type is not legal. Therefore we shouldn't expect to see a 128-bit
23757   // ATOMIC_LOAD_CLR at any point.
23758   assert(ISDOpcode != ISD::ATOMIC_LOAD_CLR &&
23759          "ATOMIC_LOAD_AND should be lowered to LDCLRP directly");
23760   assert(ISDOpcode != ISD::ATOMIC_LOAD_ADD && "There is no 128 bit LDADD");
23761   assert(ISDOpcode != ISD::ATOMIC_LOAD_SUB && "There is no 128 bit LDSUB");
23762 
23763   if (ISDOpcode == ISD::ATOMIC_LOAD_AND) {
23764     // The operand will need to be XORed in a separate step.
23765     switch (Ordering) {
23766     case AtomicOrdering::Monotonic:
23767       return AArch64::LDCLRP;
23768       break;
23769     case AtomicOrdering::Acquire:
23770       return AArch64::LDCLRPA;
23771       break;
23772     case AtomicOrdering::Release:
23773       return AArch64::LDCLRPL;
23774       break;
23775     case AtomicOrdering::AcquireRelease:
23776     case AtomicOrdering::SequentiallyConsistent:
23777       return AArch64::LDCLRPAL;
23778       break;
23779     default:
23780       llvm_unreachable("Unexpected ordering!");
23781     }
23782   }
23783 
23784   if (ISDOpcode == ISD::ATOMIC_LOAD_OR) {
23785     switch (Ordering) {
23786     case AtomicOrdering::Monotonic:
23787       return AArch64::LDSETP;
23788       break;
23789     case AtomicOrdering::Acquire:
23790       return AArch64::LDSETPA;
23791       break;
23792     case AtomicOrdering::Release:
23793       return AArch64::LDSETPL;
23794       break;
23795     case AtomicOrdering::AcquireRelease:
23796     case AtomicOrdering::SequentiallyConsistent:
23797       return AArch64::LDSETPAL;
23798       break;
23799     default:
23800       llvm_unreachable("Unexpected ordering!");
23801     }
23802   }
23803 
23804   if (ISDOpcode == ISD::ATOMIC_SWAP) {
23805     switch (Ordering) {
23806     case AtomicOrdering::Monotonic:
23807       return AArch64::SWPP;
23808       break;
23809     case AtomicOrdering::Acquire:
23810       return AArch64::SWPPA;
23811       break;
23812     case AtomicOrdering::Release:
23813       return AArch64::SWPPL;
23814       break;
23815     case AtomicOrdering::AcquireRelease:
23816     case AtomicOrdering::SequentiallyConsistent:
23817       return AArch64::SWPPAL;
23818       break;
23819     default:
23820       llvm_unreachable("Unexpected ordering!");
23821     }
23822   }
23823 
23824   llvm_unreachable("Unexpected ISDOpcode!");
23825 }
23826 
23827 static void ReplaceATOMIC_LOAD_128Results(SDNode *N,
23828                                           SmallVectorImpl<SDValue> &Results,
23829                                           SelectionDAG &DAG,
23830                                           const AArch64Subtarget *Subtarget) {
23831   // LSE128 has a 128-bit RMW ops, but i128 is not a legal type, so lower it
23832   // here. This follows the approach of the CMP_SWAP_XXX pseudo instructions
23833   // rather than the CASP instructions, because CASP has register classes for
23834   // the pairs of registers and therefore uses REG_SEQUENCE and EXTRACT_SUBREG
23835   // to present them as single operands. LSE128 instructions use the GPR64
23836   // register class (because the pair does not have to be sequential), like
23837   // CMP_SWAP_XXX, and therefore we use TRUNCATE and BUILD_PAIR.
23838 
23839   assert(N->getValueType(0) == MVT::i128 &&
23840          "AtomicLoadXXX on types less than 128 should be legal");
23841 
23842   if (!Subtarget->hasLSE128())
23843     return;
23844 
23845   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
23846   const SDValue &Chain = N->getOperand(0);
23847   const SDValue &Ptr = N->getOperand(1);
23848   const SDValue &Val128 = N->getOperand(2);
23849   std::pair<SDValue, SDValue> Val2x64 =
23850       DAG.SplitScalar(Val128, SDLoc(Val128), MVT::i64, MVT::i64);
23851 
23852   const unsigned ISDOpcode = N->getOpcode();
23853   const unsigned MachineOpcode =
23854       getAtomicLoad128Opcode(ISDOpcode, MemOp->getMergedOrdering());
23855 
23856   if (ISDOpcode == ISD::ATOMIC_LOAD_AND) {
23857     SDLoc dl(Val128);
23858     Val2x64.first =
23859         DAG.getNode(ISD::XOR, dl, MVT::i64,
23860                     DAG.getConstant(-1ULL, dl, MVT::i64), Val2x64.first);
23861     Val2x64.second =
23862         DAG.getNode(ISD::XOR, dl, MVT::i64,
23863                     DAG.getConstant(-1ULL, dl, MVT::i64), Val2x64.second);
23864   }
23865 
23866   SDValue Ops[] = {Val2x64.first, Val2x64.second, Ptr, Chain};
23867   if (DAG.getDataLayout().isBigEndian())
23868     std::swap(Ops[0], Ops[1]);
23869 
23870   MachineSDNode *AtomicInst =
23871       DAG.getMachineNode(MachineOpcode, SDLoc(N),
23872                          DAG.getVTList(MVT::i64, MVT::i64, MVT::Other), Ops);
23873 
23874   DAG.setNodeMemRefs(AtomicInst, {MemOp});
23875 
23876   SDValue Lo = SDValue(AtomicInst, 0), Hi = SDValue(AtomicInst, 1);
23877   if (DAG.getDataLayout().isBigEndian())
23878     std::swap(Lo, Hi);
23879 
23880   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
23881   Results.push_back(SDValue(AtomicInst, 2)); // Chain out
23882 }
23883 
23884 void AArch64TargetLowering::ReplaceNodeResults(
23885     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
23886   switch (N->getOpcode()) {
23887   default:
23888     llvm_unreachable("Don't know how to custom expand this");
23889   case ISD::BITCAST:
23890     ReplaceBITCASTResults(N, Results, DAG);
23891     return;
23892   case ISD::VECREDUCE_ADD:
23893   case ISD::VECREDUCE_SMAX:
23894   case ISD::VECREDUCE_SMIN:
23895   case ISD::VECREDUCE_UMAX:
23896   case ISD::VECREDUCE_UMIN:
23897     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
23898     return;
23899   case ISD::ADD:
23900   case ISD::FADD:
23901     ReplaceAddWithADDP(N, Results, DAG, Subtarget);
23902     return;
23903 
23904   case ISD::CTPOP:
23905   case ISD::PARITY:
23906     if (SDValue Result = LowerCTPOP_PARITY(SDValue(N, 0), DAG))
23907       Results.push_back(Result);
23908     return;
23909   case AArch64ISD::SADDV:
23910     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
23911     return;
23912   case AArch64ISD::UADDV:
23913     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
23914     return;
23915   case AArch64ISD::SMINV:
23916     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
23917     return;
23918   case AArch64ISD::UMINV:
23919     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
23920     return;
23921   case AArch64ISD::SMAXV:
23922     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
23923     return;
23924   case AArch64ISD::UMAXV:
23925     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
23926     return;
23927   case ISD::MULHS:
23928     if (useSVEForFixedLengthVectorVT(SDValue(N, 0).getValueType()))
23929       Results.push_back(
23930           LowerToPredicatedOp(SDValue(N, 0), DAG, AArch64ISD::MULHS_PRED));
23931     return;
23932   case ISD::MULHU:
23933     if (useSVEForFixedLengthVectorVT(SDValue(N, 0).getValueType()))
23934       Results.push_back(
23935           LowerToPredicatedOp(SDValue(N, 0), DAG, AArch64ISD::MULHU_PRED));
23936     return;
23937   case ISD::FP_TO_UINT:
23938   case ISD::FP_TO_SINT:
23939   case ISD::STRICT_FP_TO_SINT:
23940   case ISD::STRICT_FP_TO_UINT:
23941     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
23942     // Let normal code take care of it by not adding anything to Results.
23943     return;
23944   case ISD::ATOMIC_CMP_SWAP:
23945     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
23946     return;
23947   case ISD::ATOMIC_LOAD_CLR:
23948     assert(N->getValueType(0) != MVT::i128 &&
23949            "128-bit ATOMIC_LOAD_AND should be lowered directly to LDCLRP");
23950     break;
23951   case ISD::ATOMIC_LOAD_AND:
23952   case ISD::ATOMIC_LOAD_OR:
23953   case ISD::ATOMIC_SWAP: {
23954     assert(cast<AtomicSDNode>(N)->getVal().getValueType() == MVT::i128 &&
23955            "Expected 128-bit atomicrmw.");
23956     // These need custom type legalisation so we go directly to instruction.
23957     ReplaceATOMIC_LOAD_128Results(N, Results, DAG, Subtarget);
23958     return;
23959   }
23960   case ISD::ATOMIC_LOAD:
23961   case ISD::LOAD: {
23962     MemSDNode *LoadNode = cast<MemSDNode>(N);
23963     EVT MemVT = LoadNode->getMemoryVT();
23964     // Handle lowering 256 bit non temporal loads into LDNP for little-endian
23965     // targets.
23966     if (LoadNode->isNonTemporal() && Subtarget->isLittleEndian() &&
23967         MemVT.getSizeInBits() == 256u &&
23968         (MemVT.getScalarSizeInBits() == 8u ||
23969          MemVT.getScalarSizeInBits() == 16u ||
23970          MemVT.getScalarSizeInBits() == 32u ||
23971          MemVT.getScalarSizeInBits() == 64u)) {
23972 
23973       SDValue Result = DAG.getMemIntrinsicNode(
23974           AArch64ISD::LDNP, SDLoc(N),
23975           DAG.getVTList({MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
23976                          MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
23977                          MVT::Other}),
23978           {LoadNode->getChain(), LoadNode->getBasePtr()},
23979           LoadNode->getMemoryVT(), LoadNode->getMemOperand());
23980 
23981       SDValue Pair = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), MemVT,
23982                                  Result.getValue(0), Result.getValue(1));
23983       Results.append({Pair, Result.getValue(2) /* Chain */});
23984       return;
23985     }
23986 
23987     if ((!LoadNode->isVolatile() && !LoadNode->isAtomic()) ||
23988         LoadNode->getMemoryVT() != MVT::i128) {
23989       // Non-volatile or atomic loads are optimized later in AArch64's load/store
23990       // optimizer.
23991       return;
23992     }
23993 
23994     if (SDValue(N, 0).getValueType() == MVT::i128) {
23995       auto *AN = dyn_cast<AtomicSDNode>(LoadNode);
23996       bool isLoadAcquire =
23997           AN && AN->getSuccessOrdering() == AtomicOrdering::Acquire;
23998       unsigned Opcode = isLoadAcquire ? AArch64ISD::LDIAPP : AArch64ISD::LDP;
23999 
24000       if (isLoadAcquire)
24001         assert(Subtarget->hasFeature(AArch64::FeatureRCPC3));
24002 
24003       SDValue Result = DAG.getMemIntrinsicNode(
24004           Opcode, SDLoc(N), DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
24005           {LoadNode->getChain(), LoadNode->getBasePtr()},
24006           LoadNode->getMemoryVT(), LoadNode->getMemOperand());
24007 
24008       SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
24009                                  Result.getValue(0), Result.getValue(1));
24010       Results.append({Pair, Result.getValue(2) /* Chain */});
24011     }
24012     return;
24013   }
24014   case ISD::EXTRACT_SUBVECTOR:
24015     ReplaceExtractSubVectorResults(N, Results, DAG);
24016     return;
24017   case ISD::INSERT_SUBVECTOR:
24018   case ISD::CONCAT_VECTORS:
24019     // Custom lowering has been requested for INSERT_SUBVECTOR and
24020     // CONCAT_VECTORS -- but delegate to common code for result type
24021     // legalisation
24022     return;
24023   case ISD::INTRINSIC_WO_CHAIN: {
24024     EVT VT = N->getValueType(0);
24025     assert((VT == MVT::i8 || VT == MVT::i16) &&
24026            "custom lowering for unexpected type");
24027 
24028     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
24029     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
24030     switch (IntID) {
24031     default:
24032       return;
24033     case Intrinsic::aarch64_sve_clasta_n: {
24034       SDLoc DL(N);
24035       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
24036       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
24037                            N->getOperand(1), Op2, N->getOperand(3));
24038       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
24039       return;
24040     }
24041     case Intrinsic::aarch64_sve_clastb_n: {
24042       SDLoc DL(N);
24043       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
24044       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
24045                            N->getOperand(1), Op2, N->getOperand(3));
24046       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
24047       return;
24048     }
24049     case Intrinsic::aarch64_sve_lasta: {
24050       SDLoc DL(N);
24051       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
24052                            N->getOperand(1), N->getOperand(2));
24053       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
24054       return;
24055     }
24056     case Intrinsic::aarch64_sve_lastb: {
24057       SDLoc DL(N);
24058       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
24059                            N->getOperand(1), N->getOperand(2));
24060       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
24061       return;
24062     }
24063     }
24064   }
24065   case ISD::READ_REGISTER: {
24066     SDLoc DL(N);
24067     assert(N->getValueType(0) == MVT::i128 &&
24068            "READ_REGISTER custom lowering is only for 128-bit sysregs");
24069     SDValue Chain = N->getOperand(0);
24070     SDValue SysRegName = N->getOperand(1);
24071 
24072     SDValue Result = DAG.getNode(
24073         AArch64ISD::MRRS, DL, DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
24074         Chain, SysRegName);
24075 
24076     // Sysregs are not endian. Result.getValue(0) always contains the lower half
24077     // of the 128-bit System Register value.
24078     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
24079                                Result.getValue(0), Result.getValue(1));
24080     Results.push_back(Pair);
24081     Results.push_back(Result.getValue(2)); // Chain
24082     return;
24083   }
24084   }
24085 }
24086 
24087 bool AArch64TargetLowering::useLoadStackGuardNode() const {
24088   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
24089     return TargetLowering::useLoadStackGuardNode();
24090   return true;
24091 }
24092 
24093 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
24094   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
24095   // reciprocal if there are three or more FDIVs.
24096   return 3;
24097 }
24098 
24099 TargetLoweringBase::LegalizeTypeAction
24100 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
24101   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
24102   // v4i16, v2i32 instead of to promote.
24103   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
24104       VT == MVT::v1f32)
24105     return TypeWidenVector;
24106 
24107   return TargetLoweringBase::getPreferredVectorAction(VT);
24108 }
24109 
24110 // In v8.4a, ldp and stp instructions are guaranteed to be single-copy atomic
24111 // provided the address is 16-byte aligned.
24112 bool AArch64TargetLowering::isOpSuitableForLDPSTP(const Instruction *I) const {
24113   if (!Subtarget->hasLSE2())
24114     return false;
24115 
24116   if (auto LI = dyn_cast<LoadInst>(I))
24117     return LI->getType()->getPrimitiveSizeInBits() == 128 &&
24118            LI->getAlign() >= Align(16);
24119 
24120   if (auto SI = dyn_cast<StoreInst>(I))
24121     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
24122            SI->getAlign() >= Align(16);
24123 
24124   return false;
24125 }
24126 
24127 bool AArch64TargetLowering::isOpSuitableForLSE128(const Instruction *I) const {
24128   if (!Subtarget->hasLSE128())
24129     return false;
24130 
24131   // Only use SWPP for stores where LSE2 would require a fence. Unlike STP, SWPP
24132   // will clobber the two registers.
24133   if (const auto *SI = dyn_cast<StoreInst>(I))
24134     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
24135            SI->getAlign() >= Align(16) &&
24136            (SI->getOrdering() == AtomicOrdering::Release ||
24137             SI->getOrdering() == AtomicOrdering::SequentiallyConsistent);
24138 
24139   if (const auto *RMW = dyn_cast<AtomicRMWInst>(I))
24140     return RMW->getValOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
24141            RMW->getAlign() >= Align(16) &&
24142            (RMW->getOperation() == AtomicRMWInst::Xchg ||
24143             RMW->getOperation() == AtomicRMWInst::And ||
24144             RMW->getOperation() == AtomicRMWInst::Or);
24145 
24146   return false;
24147 }
24148 
24149 bool AArch64TargetLowering::isOpSuitableForRCPC3(const Instruction *I) const {
24150   if (!Subtarget->hasLSE2() || !Subtarget->hasRCPC3())
24151     return false;
24152 
24153   if (auto LI = dyn_cast<LoadInst>(I))
24154     return LI->getType()->getPrimitiveSizeInBits() == 128 &&
24155            LI->getAlign() >= Align(16) &&
24156            LI->getOrdering() == AtomicOrdering::Acquire;
24157 
24158   if (auto SI = dyn_cast<StoreInst>(I))
24159     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
24160            SI->getAlign() >= Align(16) &&
24161            SI->getOrdering() == AtomicOrdering::Release;
24162 
24163   return false;
24164 }
24165 
24166 bool AArch64TargetLowering::shouldInsertFencesForAtomic(
24167     const Instruction *I) const {
24168   if (isOpSuitableForRCPC3(I))
24169     return false;
24170   if (isOpSuitableForLSE128(I))
24171     return false;
24172   if (isOpSuitableForLDPSTP(I))
24173     return true;
24174   return false;
24175 }
24176 
24177 bool AArch64TargetLowering::shouldInsertTrailingFenceForAtomicStore(
24178     const Instruction *I) const {
24179   // Store-Release instructions only provide seq_cst guarantees when paired with
24180   // Load-Acquire instructions. MSVC CRT does not use these instructions to
24181   // implement seq_cst loads and stores, so we need additional explicit fences
24182   // after memory writes.
24183   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
24184     return false;
24185 
24186   switch (I->getOpcode()) {
24187   default:
24188     return false;
24189   case Instruction::AtomicCmpXchg:
24190     return cast<AtomicCmpXchgInst>(I)->getSuccessOrdering() ==
24191            AtomicOrdering::SequentiallyConsistent;
24192   case Instruction::AtomicRMW:
24193     return cast<AtomicRMWInst>(I)->getOrdering() ==
24194            AtomicOrdering::SequentiallyConsistent;
24195   case Instruction::Store:
24196     return cast<StoreInst>(I)->getOrdering() ==
24197            AtomicOrdering::SequentiallyConsistent;
24198   }
24199 }
24200 
24201 // Loads and stores less than 128-bits are already atomic; ones above that
24202 // are doomed anyway, so defer to the default libcall and blame the OS when
24203 // things go wrong.
24204 TargetLoweringBase::AtomicExpansionKind
24205 AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
24206   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
24207   if (Size != 128)
24208     return AtomicExpansionKind::None;
24209   if (isOpSuitableForRCPC3(SI))
24210     return AtomicExpansionKind::None;
24211   if (isOpSuitableForLSE128(SI))
24212     return AtomicExpansionKind::Expand;
24213   if (isOpSuitableForLDPSTP(SI))
24214     return AtomicExpansionKind::None;
24215   return AtomicExpansionKind::Expand;
24216 }
24217 
24218 // Loads and stores less than 128-bits are already atomic; ones above that
24219 // are doomed anyway, so defer to the default libcall and blame the OS when
24220 // things go wrong.
24221 TargetLowering::AtomicExpansionKind
24222 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
24223   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
24224 
24225   if (Size != 128)
24226     return AtomicExpansionKind::None;
24227   if (isOpSuitableForRCPC3(LI))
24228     return AtomicExpansionKind::None;
24229   // No LSE128 loads
24230   if (isOpSuitableForLDPSTP(LI))
24231     return AtomicExpansionKind::None;
24232 
24233   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
24234   // implement atomicrmw without spilling. If the target address is also on the
24235   // stack and close enough to the spill slot, this can lead to a situation
24236   // where the monitor always gets cleared and the atomic operation can never
24237   // succeed. So at -O0 lower this operation to a CAS loop.
24238   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
24239     return AtomicExpansionKind::CmpXChg;
24240 
24241   // Using CAS for an atomic load has a better chance of succeeding under high
24242   // contention situations. So use it if available.
24243   return Subtarget->hasLSE() ? AtomicExpansionKind::CmpXChg
24244                              : AtomicExpansionKind::LLSC;
24245 }
24246 
24247 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
24248 TargetLowering::AtomicExpansionKind
24249 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
24250   if (AI->isFloatingPointOperation())
24251     return AtomicExpansionKind::CmpXChg;
24252 
24253   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
24254   if (Size > 128) return AtomicExpansionKind::None;
24255 
24256   bool CanUseLSE128 = Subtarget->hasLSE128() && Size == 128 &&
24257                       (AI->getOperation() == AtomicRMWInst::Xchg ||
24258                        AI->getOperation() == AtomicRMWInst::Or ||
24259                        AI->getOperation() == AtomicRMWInst::And);
24260   if (CanUseLSE128)
24261     return AtomicExpansionKind::None;
24262 
24263   // Nand is not supported in LSE.
24264   // Leave 128 bits to LLSC or CmpXChg.
24265   if (AI->getOperation() != AtomicRMWInst::Nand && Size < 128) {
24266     if (Subtarget->hasLSE())
24267       return AtomicExpansionKind::None;
24268     if (Subtarget->outlineAtomics()) {
24269       // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
24270       // Don't outline them unless
24271       // (1) high level <atomic> support approved:
24272       //   http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
24273       // (2) low level libgcc and compiler-rt support implemented by:
24274       //   min/max outline atomics helpers
24275       if (AI->getOperation() != AtomicRMWInst::Min &&
24276           AI->getOperation() != AtomicRMWInst::Max &&
24277           AI->getOperation() != AtomicRMWInst::UMin &&
24278           AI->getOperation() != AtomicRMWInst::UMax) {
24279         return AtomicExpansionKind::None;
24280       }
24281     }
24282   }
24283 
24284   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
24285   // implement atomicrmw without spilling. If the target address is also on the
24286   // stack and close enough to the spill slot, this can lead to a situation
24287   // where the monitor always gets cleared and the atomic operation can never
24288   // succeed. So at -O0 lower this operation to a CAS loop. Also worthwhile if
24289   // we have a single CAS instruction that can replace the loop.
24290   if (getTargetMachine().getOptLevel() == CodeGenOpt::None ||
24291       Subtarget->hasLSE())
24292     return AtomicExpansionKind::CmpXChg;
24293 
24294   return AtomicExpansionKind::LLSC;
24295 }
24296 
24297 TargetLowering::AtomicExpansionKind
24298 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
24299     AtomicCmpXchgInst *AI) const {
24300   // If subtarget has LSE, leave cmpxchg intact for codegen.
24301   if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
24302     return AtomicExpansionKind::None;
24303   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
24304   // implement cmpxchg without spilling. If the address being exchanged is also
24305   // on the stack and close enough to the spill slot, this can lead to a
24306   // situation where the monitor always gets cleared and the atomic operation
24307   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
24308   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
24309     return AtomicExpansionKind::None;
24310 
24311   // 128-bit atomic cmpxchg is weird; AtomicExpand doesn't know how to expand
24312   // it.
24313   unsigned Size = AI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
24314   if (Size > 64)
24315     return AtomicExpansionKind::None;
24316 
24317   return AtomicExpansionKind::LLSC;
24318 }
24319 
24320 Value *AArch64TargetLowering::emitLoadLinked(IRBuilderBase &Builder,
24321                                              Type *ValueTy, Value *Addr,
24322                                              AtomicOrdering Ord) const {
24323   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
24324   bool IsAcquire = isAcquireOrStronger(Ord);
24325 
24326   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
24327   // intrinsic must return {i64, i64} and we have to recombine them into a
24328   // single i128 here.
24329   if (ValueTy->getPrimitiveSizeInBits() == 128) {
24330     Intrinsic::ID Int =
24331         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
24332     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
24333 
24334     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
24335     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
24336 
24337     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
24338     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
24339     Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
24340     Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
24341     return Builder.CreateOr(
24342         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 64)), "val64");
24343   }
24344 
24345   Type *Tys[] = { Addr->getType() };
24346   Intrinsic::ID Int =
24347       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
24348   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
24349 
24350   const DataLayout &DL = M->getDataLayout();
24351   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(ValueTy));
24352   CallInst *CI = Builder.CreateCall(Ldxr, Addr);
24353   CI->addParamAttr(
24354       0, Attribute::get(Builder.getContext(), Attribute::ElementType, ValueTy));
24355   Value *Trunc = Builder.CreateTrunc(CI, IntEltTy);
24356 
24357   return Builder.CreateBitCast(Trunc, ValueTy);
24358 }
24359 
24360 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
24361     IRBuilderBase &Builder) const {
24362   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
24363   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
24364 }
24365 
24366 Value *AArch64TargetLowering::emitStoreConditional(IRBuilderBase &Builder,
24367                                                    Value *Val, Value *Addr,
24368                                                    AtomicOrdering Ord) const {
24369   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
24370   bool IsRelease = isReleaseOrStronger(Ord);
24371 
24372   // Since the intrinsics must have legal type, the i128 intrinsics take two
24373   // parameters: "i64, i64". We must marshal Val into the appropriate form
24374   // before the call.
24375   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
24376     Intrinsic::ID Int =
24377         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
24378     Function *Stxr = Intrinsic::getDeclaration(M, Int);
24379     Type *Int64Ty = Type::getInt64Ty(M->getContext());
24380 
24381     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
24382     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
24383     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
24384     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
24385   }
24386 
24387   Intrinsic::ID Int =
24388       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
24389   Type *Tys[] = { Addr->getType() };
24390   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
24391 
24392   const DataLayout &DL = M->getDataLayout();
24393   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
24394   Val = Builder.CreateBitCast(Val, IntValTy);
24395 
24396   CallInst *CI = Builder.CreateCall(
24397       Stxr, {Builder.CreateZExtOrBitCast(
24398                  Val, Stxr->getFunctionType()->getParamType(0)),
24399              Addr});
24400   CI->addParamAttr(1, Attribute::get(Builder.getContext(),
24401                                      Attribute::ElementType, Val->getType()));
24402   return CI;
24403 }
24404 
24405 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
24406     Type *Ty, CallingConv::ID CallConv, bool isVarArg,
24407     const DataLayout &DL) const {
24408   if (!Ty->isArrayTy()) {
24409     const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
24410     return TySize.isScalable() && TySize.getKnownMinValue() > 128;
24411   }
24412 
24413   // All non aggregate members of the type must have the same type
24414   SmallVector<EVT> ValueVTs;
24415   ComputeValueVTs(*this, DL, Ty, ValueVTs);
24416   return all_equal(ValueVTs);
24417 }
24418 
24419 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
24420                                                             EVT) const {
24421   return false;
24422 }
24423 
24424 static Value *UseTlsOffset(IRBuilderBase &IRB, unsigned Offset) {
24425   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
24426   Function *ThreadPointerFunc =
24427       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
24428   return IRB.CreatePointerCast(
24429       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
24430                              Offset),
24431       IRB.getInt8PtrTy()->getPointerTo(0));
24432 }
24433 
24434 Value *AArch64TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
24435   // Android provides a fixed TLS slot for the stack cookie. See the definition
24436   // of TLS_SLOT_STACK_GUARD in
24437   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
24438   if (Subtarget->isTargetAndroid())
24439     return UseTlsOffset(IRB, 0x28);
24440 
24441   // Fuchsia is similar.
24442   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
24443   if (Subtarget->isTargetFuchsia())
24444     return UseTlsOffset(IRB, -0x10);
24445 
24446   return TargetLowering::getIRStackGuard(IRB);
24447 }
24448 
24449 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
24450   // MSVC CRT provides functionalities for stack protection.
24451   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
24452     // MSVC CRT has a global variable holding security cookie.
24453     M.getOrInsertGlobal("__security_cookie",
24454                         Type::getInt8PtrTy(M.getContext()));
24455 
24456     // MSVC CRT has a function to validate security cookie.
24457     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
24458         Subtarget->getSecurityCheckCookieName(),
24459         Type::getVoidTy(M.getContext()), Type::getInt8PtrTy(M.getContext()));
24460     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
24461       F->setCallingConv(CallingConv::Win64);
24462       F->addParamAttr(0, Attribute::AttrKind::InReg);
24463     }
24464     return;
24465   }
24466   TargetLowering::insertSSPDeclarations(M);
24467 }
24468 
24469 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
24470   // MSVC CRT has a global variable holding security cookie.
24471   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
24472     return M.getGlobalVariable("__security_cookie");
24473   return TargetLowering::getSDagStackGuard(M);
24474 }
24475 
24476 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
24477   // MSVC CRT has a function to validate security cookie.
24478   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
24479     return M.getFunction(Subtarget->getSecurityCheckCookieName());
24480   return TargetLowering::getSSPStackGuardCheck(M);
24481 }
24482 
24483 Value *
24484 AArch64TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
24485   // Android provides a fixed TLS slot for the SafeStack pointer. See the
24486   // definition of TLS_SLOT_SAFESTACK in
24487   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
24488   if (Subtarget->isTargetAndroid())
24489     return UseTlsOffset(IRB, 0x48);
24490 
24491   // Fuchsia is similar.
24492   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
24493   if (Subtarget->isTargetFuchsia())
24494     return UseTlsOffset(IRB, -0x8);
24495 
24496   return TargetLowering::getSafeStackPointerLocation(IRB);
24497 }
24498 
24499 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
24500     const Instruction &AndI) const {
24501   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
24502   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
24503   // may be beneficial to sink in other cases, but we would have to check that
24504   // the cmp would not get folded into the br to form a cbz for these to be
24505   // beneficial.
24506   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
24507   if (!Mask)
24508     return false;
24509   return Mask->getValue().isPowerOf2();
24510 }
24511 
24512 bool AArch64TargetLowering::
24513     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
24514         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
24515         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
24516         SelectionDAG &DAG) const {
24517   // Does baseline recommend not to perform the fold by default?
24518   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
24519           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
24520     return false;
24521   // Else, if this is a vector shift, prefer 'shl'.
24522   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
24523 }
24524 
24525 TargetLowering::ShiftLegalizationStrategy
24526 AArch64TargetLowering::preferredShiftLegalizationStrategy(
24527     SelectionDAG &DAG, SDNode *N, unsigned int ExpansionFactor) const {
24528   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
24529       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
24530     return ShiftLegalizationStrategy::LowerToLibcall;
24531   return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
24532                                                             ExpansionFactor);
24533 }
24534 
24535 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
24536   // Update IsSplitCSR in AArch64unctionInfo.
24537   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
24538   AFI->setIsSplitCSR(true);
24539 }
24540 
24541 void AArch64TargetLowering::insertCopiesSplitCSR(
24542     MachineBasicBlock *Entry,
24543     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
24544   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
24545   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
24546   if (!IStart)
24547     return;
24548 
24549   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
24550   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
24551   MachineBasicBlock::iterator MBBI = Entry->begin();
24552   for (const MCPhysReg *I = IStart; *I; ++I) {
24553     const TargetRegisterClass *RC = nullptr;
24554     if (AArch64::GPR64RegClass.contains(*I))
24555       RC = &AArch64::GPR64RegClass;
24556     else if (AArch64::FPR64RegClass.contains(*I))
24557       RC = &AArch64::FPR64RegClass;
24558     else
24559       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
24560 
24561     Register NewVR = MRI->createVirtualRegister(RC);
24562     // Create copy from CSR to a virtual register.
24563     // FIXME: this currently does not emit CFI pseudo-instructions, it works
24564     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
24565     // nounwind. If we want to generalize this later, we may need to emit
24566     // CFI pseudo-instructions.
24567     assert(Entry->getParent()->getFunction().hasFnAttribute(
24568                Attribute::NoUnwind) &&
24569            "Function should be nounwind in insertCopiesSplitCSR!");
24570     Entry->addLiveIn(*I);
24571     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
24572         .addReg(*I);
24573 
24574     // Insert the copy-back instructions right before the terminator.
24575     for (auto *Exit : Exits)
24576       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
24577               TII->get(TargetOpcode::COPY), *I)
24578           .addReg(NewVR);
24579   }
24580 }
24581 
24582 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
24583   // Integer division on AArch64 is expensive. However, when aggressively
24584   // optimizing for code size, we prefer to use a div instruction, as it is
24585   // usually smaller than the alternative sequence.
24586   // The exception to this is vector division. Since AArch64 doesn't have vector
24587   // integer division, leaving the division as-is is a loss even in terms of
24588   // size, because it will have to be scalarized, while the alternative code
24589   // sequence can be performed in vector form.
24590   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
24591   return OptSize && !VT.isVector();
24592 }
24593 
24594 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
24595   // We want inc-of-add for scalars and sub-of-not for vectors.
24596   return VT.isScalarInteger();
24597 }
24598 
24599 bool AArch64TargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
24600                                                  EVT VT) const {
24601   // v8f16 without fp16 need to be extended to v8f32, which is more difficult to
24602   // legalize.
24603   if (FPVT == MVT::v8f16 && !Subtarget->hasFullFP16())
24604     return false;
24605   return TargetLowering::shouldConvertFpToSat(Op, FPVT, VT);
24606 }
24607 
24608 MachineInstr *
24609 AArch64TargetLowering::EmitKCFICheck(MachineBasicBlock &MBB,
24610                                      MachineBasicBlock::instr_iterator &MBBI,
24611                                      const TargetInstrInfo *TII) const {
24612   assert(MBBI->isCall() && MBBI->getCFIType() &&
24613          "Invalid call instruction for a KCFI check");
24614 
24615   switch (MBBI->getOpcode()) {
24616   case AArch64::BLR:
24617   case AArch64::BLRNoIP:
24618   case AArch64::TCRETURNri:
24619   case AArch64::TCRETURNriBTI:
24620     break;
24621   default:
24622     llvm_unreachable("Unexpected CFI call opcode");
24623   }
24624 
24625   MachineOperand &Target = MBBI->getOperand(0);
24626   assert(Target.isReg() && "Invalid target operand for an indirect call");
24627   Target.setIsRenamable(false);
24628 
24629   return BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(AArch64::KCFI_CHECK))
24630       .addReg(Target.getReg())
24631       .addImm(MBBI->getCFIType())
24632       .getInstr();
24633 }
24634 
24635 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
24636   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
24637 }
24638 
24639 unsigned
24640 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
24641   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
24642     return getPointerTy(DL).getSizeInBits();
24643 
24644   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
24645 }
24646 
24647 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
24648   MachineFrameInfo &MFI = MF.getFrameInfo();
24649   // If we have any vulnerable SVE stack objects then the stack protector
24650   // needs to be placed at the top of the SVE stack area, as the SVE locals
24651   // are placed above the other locals, so we allocate it as if it were a
24652   // scalable vector.
24653   // FIXME: It may be worthwhile having a specific interface for this rather
24654   // than doing it here in finalizeLowering.
24655   if (MFI.hasStackProtectorIndex()) {
24656     for (unsigned int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
24657       if (MFI.getStackID(i) == TargetStackID::ScalableVector &&
24658           MFI.getObjectSSPLayout(i) != MachineFrameInfo::SSPLK_None) {
24659         MFI.setStackID(MFI.getStackProtectorIndex(),
24660                        TargetStackID::ScalableVector);
24661         MFI.setObjectAlignment(MFI.getStackProtectorIndex(), Align(16));
24662         break;
24663       }
24664     }
24665   }
24666   MFI.computeMaxCallFrameSize(MF);
24667   TargetLoweringBase::finalizeLowering(MF);
24668 }
24669 
24670 // Unlike X86, we let frame lowering assign offsets to all catch objects.
24671 bool AArch64TargetLowering::needsFixedCatchObjects() const {
24672   return false;
24673 }
24674 
24675 bool AArch64TargetLowering::shouldLocalize(
24676     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
24677   auto &MF = *MI.getMF();
24678   auto &MRI = MF.getRegInfo();
24679   auto maxUses = [](unsigned RematCost) {
24680     // A cost of 1 means remats are basically free.
24681     if (RematCost == 1)
24682       return std::numeric_limits<unsigned>::max();
24683     if (RematCost == 2)
24684       return 2U;
24685 
24686     // Remat is too expensive, only sink if there's one user.
24687     if (RematCost > 2)
24688       return 1U;
24689     llvm_unreachable("Unexpected remat cost");
24690   };
24691 
24692   switch (MI.getOpcode()) {
24693   case TargetOpcode::G_GLOBAL_VALUE: {
24694     // On Darwin, TLS global vars get selected into function calls, which
24695     // we don't want localized, as they can get moved into the middle of a
24696     // another call sequence.
24697     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
24698     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
24699       return false;
24700     return true; // Always localize G_GLOBAL_VALUE to avoid high reg pressure.
24701   }
24702   case TargetOpcode::G_CONSTANT: {
24703     auto *CI = MI.getOperand(1).getCImm();
24704     APInt Imm = CI->getValue();
24705     InstructionCost Cost = TTI->getIntImmCost(
24706         Imm, CI->getType(), TargetTransformInfo::TCK_CodeSize);
24707     assert(Cost.isValid() && "Expected a valid imm cost");
24708 
24709     unsigned RematCost = *Cost.getValue();
24710     Register Reg = MI.getOperand(0).getReg();
24711     unsigned MaxUses = maxUses(RematCost);
24712     // Don't pass UINT_MAX sentinal value to hasAtMostUserInstrs().
24713     if (MaxUses == std::numeric_limits<unsigned>::max())
24714       --MaxUses;
24715     return MRI.hasAtMostUserInstrs(Reg, MaxUses);
24716   }
24717   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
24718   // localizable.
24719   case AArch64::ADRP:
24720   case AArch64::G_ADD_LOW:
24721   // Need to localize G_PTR_ADD so that G_GLOBAL_VALUE can be localized too.
24722   case TargetOpcode::G_PTR_ADD:
24723     return true;
24724   default:
24725     break;
24726   }
24727   return TargetLoweringBase::shouldLocalize(MI, TTI);
24728 }
24729 
24730 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
24731   if (Inst.getType()->isScalableTy())
24732     return true;
24733 
24734   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
24735     if (Inst.getOperand(i)->getType()->isScalableTy())
24736       return true;
24737 
24738   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
24739     if (AI->getAllocatedType()->isScalableTy())
24740       return true;
24741   }
24742 
24743   // Checks to allow the use of SME instructions
24744   if (auto *Base = dyn_cast<CallBase>(&Inst)) {
24745     auto CallerAttrs = SMEAttrs(*Inst.getFunction());
24746     auto CalleeAttrs = SMEAttrs(*Base);
24747     if (CallerAttrs.requiresSMChange(CalleeAttrs,
24748                                      /*BodyOverridesInterface=*/false) ||
24749         CallerAttrs.requiresLazySave(CalleeAttrs))
24750       return true;
24751   }
24752   return false;
24753 }
24754 
24755 // Return the largest legal scalable vector type that matches VT's element type.
24756 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
24757   assert(VT.isFixedLengthVector() &&
24758          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
24759          "Expected legal fixed length vector!");
24760   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
24761   default:
24762     llvm_unreachable("unexpected element type for SVE container");
24763   case MVT::i8:
24764     return EVT(MVT::nxv16i8);
24765   case MVT::i16:
24766     return EVT(MVT::nxv8i16);
24767   case MVT::i32:
24768     return EVT(MVT::nxv4i32);
24769   case MVT::i64:
24770     return EVT(MVT::nxv2i64);
24771   case MVT::f16:
24772     return EVT(MVT::nxv8f16);
24773   case MVT::f32:
24774     return EVT(MVT::nxv4f32);
24775   case MVT::f64:
24776     return EVT(MVT::nxv2f64);
24777   }
24778 }
24779 
24780 // Return a PTRUE with active lanes corresponding to the extent of VT.
24781 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
24782                                                 EVT VT) {
24783   assert(VT.isFixedLengthVector() &&
24784          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
24785          "Expected legal fixed length vector!");
24786 
24787   std::optional<unsigned> PgPattern =
24788       getSVEPredPatternFromNumElements(VT.getVectorNumElements());
24789   assert(PgPattern && "Unexpected element count for SVE predicate");
24790 
24791   // For vectors that are exactly getMaxSVEVectorSizeInBits big, we can use
24792   // AArch64SVEPredPattern::all, which can enable the use of unpredicated
24793   // variants of instructions when available.
24794   const auto &Subtarget = DAG.getSubtarget<AArch64Subtarget>();
24795   unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
24796   unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
24797   if (MaxSVESize && MinSVESize == MaxSVESize &&
24798       MaxSVESize == VT.getSizeInBits())
24799     PgPattern = AArch64SVEPredPattern::all;
24800 
24801   MVT MaskVT;
24802   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
24803   default:
24804     llvm_unreachable("unexpected element type for SVE predicate");
24805   case MVT::i8:
24806     MaskVT = MVT::nxv16i1;
24807     break;
24808   case MVT::i16:
24809   case MVT::f16:
24810     MaskVT = MVT::nxv8i1;
24811     break;
24812   case MVT::i32:
24813   case MVT::f32:
24814     MaskVT = MVT::nxv4i1;
24815     break;
24816   case MVT::i64:
24817   case MVT::f64:
24818     MaskVT = MVT::nxv2i1;
24819     break;
24820   }
24821 
24822   return getPTrue(DAG, DL, MaskVT, *PgPattern);
24823 }
24824 
24825 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
24826                                              EVT VT) {
24827   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
24828          "Expected legal scalable vector!");
24829   auto PredTy = VT.changeVectorElementType(MVT::i1);
24830   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
24831 }
24832 
24833 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
24834   if (VT.isFixedLengthVector())
24835     return getPredicateForFixedLengthVector(DAG, DL, VT);
24836 
24837   return getPredicateForScalableVector(DAG, DL, VT);
24838 }
24839 
24840 // Grow V to consume an entire SVE register.
24841 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
24842   assert(VT.isScalableVector() &&
24843          "Expected to convert into a scalable vector!");
24844   assert(V.getValueType().isFixedLengthVector() &&
24845          "Expected a fixed length vector operand!");
24846   SDLoc DL(V);
24847   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
24848   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
24849 }
24850 
24851 // Shrink V so it's just big enough to maintain a VT's worth of data.
24852 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
24853   assert(VT.isFixedLengthVector() &&
24854          "Expected to convert into a fixed length vector!");
24855   assert(V.getValueType().isScalableVector() &&
24856          "Expected a scalable vector operand!");
24857   SDLoc DL(V);
24858   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
24859   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
24860 }
24861 
24862 // Convert all fixed length vector loads larger than NEON to masked_loads.
24863 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
24864     SDValue Op, SelectionDAG &DAG) const {
24865   auto Load = cast<LoadSDNode>(Op);
24866 
24867   SDLoc DL(Op);
24868   EVT VT = Op.getValueType();
24869   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
24870   EVT LoadVT = ContainerVT;
24871   EVT MemVT = Load->getMemoryVT();
24872 
24873   auto Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
24874 
24875   if (VT.isFloatingPoint()) {
24876     LoadVT = ContainerVT.changeTypeToInteger();
24877     MemVT = MemVT.changeTypeToInteger();
24878   }
24879 
24880   SDValue NewLoad = DAG.getMaskedLoad(
24881       LoadVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(), Pg,
24882       DAG.getUNDEF(LoadVT), MemVT, Load->getMemOperand(),
24883       Load->getAddressingMode(), Load->getExtensionType());
24884 
24885   SDValue Result = NewLoad;
24886   if (VT.isFloatingPoint() && Load->getExtensionType() == ISD::EXTLOAD) {
24887     EVT ExtendVT = ContainerVT.changeVectorElementType(
24888         Load->getMemoryVT().getVectorElementType());
24889 
24890     Result = getSVESafeBitCast(ExtendVT, Result, DAG);
24891     Result = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
24892                          Pg, Result, DAG.getUNDEF(ContainerVT));
24893   } else if (VT.isFloatingPoint()) {
24894     Result = DAG.getNode(ISD::BITCAST, DL, ContainerVT, Result);
24895   }
24896 
24897   Result = convertFromScalableVector(DAG, VT, Result);
24898   SDValue MergedValues[2] = {Result, NewLoad.getValue(1)};
24899   return DAG.getMergeValues(MergedValues, DL);
24900 }
24901 
24902 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
24903                                                 SelectionDAG &DAG) {
24904   SDLoc DL(Mask);
24905   EVT InVT = Mask.getValueType();
24906   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
24907 
24908   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
24909 
24910   if (ISD::isBuildVectorAllOnes(Mask.getNode()))
24911     return Pg;
24912 
24913   auto Op1 = convertToScalableVector(DAG, ContainerVT, Mask);
24914   auto Op2 = DAG.getConstant(0, DL, ContainerVT);
24915 
24916   return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, Pg.getValueType(),
24917                      {Pg, Op1, Op2, DAG.getCondCode(ISD::SETNE)});
24918 }
24919 
24920 // Convert all fixed length vector loads larger than NEON to masked_loads.
24921 SDValue AArch64TargetLowering::LowerFixedLengthVectorMLoadToSVE(
24922     SDValue Op, SelectionDAG &DAG) const {
24923   auto Load = cast<MaskedLoadSDNode>(Op);
24924 
24925   SDLoc DL(Op);
24926   EVT VT = Op.getValueType();
24927   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
24928 
24929   SDValue Mask = convertFixedMaskToScalableVector(Load->getMask(), DAG);
24930 
24931   SDValue PassThru;
24932   bool IsPassThruZeroOrUndef = false;
24933 
24934   if (Load->getPassThru()->isUndef()) {
24935     PassThru = DAG.getUNDEF(ContainerVT);
24936     IsPassThruZeroOrUndef = true;
24937   } else {
24938     if (ContainerVT.isInteger())
24939       PassThru = DAG.getConstant(0, DL, ContainerVT);
24940     else
24941       PassThru = DAG.getConstantFP(0, DL, ContainerVT);
24942     if (isZerosVector(Load->getPassThru().getNode()))
24943       IsPassThruZeroOrUndef = true;
24944   }
24945 
24946   SDValue NewLoad = DAG.getMaskedLoad(
24947       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
24948       Mask, PassThru, Load->getMemoryVT(), Load->getMemOperand(),
24949       Load->getAddressingMode(), Load->getExtensionType());
24950 
24951   SDValue Result = NewLoad;
24952   if (!IsPassThruZeroOrUndef) {
24953     SDValue OldPassThru =
24954         convertToScalableVector(DAG, ContainerVT, Load->getPassThru());
24955     Result = DAG.getSelect(DL, ContainerVT, Mask, Result, OldPassThru);
24956   }
24957 
24958   Result = convertFromScalableVector(DAG, VT, Result);
24959   SDValue MergedValues[2] = {Result, NewLoad.getValue(1)};
24960   return DAG.getMergeValues(MergedValues, DL);
24961 }
24962 
24963 // Convert all fixed length vector stores larger than NEON to masked_stores.
24964 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
24965     SDValue Op, SelectionDAG &DAG) const {
24966   auto Store = cast<StoreSDNode>(Op);
24967 
24968   SDLoc DL(Op);
24969   EVT VT = Store->getValue().getValueType();
24970   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
24971   EVT MemVT = Store->getMemoryVT();
24972 
24973   auto Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
24974   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
24975 
24976   if (VT.isFloatingPoint() && Store->isTruncatingStore()) {
24977     EVT TruncVT = ContainerVT.changeVectorElementType(
24978         Store->getMemoryVT().getVectorElementType());
24979     MemVT = MemVT.changeTypeToInteger();
24980     NewValue = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, TruncVT, Pg,
24981                            NewValue, DAG.getTargetConstant(0, DL, MVT::i64),
24982                            DAG.getUNDEF(TruncVT));
24983     NewValue =
24984         getSVESafeBitCast(ContainerVT.changeTypeToInteger(), NewValue, DAG);
24985   } else if (VT.isFloatingPoint()) {
24986     MemVT = MemVT.changeTypeToInteger();
24987     NewValue =
24988         getSVESafeBitCast(ContainerVT.changeTypeToInteger(), NewValue, DAG);
24989   }
24990 
24991   return DAG.getMaskedStore(Store->getChain(), DL, NewValue,
24992                             Store->getBasePtr(), Store->getOffset(), Pg, MemVT,
24993                             Store->getMemOperand(), Store->getAddressingMode(),
24994                             Store->isTruncatingStore());
24995 }
24996 
24997 SDValue AArch64TargetLowering::LowerFixedLengthVectorMStoreToSVE(
24998     SDValue Op, SelectionDAG &DAG) const {
24999   auto *Store = cast<MaskedStoreSDNode>(Op);
25000 
25001   SDLoc DL(Op);
25002   EVT VT = Store->getValue().getValueType();
25003   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25004 
25005   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
25006   SDValue Mask = convertFixedMaskToScalableVector(Store->getMask(), DAG);
25007 
25008   return DAG.getMaskedStore(
25009       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
25010       Mask, Store->getMemoryVT(), Store->getMemOperand(),
25011       Store->getAddressingMode(), Store->isTruncatingStore());
25012 }
25013 
25014 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
25015     SDValue Op, SelectionDAG &DAG) const {
25016   SDLoc dl(Op);
25017   EVT VT = Op.getValueType();
25018   EVT EltVT = VT.getVectorElementType();
25019 
25020   bool Signed = Op.getOpcode() == ISD::SDIV;
25021   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
25022 
25023   bool Negated;
25024   uint64_t SplatVal;
25025   if (Signed && isPow2Splat(Op.getOperand(1), SplatVal, Negated)) {
25026     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25027     SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
25028     SDValue Op2 = DAG.getTargetConstant(Log2_64(SplatVal), dl, MVT::i32);
25029 
25030     SDValue Pg = getPredicateForFixedLengthVector(DAG, dl, VT);
25031     SDValue Res =
25032         DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, dl, ContainerVT, Pg, Op1, Op2);
25033     if (Negated)
25034       Res = DAG.getNode(ISD::SUB, dl, ContainerVT,
25035                         DAG.getConstant(0, dl, ContainerVT), Res);
25036 
25037     return convertFromScalableVector(DAG, VT, Res);
25038   }
25039 
25040   // Scalable vector i32/i64 DIV is supported.
25041   if (EltVT == MVT::i32 || EltVT == MVT::i64)
25042     return LowerToPredicatedOp(Op, DAG, PredOpcode);
25043 
25044   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
25045   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
25046   EVT PromVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
25047   unsigned ExtendOpcode = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
25048 
25049   // If the wider type is legal: extend, op, and truncate.
25050   EVT WideVT = VT.widenIntegerVectorElementType(*DAG.getContext());
25051   if (DAG.getTargetLoweringInfo().isTypeLegal(WideVT)) {
25052     SDValue Op0 = DAG.getNode(ExtendOpcode, dl, WideVT, Op.getOperand(0));
25053     SDValue Op1 = DAG.getNode(ExtendOpcode, dl, WideVT, Op.getOperand(1));
25054     SDValue Div = DAG.getNode(Op.getOpcode(), dl, WideVT, Op0, Op1);
25055     return DAG.getNode(ISD::TRUNCATE, dl, VT, Div);
25056   }
25057 
25058   auto HalveAndExtendVector = [&DAG, &dl, &HalfVT, &PromVT,
25059                                &ExtendOpcode](SDValue Op) {
25060     SDValue IdxZero = DAG.getConstant(0, dl, MVT::i64);
25061     SDValue IdxHalf =
25062         DAG.getConstant(HalfVT.getVectorNumElements(), dl, MVT::i64);
25063     SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, Op, IdxZero);
25064     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, Op, IdxHalf);
25065     return std::pair<SDValue, SDValue>(
25066         {DAG.getNode(ExtendOpcode, dl, PromVT, Lo),
25067          DAG.getNode(ExtendOpcode, dl, PromVT, Hi)});
25068   };
25069 
25070   // If wider type is not legal: split, extend, op, trunc and concat.
25071   auto [Op0LoExt, Op0HiExt] = HalveAndExtendVector(Op.getOperand(0));
25072   auto [Op1LoExt, Op1HiExt] = HalveAndExtendVector(Op.getOperand(1));
25073   SDValue Lo = DAG.getNode(Op.getOpcode(), dl, PromVT, Op0LoExt, Op1LoExt);
25074   SDValue Hi = DAG.getNode(Op.getOpcode(), dl, PromVT, Op0HiExt, Op1HiExt);
25075   SDValue LoTrunc = DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Lo);
25076   SDValue HiTrunc = DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Hi);
25077   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, {LoTrunc, HiTrunc});
25078 }
25079 
25080 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
25081     SDValue Op, SelectionDAG &DAG) const {
25082   EVT VT = Op.getValueType();
25083   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25084 
25085   SDLoc DL(Op);
25086   SDValue Val = Op.getOperand(0);
25087   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
25088   Val = convertToScalableVector(DAG, ContainerVT, Val);
25089 
25090   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
25091   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
25092 
25093   // Repeatedly unpack Val until the result is of the desired element type.
25094   switch (ContainerVT.getSimpleVT().SimpleTy) {
25095   default:
25096     llvm_unreachable("unimplemented container type");
25097   case MVT::nxv16i8:
25098     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
25099     if (VT.getVectorElementType() == MVT::i16)
25100       break;
25101     [[fallthrough]];
25102   case MVT::nxv8i16:
25103     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
25104     if (VT.getVectorElementType() == MVT::i32)
25105       break;
25106     [[fallthrough]];
25107   case MVT::nxv4i32:
25108     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
25109     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
25110     break;
25111   }
25112 
25113   return convertFromScalableVector(DAG, VT, Val);
25114 }
25115 
25116 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
25117     SDValue Op, SelectionDAG &DAG) const {
25118   EVT VT = Op.getValueType();
25119   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25120 
25121   SDLoc DL(Op);
25122   SDValue Val = Op.getOperand(0);
25123   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
25124   Val = convertToScalableVector(DAG, ContainerVT, Val);
25125 
25126   // Repeatedly truncate Val until the result is of the desired element type.
25127   switch (ContainerVT.getSimpleVT().SimpleTy) {
25128   default:
25129     llvm_unreachable("unimplemented container type");
25130   case MVT::nxv2i64:
25131     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
25132     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
25133     if (VT.getVectorElementType() == MVT::i32)
25134       break;
25135     [[fallthrough]];
25136   case MVT::nxv4i32:
25137     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
25138     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
25139     if (VT.getVectorElementType() == MVT::i16)
25140       break;
25141     [[fallthrough]];
25142   case MVT::nxv8i16:
25143     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
25144     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
25145     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
25146     break;
25147   }
25148 
25149   return convertFromScalableVector(DAG, VT, Val);
25150 }
25151 
25152 SDValue AArch64TargetLowering::LowerFixedLengthExtractVectorElt(
25153     SDValue Op, SelectionDAG &DAG) const {
25154   EVT VT = Op.getValueType();
25155   EVT InVT = Op.getOperand(0).getValueType();
25156   assert(InVT.isFixedLengthVector() && "Expected fixed length vector type!");
25157 
25158   SDLoc DL(Op);
25159   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
25160   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
25161 
25162   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Op.getOperand(1));
25163 }
25164 
25165 SDValue AArch64TargetLowering::LowerFixedLengthInsertVectorElt(
25166     SDValue Op, SelectionDAG &DAG) const {
25167   EVT VT = Op.getValueType();
25168   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25169 
25170   SDLoc DL(Op);
25171   EVT InVT = Op.getOperand(0).getValueType();
25172   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
25173   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
25174 
25175   auto ScalableRes = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, Op0,
25176                                  Op.getOperand(1), Op.getOperand(2));
25177 
25178   return convertFromScalableVector(DAG, VT, ScalableRes);
25179 }
25180 
25181 // Convert vector operation 'Op' to an equivalent predicated operation whereby
25182 // the original operation's type is used to construct a suitable predicate.
25183 // NOTE: The results for inactive lanes are undefined.
25184 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
25185                                                    SelectionDAG &DAG,
25186                                                    unsigned NewOp) const {
25187   EVT VT = Op.getValueType();
25188   SDLoc DL(Op);
25189   auto Pg = getPredicateForVector(DAG, DL, VT);
25190 
25191   if (VT.isFixedLengthVector()) {
25192     assert(isTypeLegal(VT) && "Expected only legal fixed-width types");
25193     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25194 
25195     // Create list of operands by converting existing ones to scalable types.
25196     SmallVector<SDValue, 4> Operands = {Pg};
25197     for (const SDValue &V : Op->op_values()) {
25198       if (isa<CondCodeSDNode>(V)) {
25199         Operands.push_back(V);
25200         continue;
25201       }
25202 
25203       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
25204         EVT VTArg = VTNode->getVT().getVectorElementType();
25205         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
25206         Operands.push_back(DAG.getValueType(NewVTArg));
25207         continue;
25208       }
25209 
25210       assert(isTypeLegal(V.getValueType()) &&
25211              "Expected only legal fixed-width types");
25212       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
25213     }
25214 
25215     if (isMergePassthruOpcode(NewOp))
25216       Operands.push_back(DAG.getUNDEF(ContainerVT));
25217 
25218     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
25219     return convertFromScalableVector(DAG, VT, ScalableRes);
25220   }
25221 
25222   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
25223 
25224   SmallVector<SDValue, 4> Operands = {Pg};
25225   for (const SDValue &V : Op->op_values()) {
25226     assert((!V.getValueType().isVector() ||
25227             V.getValueType().isScalableVector()) &&
25228            "Only scalable vectors are supported!");
25229     Operands.push_back(V);
25230   }
25231 
25232   if (isMergePassthruOpcode(NewOp))
25233     Operands.push_back(DAG.getUNDEF(VT));
25234 
25235   return DAG.getNode(NewOp, DL, VT, Operands, Op->getFlags());
25236 }
25237 
25238 // If a fixed length vector operation has no side effects when applied to
25239 // undefined elements, we can safely use scalable vectors to perform the same
25240 // operation without needing to worry about predication.
25241 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
25242                                                  SelectionDAG &DAG) const {
25243   EVT VT = Op.getValueType();
25244   assert(VT.isFixedLengthVector() && isTypeLegal(VT) &&
25245          "Only expected to lower fixed length vector operation!");
25246   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25247 
25248   // Create list of operands by converting existing ones to scalable types.
25249   SmallVector<SDValue, 4> Ops;
25250   for (const SDValue &V : Op->op_values()) {
25251     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
25252 
25253     // Pass through non-vector operands.
25254     if (!V.getValueType().isVector()) {
25255       Ops.push_back(V);
25256       continue;
25257     }
25258 
25259     // "cast" fixed length vector to a scalable vector.
25260     assert(V.getValueType().isFixedLengthVector() &&
25261            isTypeLegal(V.getValueType()) &&
25262            "Only fixed length vectors are supported!");
25263     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
25264   }
25265 
25266   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
25267   return convertFromScalableVector(DAG, VT, ScalableRes);
25268 }
25269 
25270 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
25271     SelectionDAG &DAG) const {
25272   SDLoc DL(ScalarOp);
25273   SDValue AccOp = ScalarOp.getOperand(0);
25274   SDValue VecOp = ScalarOp.getOperand(1);
25275   EVT SrcVT = VecOp.getValueType();
25276   EVT ResVT = SrcVT.getVectorElementType();
25277 
25278   EVT ContainerVT = SrcVT;
25279   if (SrcVT.isFixedLengthVector()) {
25280     ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
25281     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
25282   }
25283 
25284   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
25285   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
25286 
25287   // Convert operands to Scalable.
25288   AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
25289                       DAG.getUNDEF(ContainerVT), AccOp, Zero);
25290 
25291   // Perform reduction.
25292   SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
25293                             Pg, AccOp, VecOp);
25294 
25295   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
25296 }
25297 
25298 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
25299                                                        SelectionDAG &DAG) const {
25300   SDLoc DL(ReduceOp);
25301   SDValue Op = ReduceOp.getOperand(0);
25302   EVT OpVT = Op.getValueType();
25303   EVT VT = ReduceOp.getValueType();
25304 
25305   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
25306     return SDValue();
25307 
25308   SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
25309 
25310   switch (ReduceOp.getOpcode()) {
25311   default:
25312     return SDValue();
25313   case ISD::VECREDUCE_OR:
25314     if (isAllActivePredicate(DAG, Pg) && OpVT == MVT::nxv16i1)
25315       // The predicate can be 'Op' because
25316       // vecreduce_or(Op & <all true>) <=> vecreduce_or(Op).
25317       return getPTest(DAG, VT, Op, Op, AArch64CC::ANY_ACTIVE);
25318     else
25319       return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
25320   case ISD::VECREDUCE_AND: {
25321     Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
25322     return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
25323   }
25324   case ISD::VECREDUCE_XOR: {
25325     SDValue ID =
25326         DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
25327     if (OpVT == MVT::nxv1i1) {
25328       // Emulate a CNTP on .Q using .D and a different governing predicate.
25329       Pg = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, MVT::nxv2i1, Pg);
25330       Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, MVT::nxv2i1, Op);
25331     }
25332     SDValue Cntp =
25333         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
25334     return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
25335   }
25336   }
25337 
25338   return SDValue();
25339 }
25340 
25341 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
25342                                                    SDValue ScalarOp,
25343                                                    SelectionDAG &DAG) const {
25344   SDLoc DL(ScalarOp);
25345   SDValue VecOp = ScalarOp.getOperand(0);
25346   EVT SrcVT = VecOp.getValueType();
25347 
25348   if (useSVEForFixedLengthVectorVT(
25349           SrcVT,
25350           /*OverrideNEON=*/Subtarget->useSVEForFixedLengthVectors())) {
25351     EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
25352     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
25353   }
25354 
25355   // UADDV always returns an i64 result.
25356   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
25357                                                    SrcVT.getVectorElementType();
25358   EVT RdxVT = SrcVT;
25359   if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
25360     RdxVT = getPackedSVEVectorVT(ResVT);
25361 
25362   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
25363   SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
25364   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
25365                             Rdx, DAG.getConstant(0, DL, MVT::i64));
25366 
25367   // The VEC_REDUCE nodes expect an element size result.
25368   if (ResVT != ScalarOp.getValueType())
25369     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
25370 
25371   return Res;
25372 }
25373 
25374 SDValue
25375 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
25376     SelectionDAG &DAG) const {
25377   EVT VT = Op.getValueType();
25378   SDLoc DL(Op);
25379 
25380   EVT InVT = Op.getOperand(1).getValueType();
25381   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
25382   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
25383   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
25384 
25385   // Convert the mask to a predicated (NOTE: We don't need to worry about
25386   // inactive lanes since VSELECT is safe when given undefined elements).
25387   EVT MaskVT = Op.getOperand(0).getValueType();
25388   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
25389   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
25390   Mask = DAG.getNode(ISD::TRUNCATE, DL,
25391                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
25392 
25393   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
25394                                 Mask, Op1, Op2);
25395 
25396   return convertFromScalableVector(DAG, VT, ScalableRes);
25397 }
25398 
25399 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
25400     SDValue Op, SelectionDAG &DAG) const {
25401   SDLoc DL(Op);
25402   EVT InVT = Op.getOperand(0).getValueType();
25403   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
25404 
25405   assert(InVT.isFixedLengthVector() && isTypeLegal(InVT) &&
25406          "Only expected to lower fixed length vector operation!");
25407   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
25408          "Expected integer result of the same bit length as the inputs!");
25409 
25410   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
25411   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
25412   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
25413 
25414   EVT CmpVT = Pg.getValueType();
25415   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
25416                          {Pg, Op1, Op2, Op.getOperand(2)});
25417 
25418   EVT PromoteVT = ContainerVT.changeTypeToInteger();
25419   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
25420   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
25421 }
25422 
25423 SDValue
25424 AArch64TargetLowering::LowerFixedLengthBitcastToSVE(SDValue Op,
25425                                                     SelectionDAG &DAG) const {
25426   SDLoc DL(Op);
25427   auto SrcOp = Op.getOperand(0);
25428   EVT VT = Op.getValueType();
25429   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
25430   EVT ContainerSrcVT =
25431       getContainerForFixedLengthVector(DAG, SrcOp.getValueType());
25432 
25433   SrcOp = convertToScalableVector(DAG, ContainerSrcVT, SrcOp);
25434   Op = DAG.getNode(ISD::BITCAST, DL, ContainerDstVT, SrcOp);
25435   return convertFromScalableVector(DAG, VT, Op);
25436 }
25437 
25438 SDValue AArch64TargetLowering::LowerFixedLengthConcatVectorsToSVE(
25439     SDValue Op, SelectionDAG &DAG) const {
25440   SDLoc DL(Op);
25441   unsigned NumOperands = Op->getNumOperands();
25442 
25443   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
25444          "Unexpected number of operands in CONCAT_VECTORS");
25445 
25446   auto SrcOp1 = Op.getOperand(0);
25447   auto SrcOp2 = Op.getOperand(1);
25448   EVT VT = Op.getValueType();
25449   EVT SrcVT = SrcOp1.getValueType();
25450 
25451   if (NumOperands > 2) {
25452     SmallVector<SDValue, 4> Ops;
25453     EVT PairVT = SrcVT.getDoubleNumVectorElementsVT(*DAG.getContext());
25454     for (unsigned I = 0; I < NumOperands; I += 2)
25455       Ops.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, PairVT,
25456                                 Op->getOperand(I), Op->getOperand(I + 1)));
25457 
25458     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Ops);
25459   }
25460 
25461   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25462 
25463   SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
25464   SrcOp1 = convertToScalableVector(DAG, ContainerVT, SrcOp1);
25465   SrcOp2 = convertToScalableVector(DAG, ContainerVT, SrcOp2);
25466 
25467   Op = DAG.getNode(AArch64ISD::SPLICE, DL, ContainerVT, Pg, SrcOp1, SrcOp2);
25468 
25469   return convertFromScalableVector(DAG, VT, Op);
25470 }
25471 
25472 SDValue
25473 AArch64TargetLowering::LowerFixedLengthFPExtendToSVE(SDValue Op,
25474                                                      SelectionDAG &DAG) const {
25475   EVT VT = Op.getValueType();
25476   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25477 
25478   SDLoc DL(Op);
25479   SDValue Val = Op.getOperand(0);
25480   SDValue Pg = getPredicateForVector(DAG, DL, VT);
25481   EVT SrcVT = Val.getValueType();
25482   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25483   EVT ExtendVT = ContainerVT.changeVectorElementType(
25484       SrcVT.getVectorElementType());
25485 
25486   Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
25487   Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT.changeTypeToInteger(), Val);
25488 
25489   Val = convertToScalableVector(DAG, ContainerVT.changeTypeToInteger(), Val);
25490   Val = getSVESafeBitCast(ExtendVT, Val, DAG);
25491   Val = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
25492                     Pg, Val, DAG.getUNDEF(ContainerVT));
25493 
25494   return convertFromScalableVector(DAG, VT, Val);
25495 }
25496 
25497 SDValue
25498 AArch64TargetLowering::LowerFixedLengthFPRoundToSVE(SDValue Op,
25499                                                     SelectionDAG &DAG) const {
25500   EVT VT = Op.getValueType();
25501   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25502 
25503   SDLoc DL(Op);
25504   SDValue Val = Op.getOperand(0);
25505   EVT SrcVT = Val.getValueType();
25506   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
25507   EVT RoundVT = ContainerSrcVT.changeVectorElementType(
25508       VT.getVectorElementType());
25509   SDValue Pg = getPredicateForVector(DAG, DL, RoundVT);
25510 
25511   Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
25512   Val = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, RoundVT, Pg, Val,
25513                     Op.getOperand(1), DAG.getUNDEF(RoundVT));
25514   Val = getSVESafeBitCast(ContainerSrcVT.changeTypeToInteger(), Val, DAG);
25515   Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
25516 
25517   Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
25518   return DAG.getNode(ISD::BITCAST, DL, VT, Val);
25519 }
25520 
25521 SDValue
25522 AArch64TargetLowering::LowerFixedLengthIntToFPToSVE(SDValue Op,
25523                                                     SelectionDAG &DAG) const {
25524   EVT VT = Op.getValueType();
25525   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25526 
25527   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
25528   unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
25529                              : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
25530 
25531   SDLoc DL(Op);
25532   SDValue Val = Op.getOperand(0);
25533   EVT SrcVT = Val.getValueType();
25534   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
25535   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
25536 
25537   if (VT.bitsGE(SrcVT)) {
25538     SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
25539 
25540     Val = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
25541                       VT.changeTypeToInteger(), Val);
25542 
25543     // Safe to use a larger than specified operand because by promoting the
25544     // value nothing has changed from an arithmetic point of view.
25545     Val =
25546         convertToScalableVector(DAG, ContainerDstVT.changeTypeToInteger(), Val);
25547     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
25548                       DAG.getUNDEF(ContainerDstVT));
25549     return convertFromScalableVector(DAG, VT, Val);
25550   } else {
25551     EVT CvtVT = ContainerSrcVT.changeVectorElementType(
25552         ContainerDstVT.getVectorElementType());
25553     SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
25554 
25555     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
25556     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
25557     Val = getSVESafeBitCast(ContainerSrcVT, Val, DAG);
25558     Val = convertFromScalableVector(DAG, SrcVT, Val);
25559 
25560     Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
25561     return DAG.getNode(ISD::BITCAST, DL, VT, Val);
25562   }
25563 }
25564 
25565 SDValue
25566 AArch64TargetLowering::LowerVECTOR_DEINTERLEAVE(SDValue Op,
25567                                                 SelectionDAG &DAG) const {
25568   SDLoc DL(Op);
25569   EVT OpVT = Op.getValueType();
25570   assert(OpVT.isScalableVector() &&
25571          "Expected scalable vector in LowerVECTOR_DEINTERLEAVE.");
25572   SDValue Even = DAG.getNode(AArch64ISD::UZP1, DL, OpVT, Op.getOperand(0),
25573                              Op.getOperand(1));
25574   SDValue Odd = DAG.getNode(AArch64ISD::UZP2, DL, OpVT, Op.getOperand(0),
25575                             Op.getOperand(1));
25576   return DAG.getMergeValues({Even, Odd}, DL);
25577 }
25578 
25579 SDValue AArch64TargetLowering::LowerVECTOR_INTERLEAVE(SDValue Op,
25580                                                       SelectionDAG &DAG) const {
25581   SDLoc DL(Op);
25582   EVT OpVT = Op.getValueType();
25583   assert(OpVT.isScalableVector() &&
25584          "Expected scalable vector in LowerVECTOR_INTERLEAVE.");
25585 
25586   SDValue Lo = DAG.getNode(AArch64ISD::ZIP1, DL, OpVT, Op.getOperand(0),
25587                            Op.getOperand(1));
25588   SDValue Hi = DAG.getNode(AArch64ISD::ZIP2, DL, OpVT, Op.getOperand(0),
25589                            Op.getOperand(1));
25590   return DAG.getMergeValues({Lo, Hi}, DL);
25591 }
25592 
25593 SDValue
25594 AArch64TargetLowering::LowerFixedLengthFPToIntToSVE(SDValue Op,
25595                                                     SelectionDAG &DAG) const {
25596   EVT VT = Op.getValueType();
25597   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25598 
25599   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
25600   unsigned Opcode = IsSigned ? AArch64ISD::FCVTZS_MERGE_PASSTHRU
25601                              : AArch64ISD::FCVTZU_MERGE_PASSTHRU;
25602 
25603   SDLoc DL(Op);
25604   SDValue Val = Op.getOperand(0);
25605   EVT SrcVT = Val.getValueType();
25606   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
25607   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
25608 
25609   if (VT.bitsGT(SrcVT)) {
25610     EVT CvtVT = ContainerDstVT.changeVectorElementType(
25611       ContainerSrcVT.getVectorElementType());
25612     SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
25613 
25614     Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
25615     Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Val);
25616 
25617     Val = convertToScalableVector(DAG, ContainerDstVT, Val);
25618     Val = getSVESafeBitCast(CvtVT, Val, DAG);
25619     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
25620                       DAG.getUNDEF(ContainerDstVT));
25621     return convertFromScalableVector(DAG, VT, Val);
25622   } else {
25623     EVT CvtVT = ContainerSrcVT.changeTypeToInteger();
25624     SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
25625 
25626     // Safe to use a larger than specified result since an fp_to_int where the
25627     // result doesn't fit into the destination is undefined.
25628     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
25629     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
25630     Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
25631 
25632     return DAG.getNode(ISD::TRUNCATE, DL, VT, Val);
25633   }
25634 }
25635 
25636 SDValue AArch64TargetLowering::LowerFixedLengthVECTOR_SHUFFLEToSVE(
25637     SDValue Op, SelectionDAG &DAG) const {
25638   EVT VT = Op.getValueType();
25639   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
25640 
25641   auto *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
25642   auto ShuffleMask = SVN->getMask();
25643 
25644   SDLoc DL(Op);
25645   SDValue Op1 = Op.getOperand(0);
25646   SDValue Op2 = Op.getOperand(1);
25647 
25648   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
25649   Op1 = convertToScalableVector(DAG, ContainerVT, Op1);
25650   Op2 = convertToScalableVector(DAG, ContainerVT, Op2);
25651 
25652   auto MinLegalExtractEltScalarTy = [](EVT ScalarTy) -> EVT {
25653     if (ScalarTy == MVT::i8 || ScalarTy == MVT::i16)
25654       return MVT::i32;
25655     return ScalarTy;
25656   };
25657 
25658   if (SVN->isSplat()) {
25659     unsigned Lane = std::max(0, SVN->getSplatIndex());
25660     EVT ScalarTy = MinLegalExtractEltScalarTy(VT.getVectorElementType());
25661     SDValue SplatEl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarTy, Op1,
25662                                   DAG.getConstant(Lane, DL, MVT::i64));
25663     Op = DAG.getNode(ISD::SPLAT_VECTOR, DL, ContainerVT, SplatEl);
25664     return convertFromScalableVector(DAG, VT, Op);
25665   }
25666 
25667   bool ReverseEXT = false;
25668   unsigned Imm;
25669   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm) &&
25670       Imm == VT.getVectorNumElements() - 1) {
25671     if (ReverseEXT)
25672       std::swap(Op1, Op2);
25673     EVT ScalarTy = MinLegalExtractEltScalarTy(VT.getVectorElementType());
25674     SDValue Scalar = DAG.getNode(
25675         ISD::EXTRACT_VECTOR_ELT, DL, ScalarTy, Op1,
25676         DAG.getConstant(VT.getVectorNumElements() - 1, DL, MVT::i64));
25677     Op = DAG.getNode(AArch64ISD::INSR, DL, ContainerVT, Op2, Scalar);
25678     return convertFromScalableVector(DAG, VT, Op);
25679   }
25680 
25681   for (unsigned LaneSize : {64U, 32U, 16U}) {
25682     if (isREVMask(ShuffleMask, VT, LaneSize)) {
25683       EVT NewVT =
25684           getPackedSVEVectorVT(EVT::getIntegerVT(*DAG.getContext(), LaneSize));
25685       unsigned RevOp;
25686       unsigned EltSz = VT.getScalarSizeInBits();
25687       if (EltSz == 8)
25688         RevOp = AArch64ISD::BSWAP_MERGE_PASSTHRU;
25689       else if (EltSz == 16)
25690         RevOp = AArch64ISD::REVH_MERGE_PASSTHRU;
25691       else
25692         RevOp = AArch64ISD::REVW_MERGE_PASSTHRU;
25693 
25694       Op = DAG.getNode(ISD::BITCAST, DL, NewVT, Op1);
25695       Op = LowerToPredicatedOp(Op, DAG, RevOp);
25696       Op = DAG.getNode(ISD::BITCAST, DL, ContainerVT, Op);
25697       return convertFromScalableVector(DAG, VT, Op);
25698     }
25699   }
25700 
25701   if (Subtarget->hasSVE2p1() && VT.getScalarSizeInBits() == 64 &&
25702       isREVMask(ShuffleMask, VT, 128)) {
25703     if (!VT.isFloatingPoint())
25704       return LowerToPredicatedOp(Op, DAG, AArch64ISD::REVD_MERGE_PASSTHRU);
25705 
25706     EVT NewVT = getPackedSVEVectorVT(EVT::getIntegerVT(*DAG.getContext(), 64));
25707     Op = DAG.getNode(ISD::BITCAST, DL, NewVT, Op1);
25708     Op = LowerToPredicatedOp(Op, DAG, AArch64ISD::REVD_MERGE_PASSTHRU);
25709     Op = DAG.getNode(ISD::BITCAST, DL, ContainerVT, Op);
25710     return convertFromScalableVector(DAG, VT, Op);
25711   }
25712 
25713   unsigned WhichResult;
25714   if (isZIPMask(ShuffleMask, VT, WhichResult) && WhichResult == 0)
25715     return convertFromScalableVector(
25716         DAG, VT, DAG.getNode(AArch64ISD::ZIP1, DL, ContainerVT, Op1, Op2));
25717 
25718   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
25719     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
25720     return convertFromScalableVector(
25721         DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op2));
25722   }
25723 
25724   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult) && WhichResult == 0)
25725     return convertFromScalableVector(
25726         DAG, VT, DAG.getNode(AArch64ISD::ZIP1, DL, ContainerVT, Op1, Op1));
25727 
25728   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
25729     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
25730     return convertFromScalableVector(
25731         DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op1));
25732   }
25733 
25734   // Functions like isZIPMask return true when a ISD::VECTOR_SHUFFLE's mask
25735   // represents the same logical operation as performed by a ZIP instruction. In
25736   // isolation these functions do not mean the ISD::VECTOR_SHUFFLE is exactly
25737   // equivalent to an AArch64 instruction. There's the extra component of
25738   // ISD::VECTOR_SHUFFLE's value type to consider. Prior to SVE these functions
25739   // only operated on 64/128bit vector types that have a direct mapping to a
25740   // target register and so an exact mapping is implied.
25741   // However, when using SVE for fixed length vectors, most legal vector types
25742   // are actually sub-vectors of a larger SVE register. When mapping
25743   // ISD::VECTOR_SHUFFLE to an SVE instruction care must be taken to consider
25744   // how the mask's indices translate. Specifically, when the mapping requires
25745   // an exact meaning for a specific vector index (e.g. Index X is the last
25746   // vector element in the register) then such mappings are often only safe when
25747   // the exact SVE register size is know. The main exception to this is when
25748   // indices are logically relative to the first element of either
25749   // ISD::VECTOR_SHUFFLE operand because these relative indices don't change
25750   // when converting from fixed-length to scalable vector types (i.e. the start
25751   // of a fixed length vector is always the start of a scalable vector).
25752   unsigned MinSVESize = Subtarget->getMinSVEVectorSizeInBits();
25753   unsigned MaxSVESize = Subtarget->getMaxSVEVectorSizeInBits();
25754   if (MinSVESize == MaxSVESize && MaxSVESize == VT.getSizeInBits()) {
25755     if (ShuffleVectorInst::isReverseMask(ShuffleMask) && Op2.isUndef()) {
25756       Op = DAG.getNode(ISD::VECTOR_REVERSE, DL, ContainerVT, Op1);
25757       return convertFromScalableVector(DAG, VT, Op);
25758     }
25759 
25760     if (isZIPMask(ShuffleMask, VT, WhichResult) && WhichResult != 0)
25761       return convertFromScalableVector(
25762           DAG, VT, DAG.getNode(AArch64ISD::ZIP2, DL, ContainerVT, Op1, Op2));
25763 
25764     if (isUZPMask(ShuffleMask, VT, WhichResult)) {
25765       unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
25766       return convertFromScalableVector(
25767           DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op2));
25768     }
25769 
25770     if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult) && WhichResult != 0)
25771       return convertFromScalableVector(
25772           DAG, VT, DAG.getNode(AArch64ISD::ZIP2, DL, ContainerVT, Op1, Op1));
25773 
25774     if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
25775       unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
25776       return convertFromScalableVector(
25777           DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op1));
25778     }
25779   }
25780 
25781   return SDValue();
25782 }
25783 
25784 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
25785                                                  SelectionDAG &DAG) const {
25786   SDLoc DL(Op);
25787   EVT InVT = Op.getValueType();
25788 
25789   assert(VT.isScalableVector() && isTypeLegal(VT) &&
25790          InVT.isScalableVector() && isTypeLegal(InVT) &&
25791          "Only expect to cast between legal scalable vector types!");
25792   assert(VT.getVectorElementType() != MVT::i1 &&
25793          InVT.getVectorElementType() != MVT::i1 &&
25794          "For predicate bitcasts, use getSVEPredicateBitCast");
25795 
25796   if (InVT == VT)
25797     return Op;
25798 
25799   EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
25800   EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
25801 
25802   // Safe bitcasting between unpacked vector types of different element counts
25803   // is currently unsupported because the following is missing the necessary
25804   // work to ensure the result's elements live where they're supposed to within
25805   // an SVE register.
25806   //                01234567
25807   // e.g. nxv2i32 = XX??XX??
25808   //      nxv4f16 = X?X?X?X?
25809   assert((VT.getVectorElementCount() == InVT.getVectorElementCount() ||
25810           VT == PackedVT || InVT == PackedInVT) &&
25811          "Unexpected bitcast!");
25812 
25813   // Pack input if required.
25814   if (InVT != PackedInVT)
25815     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
25816 
25817   Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
25818 
25819   // Unpack result if required.
25820   if (VT != PackedVT)
25821     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
25822 
25823   return Op;
25824 }
25825 
25826 bool AArch64TargetLowering::isAllActivePredicate(SelectionDAG &DAG,
25827                                                  SDValue N) const {
25828   return ::isAllActivePredicate(DAG, N);
25829 }
25830 
25831 EVT AArch64TargetLowering::getPromotedVTForPredicate(EVT VT) const {
25832   return ::getPromotedVTForPredicate(VT);
25833 }
25834 
25835 bool AArch64TargetLowering::SimplifyDemandedBitsForTargetNode(
25836     SDValue Op, const APInt &OriginalDemandedBits,
25837     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
25838     unsigned Depth) const {
25839 
25840   unsigned Opc = Op.getOpcode();
25841   switch (Opc) {
25842   case AArch64ISD::VSHL: {
25843     // Match (VSHL (VLSHR Val X) X)
25844     SDValue ShiftL = Op;
25845     SDValue ShiftR = Op->getOperand(0);
25846     if (ShiftR->getOpcode() != AArch64ISD::VLSHR)
25847       return false;
25848 
25849     if (!ShiftL.hasOneUse() || !ShiftR.hasOneUse())
25850       return false;
25851 
25852     unsigned ShiftLBits = ShiftL->getConstantOperandVal(1);
25853     unsigned ShiftRBits = ShiftR->getConstantOperandVal(1);
25854 
25855     // Other cases can be handled as well, but this is not
25856     // implemented.
25857     if (ShiftRBits != ShiftLBits)
25858       return false;
25859 
25860     unsigned ScalarSize = Op.getScalarValueSizeInBits();
25861     assert(ScalarSize > ShiftLBits && "Invalid shift imm");
25862 
25863     APInt ZeroBits = APInt::getLowBitsSet(ScalarSize, ShiftLBits);
25864     APInt UnusedBits = ~OriginalDemandedBits;
25865 
25866     if ((ZeroBits & UnusedBits) != ZeroBits)
25867       return false;
25868 
25869     // All bits that are zeroed by (VSHL (VLSHR Val X) X) are not
25870     // used - simplify to just Val.
25871     return TLO.CombineTo(Op, ShiftR->getOperand(0));
25872   }
25873   case ISD::INTRINSIC_WO_CHAIN: {
25874     if (auto ElementSize = IsSVECntIntrinsic(Op)) {
25875       unsigned MaxSVEVectorSizeInBits = Subtarget->getMaxSVEVectorSizeInBits();
25876       if (!MaxSVEVectorSizeInBits)
25877         MaxSVEVectorSizeInBits = AArch64::SVEMaxBitsPerVector;
25878       unsigned MaxElements = MaxSVEVectorSizeInBits / *ElementSize;
25879       // The SVE count intrinsics don't support the multiplier immediate so we
25880       // don't have to account for that here. The value returned may be slightly
25881       // over the true required bits, as this is based on the "ALL" pattern. The
25882       // other patterns are also exposed by these intrinsics, but they all
25883       // return a value that's strictly less than "ALL".
25884       unsigned RequiredBits = llvm::bit_width(MaxElements);
25885       unsigned BitWidth = Known.Zero.getBitWidth();
25886       if (RequiredBits < BitWidth)
25887         Known.Zero.setHighBits(BitWidth - RequiredBits);
25888       return false;
25889     }
25890   }
25891   }
25892 
25893   return TargetLowering::SimplifyDemandedBitsForTargetNode(
25894       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
25895 }
25896 
25897 bool AArch64TargetLowering::isTargetCanonicalConstantNode(SDValue Op) const {
25898   return Op.getOpcode() == AArch64ISD::DUP ||
25899          Op.getOpcode() == AArch64ISD::MOVI ||
25900          (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
25901           Op.getOperand(0).getOpcode() == AArch64ISD::DUP) ||
25902          TargetLowering::isTargetCanonicalConstantNode(Op);
25903 }
25904 
25905 bool AArch64TargetLowering::isConstantUnsignedBitfieldExtractLegal(
25906     unsigned Opc, LLT Ty1, LLT Ty2) const {
25907   return Ty1 == Ty2 && (Ty1 == LLT::scalar(32) || Ty1 == LLT::scalar(64));
25908 }
25909 
25910 bool AArch64TargetLowering::isComplexDeinterleavingSupported() const {
25911   return Subtarget->hasSVE() || Subtarget->hasSVE2() ||
25912          Subtarget->hasComplxNum();
25913 }
25914 
25915 bool AArch64TargetLowering::isComplexDeinterleavingOperationSupported(
25916     ComplexDeinterleavingOperation Operation, Type *Ty) const {
25917   auto *VTy = dyn_cast<VectorType>(Ty);
25918   if (!VTy)
25919     return false;
25920 
25921   // If the vector is scalable, SVE is enabled, implying support for complex
25922   // numbers. Otherwirse, we need to ensure complex number support is avaialble
25923   if (!VTy->isScalableTy() && !Subtarget->hasComplxNum())
25924     return false;
25925 
25926   auto *ScalarTy = VTy->getScalarType();
25927   unsigned NumElements = VTy->getElementCount().getKnownMinValue();
25928 
25929   // We can only process vectors that have a bit size of 128 or higher (with an
25930   // additional 64 bits for Neon). Additionally, these vectors must have a
25931   // power-of-2 size, as we later split them into the smallest supported size
25932   // and merging them back together after applying complex operation.
25933   unsigned VTyWidth = VTy->getScalarSizeInBits() * NumElements;
25934   if ((VTyWidth < 128 && (VTy->isScalableTy() || VTyWidth != 64)) ||
25935       !llvm::isPowerOf2_32(VTyWidth))
25936     return false;
25937 
25938   if (ScalarTy->isIntegerTy() && Subtarget->hasSVE2()) {
25939     unsigned ScalarWidth = ScalarTy->getScalarSizeInBits();
25940     return 8 <= ScalarWidth && ScalarWidth <= 64;
25941   }
25942 
25943   return (ScalarTy->isHalfTy() && Subtarget->hasFullFP16()) ||
25944          ScalarTy->isFloatTy() || ScalarTy->isDoubleTy();
25945 }
25946 
25947 Value *AArch64TargetLowering::createComplexDeinterleavingIR(
25948     IRBuilderBase &B, ComplexDeinterleavingOperation OperationType,
25949     ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
25950     Value *Accumulator) const {
25951   VectorType *Ty = cast<VectorType>(InputA->getType());
25952   bool IsScalable = Ty->isScalableTy();
25953   bool IsInt = Ty->getElementType()->isIntegerTy();
25954 
25955   unsigned TyWidth =
25956       Ty->getScalarSizeInBits() * Ty->getElementCount().getKnownMinValue();
25957 
25958   assert(((TyWidth >= 128 && llvm::isPowerOf2_32(TyWidth)) || TyWidth == 64) &&
25959          "Vector type must be either 64 or a power of 2 that is at least 128");
25960 
25961   if (TyWidth > 128) {
25962     int Stride = Ty->getElementCount().getKnownMinValue() / 2;
25963     auto *HalfTy = VectorType::getHalfElementsVectorType(Ty);
25964     auto *LowerSplitA = B.CreateExtractVector(HalfTy, InputA, B.getInt64(0));
25965     auto *LowerSplitB = B.CreateExtractVector(HalfTy, InputB, B.getInt64(0));
25966     auto *UpperSplitA =
25967         B.CreateExtractVector(HalfTy, InputA, B.getInt64(Stride));
25968     auto *UpperSplitB =
25969         B.CreateExtractVector(HalfTy, InputB, B.getInt64(Stride));
25970     Value *LowerSplitAcc = nullptr;
25971     Value *UpperSplitAcc = nullptr;
25972     if (Accumulator) {
25973       LowerSplitAcc = B.CreateExtractVector(HalfTy, Accumulator, B.getInt64(0));
25974       UpperSplitAcc =
25975           B.CreateExtractVector(HalfTy, Accumulator, B.getInt64(Stride));
25976     }
25977     auto *LowerSplitInt = createComplexDeinterleavingIR(
25978         B, OperationType, Rotation, LowerSplitA, LowerSplitB, LowerSplitAcc);
25979     auto *UpperSplitInt = createComplexDeinterleavingIR(
25980         B, OperationType, Rotation, UpperSplitA, UpperSplitB, UpperSplitAcc);
25981 
25982     auto *Result = B.CreateInsertVector(Ty, PoisonValue::get(Ty), LowerSplitInt,
25983                                         B.getInt64(0));
25984     return B.CreateInsertVector(Ty, Result, UpperSplitInt, B.getInt64(Stride));
25985   }
25986 
25987   if (OperationType == ComplexDeinterleavingOperation::CMulPartial) {
25988     if (Accumulator == nullptr)
25989       Accumulator = Constant::getNullValue(Ty);
25990 
25991     if (IsScalable) {
25992       if (IsInt)
25993         return B.CreateIntrinsic(
25994             Intrinsic::aarch64_sve_cmla_x, Ty,
25995             {Accumulator, InputA, InputB, B.getInt32((int)Rotation * 90)});
25996 
25997       auto *Mask = B.getAllOnesMask(Ty->getElementCount());
25998       return B.CreateIntrinsic(
25999           Intrinsic::aarch64_sve_fcmla, Ty,
26000           {Mask, Accumulator, InputA, InputB, B.getInt32((int)Rotation * 90)});
26001     }
26002 
26003     Intrinsic::ID IdMap[4] = {Intrinsic::aarch64_neon_vcmla_rot0,
26004                               Intrinsic::aarch64_neon_vcmla_rot90,
26005                               Intrinsic::aarch64_neon_vcmla_rot180,
26006                               Intrinsic::aarch64_neon_vcmla_rot270};
26007 
26008 
26009     return B.CreateIntrinsic(IdMap[(int)Rotation], Ty,
26010                              {Accumulator, InputB, InputA});
26011   }
26012 
26013   if (OperationType == ComplexDeinterleavingOperation::CAdd) {
26014     if (IsScalable) {
26015       if (Rotation == ComplexDeinterleavingRotation::Rotation_90 ||
26016           Rotation == ComplexDeinterleavingRotation::Rotation_270) {
26017         if (IsInt)
26018           return B.CreateIntrinsic(
26019               Intrinsic::aarch64_sve_cadd_x, Ty,
26020               {InputA, InputB, B.getInt32((int)Rotation * 90)});
26021 
26022         auto *Mask = B.getAllOnesMask(Ty->getElementCount());
26023         return B.CreateIntrinsic(
26024             Intrinsic::aarch64_sve_fcadd, Ty,
26025             {Mask, InputA, InputB, B.getInt32((int)Rotation * 90)});
26026       }
26027       return nullptr;
26028     }
26029 
26030     Intrinsic::ID IntId = Intrinsic::not_intrinsic;
26031     if (Rotation == ComplexDeinterleavingRotation::Rotation_90)
26032       IntId = Intrinsic::aarch64_neon_vcadd_rot90;
26033     else if (Rotation == ComplexDeinterleavingRotation::Rotation_270)
26034       IntId = Intrinsic::aarch64_neon_vcadd_rot270;
26035 
26036     if (IntId == Intrinsic::not_intrinsic)
26037       return nullptr;
26038 
26039     return B.CreateIntrinsic(IntId, Ty, {InputA, InputB});
26040   }
26041 
26042   return nullptr;
26043 }
26044 
26045 bool AArch64TargetLowering::preferScalarizeSplat(SDNode *N) const {
26046   unsigned Opc = N->getOpcode();
26047   if (ISD::isExtOpcode(Opc)) {
26048     if (any_of(N->uses(),
26049                [&](SDNode *Use) { return Use->getOpcode() == ISD::MUL; }))
26050       return false;
26051   }
26052   return true;
26053 }
26054