1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64ISelLowering.h"
14 #include "AArch64CallingConvention.h"
15 #include "AArch64ExpandImm.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/ObjCARCUtil.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/RuntimeLibcalls.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/CodeGen/SelectionDAGNodes.h"
46 #include "llvm/CodeGen/TargetCallingConv.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/ValueTypes.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/Constants.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GetElementPtrTypeIterator.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/IntrinsicsAArch64.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/OperandTraits.h"
65 #include "llvm/IR/PatternMatch.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/IR/Use.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/MC/MCRegisterInfo.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/KnownBits.h"
77 #include "llvm/Support/MachineValueType.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Target/TargetMachine.h"
81 #include "llvm/Target/TargetOptions.h"
82 #include <algorithm>
83 #include <bitset>
84 #include <cassert>
85 #include <cctype>
86 #include <cstdint>
87 #include <cstdlib>
88 #include <iterator>
89 #include <limits>
90 #include <tuple>
91 #include <utility>
92 #include <vector>
93 
94 using namespace llvm;
95 using namespace llvm::PatternMatch;
96 
97 #define DEBUG_TYPE "aarch64-lower"
98 
99 STATISTIC(NumTailCalls, "Number of tail calls");
100 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
101 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
102 
103 // FIXME: The necessary dtprel relocations don't seem to be supported
104 // well in the GNU bfd and gold linkers at the moment. Therefore, by
105 // default, for now, fall back to GeneralDynamic code generation.
106 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
107     "aarch64-elf-ldtls-generation", cl::Hidden,
108     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
109     cl::init(false));
110 
111 static cl::opt<bool>
112 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
113                          cl::desc("Enable AArch64 logical imm instruction "
114                                   "optimization"),
115                          cl::init(true));
116 
117 // Temporary option added for the purpose of testing functionality added
118 // to DAGCombiner.cpp in D92230. It is expected that this can be removed
119 // in future when both implementations will be based off MGATHER rather
120 // than the GLD1 nodes added for the SVE gather load intrinsics.
121 static cl::opt<bool>
122 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
123                                 cl::desc("Combine extends of AArch64 masked "
124                                          "gather intrinsics"),
125                                 cl::init(true));
126 
127 /// Value type used for condition codes.
128 static const MVT MVT_CC = MVT::i32;
129 
getPackedSVEVectorVT(EVT VT)130 static inline EVT getPackedSVEVectorVT(EVT VT) {
131   switch (VT.getSimpleVT().SimpleTy) {
132   default:
133     llvm_unreachable("unexpected element type for vector");
134   case MVT::i8:
135     return MVT::nxv16i8;
136   case MVT::i16:
137     return MVT::nxv8i16;
138   case MVT::i32:
139     return MVT::nxv4i32;
140   case MVT::i64:
141     return MVT::nxv2i64;
142   case MVT::f16:
143     return MVT::nxv8f16;
144   case MVT::f32:
145     return MVT::nxv4f32;
146   case MVT::f64:
147     return MVT::nxv2f64;
148   case MVT::bf16:
149     return MVT::nxv8bf16;
150   }
151 }
152 
153 // NOTE: Currently there's only a need to return integer vector types. If this
154 // changes then just add an extra "type" parameter.
getPackedSVEVectorVT(ElementCount EC)155 static inline EVT getPackedSVEVectorVT(ElementCount EC) {
156   switch (EC.getKnownMinValue()) {
157   default:
158     llvm_unreachable("unexpected element count for vector");
159   case 16:
160     return MVT::nxv16i8;
161   case 8:
162     return MVT::nxv8i16;
163   case 4:
164     return MVT::nxv4i32;
165   case 2:
166     return MVT::nxv2i64;
167   }
168 }
169 
getPromotedVTForPredicate(EVT VT)170 static inline EVT getPromotedVTForPredicate(EVT VT) {
171   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
172          "Expected scalable predicate vector type!");
173   switch (VT.getVectorMinNumElements()) {
174   default:
175     llvm_unreachable("unexpected element count for vector");
176   case 2:
177     return MVT::nxv2i64;
178   case 4:
179     return MVT::nxv4i32;
180   case 8:
181     return MVT::nxv8i16;
182   case 16:
183     return MVT::nxv16i8;
184   }
185 }
186 
187 /// Returns true if VT's elements occupy the lowest bit positions of its
188 /// associated register class without any intervening space.
189 ///
190 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
191 /// same register class, but only nxv8f16 can be treated as a packed vector.
isPackedVectorType(EVT VT,SelectionDAG & DAG)192 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
193   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
194          "Expected legal vector type!");
195   return VT.isFixedLengthVector() ||
196          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
197 }
198 
199 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
200 // predicate and end with a passthru value matching the result type.
isMergePassthruOpcode(unsigned Opc)201 static bool isMergePassthruOpcode(unsigned Opc) {
202   switch (Opc) {
203   default:
204     return false;
205   case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
206   case AArch64ISD::BSWAP_MERGE_PASSTHRU:
207   case AArch64ISD::CTLZ_MERGE_PASSTHRU:
208   case AArch64ISD::CTPOP_MERGE_PASSTHRU:
209   case AArch64ISD::DUP_MERGE_PASSTHRU:
210   case AArch64ISD::ABS_MERGE_PASSTHRU:
211   case AArch64ISD::NEG_MERGE_PASSTHRU:
212   case AArch64ISD::FNEG_MERGE_PASSTHRU:
213   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
214   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
215   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
216   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
217   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
218   case AArch64ISD::FRINT_MERGE_PASSTHRU:
219   case AArch64ISD::FROUND_MERGE_PASSTHRU:
220   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
221   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
222   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
223   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
224   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
225   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
226   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
227   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
228   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
229   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
230   case AArch64ISD::FABS_MERGE_PASSTHRU:
231     return true;
232   }
233 }
234 
AArch64TargetLowering(const TargetMachine & TM,const AArch64Subtarget & STI)235 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
236                                              const AArch64Subtarget &STI)
237     : TargetLowering(TM), Subtarget(&STI) {
238   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
239   // we have to make something up. Arbitrarily, choose ZeroOrOne.
240   setBooleanContents(ZeroOrOneBooleanContent);
241   // When comparing vectors the result sets the different elements in the
242   // vector to all-one or all-zero.
243   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
244 
245   // Set up the register classes.
246   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
247   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
248 
249   if (Subtarget->hasLS64()) {
250     addRegisterClass(MVT::i64x8, &AArch64::GPR64x8ClassRegClass);
251     setOperationAction(ISD::LOAD, MVT::i64x8, Custom);
252     setOperationAction(ISD::STORE, MVT::i64x8, Custom);
253   }
254 
255   if (Subtarget->hasFPARMv8()) {
256     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
257     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
258     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
259     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
260     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
261   }
262 
263   if (Subtarget->hasNEON()) {
264     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
265     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
266     // Someone set us up the NEON.
267     addDRTypeForNEON(MVT::v2f32);
268     addDRTypeForNEON(MVT::v8i8);
269     addDRTypeForNEON(MVT::v4i16);
270     addDRTypeForNEON(MVT::v2i32);
271     addDRTypeForNEON(MVT::v1i64);
272     addDRTypeForNEON(MVT::v1f64);
273     addDRTypeForNEON(MVT::v4f16);
274     if (Subtarget->hasBF16())
275       addDRTypeForNEON(MVT::v4bf16);
276 
277     addQRTypeForNEON(MVT::v4f32);
278     addQRTypeForNEON(MVT::v2f64);
279     addQRTypeForNEON(MVT::v16i8);
280     addQRTypeForNEON(MVT::v8i16);
281     addQRTypeForNEON(MVT::v4i32);
282     addQRTypeForNEON(MVT::v2i64);
283     addQRTypeForNEON(MVT::v8f16);
284     if (Subtarget->hasBF16())
285       addQRTypeForNEON(MVT::v8bf16);
286   }
287 
288   if (Subtarget->hasSVE()) {
289     // Add legal sve predicate types
290     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
291     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
292     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
293     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
294 
295     // Add legal sve data types
296     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
297     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
298     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
299     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
300 
301     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
302     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
303     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
304     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
305     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
306     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
307 
308     if (Subtarget->hasBF16()) {
309       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
310       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
311       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
312     }
313 
314     if (Subtarget->useSVEForFixedLengthVectors()) {
315       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
316         if (useSVEForFixedLengthVectorVT(VT))
317           addRegisterClass(VT, &AArch64::ZPRRegClass);
318 
319       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
320         if (useSVEForFixedLengthVectorVT(VT))
321           addRegisterClass(VT, &AArch64::ZPRRegClass);
322     }
323 
324     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
325       setOperationAction(ISD::SADDSAT, VT, Legal);
326       setOperationAction(ISD::UADDSAT, VT, Legal);
327       setOperationAction(ISD::SSUBSAT, VT, Legal);
328       setOperationAction(ISD::USUBSAT, VT, Legal);
329       setOperationAction(ISD::UREM, VT, Expand);
330       setOperationAction(ISD::SREM, VT, Expand);
331       setOperationAction(ISD::SDIVREM, VT, Expand);
332       setOperationAction(ISD::UDIVREM, VT, Expand);
333     }
334 
335     for (auto VT :
336          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
337            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
338       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
339 
340     for (auto VT :
341          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
342            MVT::nxv2f64 }) {
343       setCondCodeAction(ISD::SETO, VT, Expand);
344       setCondCodeAction(ISD::SETOLT, VT, Expand);
345       setCondCodeAction(ISD::SETLT, VT, Expand);
346       setCondCodeAction(ISD::SETOLE, VT, Expand);
347       setCondCodeAction(ISD::SETLE, VT, Expand);
348       setCondCodeAction(ISD::SETULT, VT, Expand);
349       setCondCodeAction(ISD::SETULE, VT, Expand);
350       setCondCodeAction(ISD::SETUGE, VT, Expand);
351       setCondCodeAction(ISD::SETUGT, VT, Expand);
352       setCondCodeAction(ISD::SETUEQ, VT, Expand);
353       setCondCodeAction(ISD::SETUNE, VT, Expand);
354 
355       setOperationAction(ISD::FREM, VT, Expand);
356       setOperationAction(ISD::FPOW, VT, Expand);
357       setOperationAction(ISD::FPOWI, VT, Expand);
358       setOperationAction(ISD::FCOS, VT, Expand);
359       setOperationAction(ISD::FSIN, VT, Expand);
360       setOperationAction(ISD::FSINCOS, VT, Expand);
361       setOperationAction(ISD::FEXP, VT, Expand);
362       setOperationAction(ISD::FEXP2, VT, Expand);
363       setOperationAction(ISD::FLOG, VT, Expand);
364       setOperationAction(ISD::FLOG2, VT, Expand);
365       setOperationAction(ISD::FLOG10, VT, Expand);
366     }
367   }
368 
369   // Compute derived properties from the register classes
370   computeRegisterProperties(Subtarget->getRegisterInfo());
371 
372   // Provide all sorts of operation actions
373   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
374   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
375   setOperationAction(ISD::SETCC, MVT::i32, Custom);
376   setOperationAction(ISD::SETCC, MVT::i64, Custom);
377   setOperationAction(ISD::SETCC, MVT::f16, Custom);
378   setOperationAction(ISD::SETCC, MVT::f32, Custom);
379   setOperationAction(ISD::SETCC, MVT::f64, Custom);
380   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
381   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
382   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
383   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
384   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
385   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
386   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
387   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
388   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
389   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
390   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
391   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
392   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
393   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
394   setOperationAction(ISD::SELECT, MVT::i32, Custom);
395   setOperationAction(ISD::SELECT, MVT::i64, Custom);
396   setOperationAction(ISD::SELECT, MVT::f16, Custom);
397   setOperationAction(ISD::SELECT, MVT::f32, Custom);
398   setOperationAction(ISD::SELECT, MVT::f64, Custom);
399   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
400   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
401   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
402   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
403   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
404   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
405   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
406 
407   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
408   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
409   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
410 
411   setOperationAction(ISD::FREM, MVT::f32, Expand);
412   setOperationAction(ISD::FREM, MVT::f64, Expand);
413   setOperationAction(ISD::FREM, MVT::f80, Expand);
414 
415   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
416 
417   // Custom lowering hooks are needed for XOR
418   // to fold it into CSINC/CSINV.
419   setOperationAction(ISD::XOR, MVT::i32, Custom);
420   setOperationAction(ISD::XOR, MVT::i64, Custom);
421 
422   // Virtually no operation on f128 is legal, but LLVM can't expand them when
423   // there's a valid register class, so we need custom operations in most cases.
424   setOperationAction(ISD::FABS, MVT::f128, Expand);
425   setOperationAction(ISD::FADD, MVT::f128, LibCall);
426   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
427   setOperationAction(ISD::FCOS, MVT::f128, Expand);
428   setOperationAction(ISD::FDIV, MVT::f128, LibCall);
429   setOperationAction(ISD::FMA, MVT::f128, Expand);
430   setOperationAction(ISD::FMUL, MVT::f128, LibCall);
431   setOperationAction(ISD::FNEG, MVT::f128, Expand);
432   setOperationAction(ISD::FPOW, MVT::f128, Expand);
433   setOperationAction(ISD::FREM, MVT::f128, Expand);
434   setOperationAction(ISD::FRINT, MVT::f128, Expand);
435   setOperationAction(ISD::FSIN, MVT::f128, Expand);
436   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
437   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
438   setOperationAction(ISD::FSUB, MVT::f128, LibCall);
439   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
440   setOperationAction(ISD::SETCC, MVT::f128, Custom);
441   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
442   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
443   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
444   setOperationAction(ISD::SELECT, MVT::f128, Custom);
445   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
446   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
447 
448   // Lowering for many of the conversions is actually specified by the non-f128
449   // type. The LowerXXX function will be trivial when f128 isn't involved.
450   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
451   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
452   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
453   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
454   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
455   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
456   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
457   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
458   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
459   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
460   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
461   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
462   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
463   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
464   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
465   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
466   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
467   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
468   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
469   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
470   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
471   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
472   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
473   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
474   setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
475   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
476   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
477   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
478   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
479   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
480 
481   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
482   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
483   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
484   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
485 
486   // Variable arguments.
487   setOperationAction(ISD::VASTART, MVT::Other, Custom);
488   setOperationAction(ISD::VAARG, MVT::Other, Custom);
489   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
490   setOperationAction(ISD::VAEND, MVT::Other, Expand);
491 
492   // Variable-sized objects.
493   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
494   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
495 
496   if (Subtarget->isTargetWindows())
497     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
498   else
499     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
500 
501   // Constant pool entries
502   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
503 
504   // BlockAddress
505   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
506 
507   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
508   setOperationAction(ISD::ADDC, MVT::i32, Custom);
509   setOperationAction(ISD::ADDE, MVT::i32, Custom);
510   setOperationAction(ISD::SUBC, MVT::i32, Custom);
511   setOperationAction(ISD::SUBE, MVT::i32, Custom);
512   setOperationAction(ISD::ADDC, MVT::i64, Custom);
513   setOperationAction(ISD::ADDE, MVT::i64, Custom);
514   setOperationAction(ISD::SUBC, MVT::i64, Custom);
515   setOperationAction(ISD::SUBE, MVT::i64, Custom);
516 
517   // AArch64 lacks both left-rotate and popcount instructions.
518   setOperationAction(ISD::ROTL, MVT::i32, Expand);
519   setOperationAction(ISD::ROTL, MVT::i64, Expand);
520   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
521     setOperationAction(ISD::ROTL, VT, Expand);
522     setOperationAction(ISD::ROTR, VT, Expand);
523   }
524 
525   // AArch64 doesn't have i32 MULH{S|U}.
526   setOperationAction(ISD::MULHU, MVT::i32, Expand);
527   setOperationAction(ISD::MULHS, MVT::i32, Expand);
528 
529   // AArch64 doesn't have {U|S}MUL_LOHI.
530   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
531   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
532 
533   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
534   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
535   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
536 
537   setOperationAction(ISD::ABS, MVT::i32, Custom);
538   setOperationAction(ISD::ABS, MVT::i64, Custom);
539 
540   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
541   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
542   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
543     setOperationAction(ISD::SDIVREM, VT, Expand);
544     setOperationAction(ISD::UDIVREM, VT, Expand);
545   }
546   setOperationAction(ISD::SREM, MVT::i32, Expand);
547   setOperationAction(ISD::SREM, MVT::i64, Expand);
548   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
549   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
550   setOperationAction(ISD::UREM, MVT::i32, Expand);
551   setOperationAction(ISD::UREM, MVT::i64, Expand);
552 
553   // Custom lower Add/Sub/Mul with overflow.
554   setOperationAction(ISD::SADDO, MVT::i32, Custom);
555   setOperationAction(ISD::SADDO, MVT::i64, Custom);
556   setOperationAction(ISD::UADDO, MVT::i32, Custom);
557   setOperationAction(ISD::UADDO, MVT::i64, Custom);
558   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
559   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
560   setOperationAction(ISD::USUBO, MVT::i32, Custom);
561   setOperationAction(ISD::USUBO, MVT::i64, Custom);
562   setOperationAction(ISD::SMULO, MVT::i32, Custom);
563   setOperationAction(ISD::SMULO, MVT::i64, Custom);
564   setOperationAction(ISD::UMULO, MVT::i32, Custom);
565   setOperationAction(ISD::UMULO, MVT::i64, Custom);
566 
567   setOperationAction(ISD::FSIN, MVT::f32, Expand);
568   setOperationAction(ISD::FSIN, MVT::f64, Expand);
569   setOperationAction(ISD::FCOS, MVT::f32, Expand);
570   setOperationAction(ISD::FCOS, MVT::f64, Expand);
571   setOperationAction(ISD::FPOW, MVT::f32, Expand);
572   setOperationAction(ISD::FPOW, MVT::f64, Expand);
573   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
574   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
575   if (Subtarget->hasFullFP16())
576     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
577   else
578     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
579 
580   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
581   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
582   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
583   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
584   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
585   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
586   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
587   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
588   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
589   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
590   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
591   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
592   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
593   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
594   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
595   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
596   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
597   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
598   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
599   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
600   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
601   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
602   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
603   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
604   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
605   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
606   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
607   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
608   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
609   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
610   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
611   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
612   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
613 
614   if (!Subtarget->hasFullFP16()) {
615     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
616     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
617     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
618     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
619     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
620     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
621     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
622     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
623     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
624     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
625     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
626     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
627     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
628     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
629     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
630     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
631     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
632     setOperationAction(ISD::FROUNDEVEN,  MVT::f16,  Promote);
633     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
634     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
635     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
636     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
637     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
638 
639     // promote v4f16 to v4f32 when that is known to be safe.
640     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
641     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
642     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
643     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
644     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
645     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
646     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
647     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
648 
649     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
650     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
651     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
652     setOperationAction(ISD::FROUNDEVEN,  MVT::v4f16, Expand);
653     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
654     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
655     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
656     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
657     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
658     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
659     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
660     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
661     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
662     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
663     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
664     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
665 
666     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
667     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
668     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
669     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
670     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
671     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
672     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
673     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
674     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
675     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
676     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
677     setOperationAction(ISD::FROUNDEVEN,  MVT::v8f16, Expand);
678     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
679     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
680     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
681     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
682     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
683     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
684     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
685     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
686     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
687   }
688 
689   // AArch64 has implementations of a lot of rounding-like FP operations.
690   for (MVT Ty : {MVT::f32, MVT::f64}) {
691     setOperationAction(ISD::FFLOOR, Ty, Legal);
692     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
693     setOperationAction(ISD::FCEIL, Ty, Legal);
694     setOperationAction(ISD::FRINT, Ty, Legal);
695     setOperationAction(ISD::FTRUNC, Ty, Legal);
696     setOperationAction(ISD::FROUND, Ty, Legal);
697     setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
698     setOperationAction(ISD::FMINNUM, Ty, Legal);
699     setOperationAction(ISD::FMAXNUM, Ty, Legal);
700     setOperationAction(ISD::FMINIMUM, Ty, Legal);
701     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
702     setOperationAction(ISD::LROUND, Ty, Legal);
703     setOperationAction(ISD::LLROUND, Ty, Legal);
704     setOperationAction(ISD::LRINT, Ty, Legal);
705     setOperationAction(ISD::LLRINT, Ty, Legal);
706   }
707 
708   if (Subtarget->hasFullFP16()) {
709     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
710     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
711     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
712     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
713     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
714     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
715     setOperationAction(ISD::FROUNDEVEN,  MVT::f16, Legal);
716     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
717     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
718     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
719     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
720   }
721 
722   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
723 
724   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
725   setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
726 
727   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
728   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
729   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
730   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
731   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
732 
733   // Generate outline atomics library calls only if LSE was not specified for
734   // subtarget
735   if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
736     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
737     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
738     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
739     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
740     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
741     setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
742     setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
743     setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
744     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
745     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
746     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
747     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
748     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
749     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
750     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
751     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
752     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
753     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
754     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
755     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
756     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
757     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
758     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
759     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
760     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
761 #define LCALLNAMES(A, B, N)                                                    \
762   setLibcallName(A##N##_RELAX, #B #N "_relax");                                \
763   setLibcallName(A##N##_ACQ, #B #N "_acq");                                    \
764   setLibcallName(A##N##_REL, #B #N "_rel");                                    \
765   setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
766 #define LCALLNAME4(A, B)                                                       \
767   LCALLNAMES(A, B, 1)                                                          \
768   LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
769 #define LCALLNAME5(A, B)                                                       \
770   LCALLNAMES(A, B, 1)                                                          \
771   LCALLNAMES(A, B, 2)                                                          \
772   LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
773     LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
774     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
775     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
776     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
777     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
778     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
779 #undef LCALLNAMES
780 #undef LCALLNAME4
781 #undef LCALLNAME5
782   }
783 
784   // 128-bit loads and stores can be done without expanding
785   setOperationAction(ISD::LOAD, MVT::i128, Custom);
786   setOperationAction(ISD::STORE, MVT::i128, Custom);
787 
788   // Aligned 128-bit loads and stores are single-copy atomic according to the
789   // v8.4a spec.
790   if (Subtarget->hasLSE2()) {
791     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
792     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
793   }
794 
795   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
796   // custom lowering, as there are no un-paired non-temporal stores and
797   // legalization will break up 256 bit inputs.
798   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
799   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
800   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
801   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
802   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
803   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
804   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
805 
806   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
807   // This requires the Performance Monitors extension.
808   if (Subtarget->hasPerfMon())
809     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
810 
811   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
812       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
813     // Issue __sincos_stret if available.
814     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
815     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
816   } else {
817     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
818     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
819   }
820 
821   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
822     // MSVCRT doesn't have powi; fall back to pow
823     setLibcallName(RTLIB::POWI_F32, nullptr);
824     setLibcallName(RTLIB::POWI_F64, nullptr);
825   }
826 
827   // Make floating-point constants legal for the large code model, so they don't
828   // become loads from the constant pool.
829   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
830     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
831     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
832   }
833 
834   // AArch64 does not have floating-point extending loads, i1 sign-extending
835   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
836   for (MVT VT : MVT::fp_valuetypes()) {
837     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
838     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
839     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
840     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
841   }
842   for (MVT VT : MVT::integer_valuetypes())
843     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
844 
845   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
846   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
847   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
848   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
849   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
850   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
851   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
852 
853   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
854   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
855   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
856 
857   // Indexed loads and stores are supported.
858   for (unsigned im = (unsigned)ISD::PRE_INC;
859        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
860     setIndexedLoadAction(im, MVT::i8, Legal);
861     setIndexedLoadAction(im, MVT::i16, Legal);
862     setIndexedLoadAction(im, MVT::i32, Legal);
863     setIndexedLoadAction(im, MVT::i64, Legal);
864     setIndexedLoadAction(im, MVT::f64, Legal);
865     setIndexedLoadAction(im, MVT::f32, Legal);
866     setIndexedLoadAction(im, MVT::f16, Legal);
867     setIndexedLoadAction(im, MVT::bf16, Legal);
868     setIndexedStoreAction(im, MVT::i8, Legal);
869     setIndexedStoreAction(im, MVT::i16, Legal);
870     setIndexedStoreAction(im, MVT::i32, Legal);
871     setIndexedStoreAction(im, MVT::i64, Legal);
872     setIndexedStoreAction(im, MVT::f64, Legal);
873     setIndexedStoreAction(im, MVT::f32, Legal);
874     setIndexedStoreAction(im, MVT::f16, Legal);
875     setIndexedStoreAction(im, MVT::bf16, Legal);
876   }
877 
878   // Trap.
879   setOperationAction(ISD::TRAP, MVT::Other, Legal);
880   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
881   setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
882 
883   // We combine OR nodes for bitfield operations.
884   setTargetDAGCombine(ISD::OR);
885   // Try to create BICs for vector ANDs.
886   setTargetDAGCombine(ISD::AND);
887 
888   // Vector add and sub nodes may conceal a high-half opportunity.
889   // Also, try to fold ADD into CSINC/CSINV..
890   setTargetDAGCombine(ISD::ADD);
891   setTargetDAGCombine(ISD::ABS);
892   setTargetDAGCombine(ISD::SUB);
893   setTargetDAGCombine(ISD::SRL);
894   setTargetDAGCombine(ISD::XOR);
895   setTargetDAGCombine(ISD::SINT_TO_FP);
896   setTargetDAGCombine(ISD::UINT_TO_FP);
897 
898   // TODO: Do the same for FP_TO_*INT_SAT.
899   setTargetDAGCombine(ISD::FP_TO_SINT);
900   setTargetDAGCombine(ISD::FP_TO_UINT);
901   setTargetDAGCombine(ISD::FDIV);
902 
903   // Try and combine setcc with csel
904   setTargetDAGCombine(ISD::SETCC);
905 
906   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
907 
908   setTargetDAGCombine(ISD::ANY_EXTEND);
909   setTargetDAGCombine(ISD::ZERO_EXTEND);
910   setTargetDAGCombine(ISD::SIGN_EXTEND);
911   setTargetDAGCombine(ISD::VECTOR_SPLICE);
912   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
913   setTargetDAGCombine(ISD::TRUNCATE);
914   setTargetDAGCombine(ISD::CONCAT_VECTORS);
915   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
916   setTargetDAGCombine(ISD::STORE);
917   if (Subtarget->supportsAddressTopByteIgnored())
918     setTargetDAGCombine(ISD::LOAD);
919 
920   setTargetDAGCombine(ISD::MUL);
921 
922   setTargetDAGCombine(ISD::SELECT);
923   setTargetDAGCombine(ISD::VSELECT);
924 
925   setTargetDAGCombine(ISD::INTRINSIC_VOID);
926   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
927   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
928   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
929   setTargetDAGCombine(ISD::VECREDUCE_ADD);
930   setTargetDAGCombine(ISD::STEP_VECTOR);
931 
932   setTargetDAGCombine(ISD::GlobalAddress);
933 
934   // In case of strict alignment, avoid an excessive number of byte wide stores.
935   MaxStoresPerMemsetOptSize = 8;
936   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
937                        ? MaxStoresPerMemsetOptSize : 32;
938 
939   MaxGluedStoresPerMemcpy = 4;
940   MaxStoresPerMemcpyOptSize = 4;
941   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
942                        ? MaxStoresPerMemcpyOptSize : 16;
943 
944   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
945 
946   MaxLoadsPerMemcmpOptSize = 4;
947   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
948                       ? MaxLoadsPerMemcmpOptSize : 8;
949 
950   setStackPointerRegisterToSaveRestore(AArch64::SP);
951 
952   setSchedulingPreference(Sched::Hybrid);
953 
954   EnableExtLdPromotion = true;
955 
956   // Set required alignment.
957   setMinFunctionAlignment(Align(4));
958   // Set preferred alignments.
959   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
960   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
961 
962   // Only change the limit for entries in a jump table if specified by
963   // the sub target, but not at the command line.
964   unsigned MaxJT = STI.getMaximumJumpTableSize();
965   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
966     setMaximumJumpTableSize(MaxJT);
967 
968   setHasExtractBitsInsn(true);
969 
970   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
971 
972   if (Subtarget->hasNEON()) {
973     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
974     // silliness like this:
975     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
976     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
977     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
978     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
979     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
980     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
981     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
982     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
983     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
984     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
985     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
986     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
987     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
988     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
989     setOperationAction(ISD::FROUNDEVEN, MVT::v1f64, Expand);
990     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
991     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
992     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
993     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
994     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
995     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
996     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
997     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
998     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
999     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
1000     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
1001 
1002     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
1003     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
1004     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
1005     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
1006     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
1007 
1008     setOperationAction(ISD::FP_TO_SINT_SAT, MVT::v1i64, Expand);
1009     setOperationAction(ISD::FP_TO_UINT_SAT, MVT::v1i64, Expand);
1010 
1011     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
1012 
1013     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
1014     // elements smaller than i32, so promote the input to i32 first.
1015     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
1016     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
1017     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
1018     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
1019     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v16i8, MVT::v16i32);
1020     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v16i8, MVT::v16i32);
1021 
1022     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
1023     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
1024     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
1025     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
1026     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
1027     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
1028     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
1029     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
1030     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
1031 
1032     if (Subtarget->hasFullFP16()) {
1033       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1034       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1035       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
1036       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1037     } else {
1038       // when AArch64 doesn't have fullfp16 support, promote the input
1039       // to i32 first.
1040       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
1041       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
1042       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
1043       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
1044     }
1045 
1046     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
1047     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
1048     setOperationAction(ISD::BITREVERSE, MVT::v8i8, Legal);
1049     setOperationAction(ISD::BITREVERSE, MVT::v16i8, Legal);
1050     setOperationAction(ISD::BITREVERSE, MVT::v2i32, Custom);
1051     setOperationAction(ISD::BITREVERSE, MVT::v4i32, Custom);
1052     setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1053     setOperationAction(ISD::BITREVERSE, MVT::v2i64, Custom);
1054     for (auto VT : {MVT::v1i64, MVT::v2i64}) {
1055       setOperationAction(ISD::UMAX, VT, Custom);
1056       setOperationAction(ISD::SMAX, VT, Custom);
1057       setOperationAction(ISD::UMIN, VT, Custom);
1058       setOperationAction(ISD::SMIN, VT, Custom);
1059     }
1060 
1061     // AArch64 doesn't have MUL.2d:
1062     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
1063     // Custom handling for some quad-vector types to detect MULL.
1064     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
1065     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1066     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1067 
1068     // Saturates
1069     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1070                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1071       setOperationAction(ISD::SADDSAT, VT, Legal);
1072       setOperationAction(ISD::UADDSAT, VT, Legal);
1073       setOperationAction(ISD::SSUBSAT, VT, Legal);
1074       setOperationAction(ISD::USUBSAT, VT, Legal);
1075     }
1076 
1077     for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
1078                    MVT::v4i32}) {
1079       setOperationAction(ISD::ABDS, VT, Legal);
1080       setOperationAction(ISD::ABDU, VT, Legal);
1081     }
1082 
1083     // Vector reductions
1084     for (MVT VT : { MVT::v4f16, MVT::v2f32,
1085                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1086       if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) {
1087         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1088         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1089 
1090         setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
1091       }
1092     }
1093     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1094                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1095       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1096       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1097       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1098       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1099       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1100     }
1101     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
1102 
1103     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
1104     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
1105     // Likewise, narrowing and extending vector loads/stores aren't handled
1106     // directly.
1107     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1108       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
1109 
1110       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
1111         setOperationAction(ISD::MULHS, VT, Legal);
1112         setOperationAction(ISD::MULHU, VT, Legal);
1113       } else {
1114         setOperationAction(ISD::MULHS, VT, Expand);
1115         setOperationAction(ISD::MULHU, VT, Expand);
1116       }
1117       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1118       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1119 
1120       setOperationAction(ISD::BSWAP, VT, Expand);
1121       setOperationAction(ISD::CTTZ, VT, Expand);
1122 
1123       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1124         setTruncStoreAction(VT, InnerVT, Expand);
1125         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1126         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1127         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1128       }
1129     }
1130 
1131     // AArch64 has implementations of a lot of rounding-like FP operations.
1132     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
1133       setOperationAction(ISD::FFLOOR, Ty, Legal);
1134       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1135       setOperationAction(ISD::FCEIL, Ty, Legal);
1136       setOperationAction(ISD::FRINT, Ty, Legal);
1137       setOperationAction(ISD::FTRUNC, Ty, Legal);
1138       setOperationAction(ISD::FROUND, Ty, Legal);
1139       setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
1140     }
1141 
1142     if (Subtarget->hasFullFP16()) {
1143       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
1144         setOperationAction(ISD::FFLOOR, Ty, Legal);
1145         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1146         setOperationAction(ISD::FCEIL, Ty, Legal);
1147         setOperationAction(ISD::FRINT, Ty, Legal);
1148         setOperationAction(ISD::FTRUNC, Ty, Legal);
1149         setOperationAction(ISD::FROUND, Ty, Legal);
1150         setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
1151       }
1152     }
1153 
1154     if (Subtarget->hasSVE())
1155       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
1156 
1157     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
1158 
1159     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i16, MVT::v4i8, Custom);
1160     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1161     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1162     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i32, MVT::v4i8, Custom);
1163     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1164     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1165   }
1166 
1167   if (Subtarget->hasSVE()) {
1168     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
1169       setOperationAction(ISD::BITREVERSE, VT, Custom);
1170       setOperationAction(ISD::BSWAP, VT, Custom);
1171       setOperationAction(ISD::CTLZ, VT, Custom);
1172       setOperationAction(ISD::CTPOP, VT, Custom);
1173       setOperationAction(ISD::CTTZ, VT, Custom);
1174       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1175       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1176       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1177       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1178       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1179       setOperationAction(ISD::MGATHER, VT, Custom);
1180       setOperationAction(ISD::MSCATTER, VT, Custom);
1181       setOperationAction(ISD::MLOAD, VT, Custom);
1182       setOperationAction(ISD::MUL, VT, Custom);
1183       setOperationAction(ISD::MULHS, VT, Custom);
1184       setOperationAction(ISD::MULHU, VT, Custom);
1185       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1186       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1187       setOperationAction(ISD::SELECT, VT, Custom);
1188       setOperationAction(ISD::SETCC, VT, Custom);
1189       setOperationAction(ISD::SDIV, VT, Custom);
1190       setOperationAction(ISD::UDIV, VT, Custom);
1191       setOperationAction(ISD::SMIN, VT, Custom);
1192       setOperationAction(ISD::UMIN, VT, Custom);
1193       setOperationAction(ISD::SMAX, VT, Custom);
1194       setOperationAction(ISD::UMAX, VT, Custom);
1195       setOperationAction(ISD::SHL, VT, Custom);
1196       setOperationAction(ISD::SRL, VT, Custom);
1197       setOperationAction(ISD::SRA, VT, Custom);
1198       setOperationAction(ISD::ABS, VT, Custom);
1199       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1200       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1201       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1202       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1203       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1204       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1205       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1206       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1207 
1208       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1209       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1210       setOperationAction(ISD::SELECT_CC, VT, Expand);
1211       setOperationAction(ISD::ROTL, VT, Expand);
1212       setOperationAction(ISD::ROTR, VT, Expand);
1213     }
1214 
1215     // Illegal unpacked integer vector types.
1216     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1217       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1219     }
1220 
1221     // Legalize unpacked bitcasts to REINTERPRET_CAST.
1222     for (auto VT : {MVT::nxv2i16, MVT::nxv4i16, MVT::nxv2i32, MVT::nxv2bf16,
1223                     MVT::nxv2f16, MVT::nxv4f16, MVT::nxv2f32})
1224       setOperationAction(ISD::BITCAST, VT, Custom);
1225 
1226     for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
1227       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1228       setOperationAction(ISD::SELECT, VT, Custom);
1229       setOperationAction(ISD::SETCC, VT, Custom);
1230       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1231       setOperationAction(ISD::TRUNCATE, VT, Custom);
1232       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1233       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1234       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1235 
1236       setOperationAction(ISD::SELECT_CC, VT, Expand);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1239 
1240       // There are no legal MVT::nxv16f## based types.
1241       if (VT != MVT::nxv16i1) {
1242         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1243         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1244       }
1245     }
1246 
1247     // NEON doesn't support masked loads/stores/gathers/scatters, but SVE does
1248     for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v1f64,
1249                     MVT::v2f64, MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1250                     MVT::v2i32, MVT::v4i32, MVT::v1i64, MVT::v2i64}) {
1251       setOperationAction(ISD::MLOAD, VT, Custom);
1252       setOperationAction(ISD::MSTORE, VT, Custom);
1253       setOperationAction(ISD::MGATHER, VT, Custom);
1254       setOperationAction(ISD::MSCATTER, VT, Custom);
1255     }
1256 
1257     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
1258       for (MVT InnerVT : MVT::fp_scalable_vector_valuetypes()) {
1259         // Avoid marking truncating FP stores as legal to prevent the
1260         // DAGCombiner from creating unsupported truncating stores.
1261         setTruncStoreAction(VT, InnerVT, Expand);
1262         // SVE does not have floating-point extending loads.
1263         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1264         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1265         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1266       }
1267     }
1268 
1269     // SVE supports truncating stores of 64 and 128-bit vectors
1270     setTruncStoreAction(MVT::v2i64, MVT::v2i8, Custom);
1271     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Custom);
1272     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Custom);
1273     setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
1274     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
1275 
1276     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1277                     MVT::nxv4f32, MVT::nxv2f64}) {
1278       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1280       setOperationAction(ISD::MGATHER, VT, Custom);
1281       setOperationAction(ISD::MSCATTER, VT, Custom);
1282       setOperationAction(ISD::MLOAD, VT, Custom);
1283       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1284       setOperationAction(ISD::SELECT, VT, Custom);
1285       setOperationAction(ISD::FADD, VT, Custom);
1286       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1287       setOperationAction(ISD::FDIV, VT, Custom);
1288       setOperationAction(ISD::FMA, VT, Custom);
1289       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1290       setOperationAction(ISD::FMAXNUM, VT, Custom);
1291       setOperationAction(ISD::FMINIMUM, VT, Custom);
1292       setOperationAction(ISD::FMINNUM, VT, Custom);
1293       setOperationAction(ISD::FMUL, VT, Custom);
1294       setOperationAction(ISD::FNEG, VT, Custom);
1295       setOperationAction(ISD::FSUB, VT, Custom);
1296       setOperationAction(ISD::FCEIL, VT, Custom);
1297       setOperationAction(ISD::FFLOOR, VT, Custom);
1298       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1299       setOperationAction(ISD::FRINT, VT, Custom);
1300       setOperationAction(ISD::FROUND, VT, Custom);
1301       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1302       setOperationAction(ISD::FTRUNC, VT, Custom);
1303       setOperationAction(ISD::FSQRT, VT, Custom);
1304       setOperationAction(ISD::FABS, VT, Custom);
1305       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1306       setOperationAction(ISD::FP_ROUND, VT, Custom);
1307       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1308       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1309       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1310       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1311       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1312 
1313       setOperationAction(ISD::SELECT_CC, VT, Expand);
1314     }
1315 
1316     for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
1317       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1318       setOperationAction(ISD::MGATHER, VT, Custom);
1319       setOperationAction(ISD::MSCATTER, VT, Custom);
1320       setOperationAction(ISD::MLOAD, VT, Custom);
1321     }
1322 
1323     setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
1324 
1325     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1326     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1327 
1328     // NOTE: Currently this has to happen after computeRegisterProperties rather
1329     // than the preferred option of combining it with the addRegisterClass call.
1330     if (Subtarget->useSVEForFixedLengthVectors()) {
1331       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1332         if (useSVEForFixedLengthVectorVT(VT))
1333           addTypeForFixedLengthSVE(VT);
1334       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1335         if (useSVEForFixedLengthVectorVT(VT))
1336           addTypeForFixedLengthSVE(VT);
1337 
1338       // 64bit results can mean a bigger than NEON input.
1339       for (auto VT : {MVT::v8i8, MVT::v4i16})
1340         setOperationAction(ISD::TRUNCATE, VT, Custom);
1341       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1342 
1343       // 128bit results imply a bigger than NEON input.
1344       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1345         setOperationAction(ISD::TRUNCATE, VT, Custom);
1346       for (auto VT : {MVT::v8f16, MVT::v4f32})
1347         setOperationAction(ISD::FP_ROUND, VT, Custom);
1348 
1349       // These operations are not supported on NEON but SVE can do them.
1350       setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1351       setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
1352       setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1353       setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
1354       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1355       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1356       setOperationAction(ISD::MULHS, MVT::v1i64, Custom);
1357       setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
1358       setOperationAction(ISD::MULHU, MVT::v1i64, Custom);
1359       setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
1360       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1361       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1362       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1363       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1364       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1365       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1366       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1367       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1368       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1369       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1370       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1371       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1372       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1373       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1374       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1375       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1376       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1377       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1378       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1379       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1380       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1381       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1382       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1383       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1384       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1385       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1386       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1387       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1388 
1389       // Int operations with no NEON support.
1390       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1391                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1392         setOperationAction(ISD::BITREVERSE, VT, Custom);
1393         setOperationAction(ISD::CTTZ, VT, Custom);
1394         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1395         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1396         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1397       }
1398 
1399       // FP operations with no NEON support.
1400       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
1401                       MVT::v1f64, MVT::v2f64})
1402         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1403 
1404       // Use SVE for vectors with more than 2 elements.
1405       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1406         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1407     }
1408 
1409     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64);
1410     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32);
1411     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16);
1412     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8);
1413   }
1414 
1415   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1416 }
1417 
addTypeForNEON(MVT VT)1418 void AArch64TargetLowering::addTypeForNEON(MVT VT) {
1419   assert(VT.isVector() && "VT should be a vector type");
1420 
1421   if (VT.isFloatingPoint()) {
1422     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1423     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1424     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1425   }
1426 
1427   // Mark vector float intrinsics as expand.
1428   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1429     setOperationAction(ISD::FSIN, VT, Expand);
1430     setOperationAction(ISD::FCOS, VT, Expand);
1431     setOperationAction(ISD::FPOW, VT, Expand);
1432     setOperationAction(ISD::FLOG, VT, Expand);
1433     setOperationAction(ISD::FLOG2, VT, Expand);
1434     setOperationAction(ISD::FLOG10, VT, Expand);
1435     setOperationAction(ISD::FEXP, VT, Expand);
1436     setOperationAction(ISD::FEXP2, VT, Expand);
1437   }
1438 
1439   // But we do support custom-lowering for FCOPYSIGN.
1440   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
1441       ((VT == MVT::v4f16 || VT == MVT::v8f16) && Subtarget->hasFullFP16()))
1442     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1443 
1444   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1445   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1446   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1447   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1448   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1449   setOperationAction(ISD::SRA, VT, Custom);
1450   setOperationAction(ISD::SRL, VT, Custom);
1451   setOperationAction(ISD::SHL, VT, Custom);
1452   setOperationAction(ISD::OR, VT, Custom);
1453   setOperationAction(ISD::SETCC, VT, Custom);
1454   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1455 
1456   setOperationAction(ISD::SELECT, VT, Expand);
1457   setOperationAction(ISD::SELECT_CC, VT, Expand);
1458   setOperationAction(ISD::VSELECT, VT, Expand);
1459   for (MVT InnerVT : MVT::all_valuetypes())
1460     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1461 
1462   // CNT supports only B element sizes, then use UADDLP to widen.
1463   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1464     setOperationAction(ISD::CTPOP, VT, Custom);
1465 
1466   setOperationAction(ISD::UDIV, VT, Expand);
1467   setOperationAction(ISD::SDIV, VT, Expand);
1468   setOperationAction(ISD::UREM, VT, Expand);
1469   setOperationAction(ISD::SREM, VT, Expand);
1470   setOperationAction(ISD::FREM, VT, Expand);
1471 
1472   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1473   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1474   setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
1475   setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
1476 
1477   if (!VT.isFloatingPoint())
1478     setOperationAction(ISD::ABS, VT, Legal);
1479 
1480   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1481   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1482     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1483       setOperationAction(Opcode, VT, Legal);
1484 
1485   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1486   if (VT.isFloatingPoint() &&
1487       VT.getVectorElementType() != MVT::bf16 &&
1488       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1489     for (unsigned Opcode :
1490          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1491       setOperationAction(Opcode, VT, Legal);
1492 
1493   if (Subtarget->isLittleEndian()) {
1494     for (unsigned im = (unsigned)ISD::PRE_INC;
1495          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1496       setIndexedLoadAction(im, VT, Legal);
1497       setIndexedStoreAction(im, VT, Legal);
1498     }
1499   }
1500 }
1501 
addTypeForFixedLengthSVE(MVT VT)1502 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1503   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1504 
1505   // By default everything must be expanded.
1506   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1507     setOperationAction(Op, VT, Expand);
1508 
1509   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1510   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1511 
1512   if (VT.isFloatingPoint()) {
1513     setCondCodeAction(ISD::SETO, VT, Expand);
1514     setCondCodeAction(ISD::SETOLT, VT, Expand);
1515     setCondCodeAction(ISD::SETLT, VT, Expand);
1516     setCondCodeAction(ISD::SETOLE, VT, Expand);
1517     setCondCodeAction(ISD::SETLE, VT, Expand);
1518     setCondCodeAction(ISD::SETULT, VT, Expand);
1519     setCondCodeAction(ISD::SETULE, VT, Expand);
1520     setCondCodeAction(ISD::SETUGE, VT, Expand);
1521     setCondCodeAction(ISD::SETUGT, VT, Expand);
1522     setCondCodeAction(ISD::SETUEQ, VT, Expand);
1523     setCondCodeAction(ISD::SETUNE, VT, Expand);
1524   }
1525 
1526   // Mark integer truncating stores as having custom lowering
1527   if (VT.isInteger()) {
1528     MVT InnerVT = VT.changeVectorElementType(MVT::i8);
1529     while (InnerVT != VT) {
1530       setTruncStoreAction(VT, InnerVT, Custom);
1531       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Custom);
1532       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Custom);
1533       InnerVT = InnerVT.changeVectorElementType(
1534           MVT::getIntegerVT(2 * InnerVT.getScalarSizeInBits()));
1535     }
1536   }
1537 
1538   // Lower fixed length vector operations to scalable equivalents.
1539   setOperationAction(ISD::ABS, VT, Custom);
1540   setOperationAction(ISD::ADD, VT, Custom);
1541   setOperationAction(ISD::AND, VT, Custom);
1542   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1543   setOperationAction(ISD::BITCAST, VT, Custom);
1544   setOperationAction(ISD::BITREVERSE, VT, Custom);
1545   setOperationAction(ISD::BSWAP, VT, Custom);
1546   setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1547   setOperationAction(ISD::CTLZ, VT, Custom);
1548   setOperationAction(ISD::CTPOP, VT, Custom);
1549   setOperationAction(ISD::CTTZ, VT, Custom);
1550   setOperationAction(ISD::FABS, VT, Custom);
1551   setOperationAction(ISD::FADD, VT, Custom);
1552   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1553   setOperationAction(ISD::FCEIL, VT, Custom);
1554   setOperationAction(ISD::FDIV, VT, Custom);
1555   setOperationAction(ISD::FFLOOR, VT, Custom);
1556   setOperationAction(ISD::FMA, VT, Custom);
1557   setOperationAction(ISD::FMAXIMUM, VT, Custom);
1558   setOperationAction(ISD::FMAXNUM, VT, Custom);
1559   setOperationAction(ISD::FMINIMUM, VT, Custom);
1560   setOperationAction(ISD::FMINNUM, VT, Custom);
1561   setOperationAction(ISD::FMUL, VT, Custom);
1562   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1563   setOperationAction(ISD::FNEG, VT, Custom);
1564   setOperationAction(ISD::FP_EXTEND, VT, Custom);
1565   setOperationAction(ISD::FP_ROUND, VT, Custom);
1566   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1567   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1568   setOperationAction(ISD::FRINT, VT, Custom);
1569   setOperationAction(ISD::FROUND, VT, Custom);
1570   setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1571   setOperationAction(ISD::FSQRT, VT, Custom);
1572   setOperationAction(ISD::FSUB, VT, Custom);
1573   setOperationAction(ISD::FTRUNC, VT, Custom);
1574   setOperationAction(ISD::LOAD, VT, Custom);
1575   setOperationAction(ISD::MGATHER, VT, Custom);
1576   setOperationAction(ISD::MLOAD, VT, Custom);
1577   setOperationAction(ISD::MSCATTER, VT, Custom);
1578   setOperationAction(ISD::MSTORE, VT, Custom);
1579   setOperationAction(ISD::MUL, VT, Custom);
1580   setOperationAction(ISD::MULHS, VT, Custom);
1581   setOperationAction(ISD::MULHU, VT, Custom);
1582   setOperationAction(ISD::OR, VT, Custom);
1583   setOperationAction(ISD::SDIV, VT, Custom);
1584   setOperationAction(ISD::SELECT, VT, Custom);
1585   setOperationAction(ISD::SETCC, VT, Custom);
1586   setOperationAction(ISD::SHL, VT, Custom);
1587   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1588   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1589   setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1590   setOperationAction(ISD::SMAX, VT, Custom);
1591   setOperationAction(ISD::SMIN, VT, Custom);
1592   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1593   setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1594   setOperationAction(ISD::SRA, VT, Custom);
1595   setOperationAction(ISD::SRL, VT, Custom);
1596   setOperationAction(ISD::STORE, VT, Custom);
1597   setOperationAction(ISD::SUB, VT, Custom);
1598   setOperationAction(ISD::TRUNCATE, VT, Custom);
1599   setOperationAction(ISD::UDIV, VT, Custom);
1600   setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1601   setOperationAction(ISD::UMAX, VT, Custom);
1602   setOperationAction(ISD::UMIN, VT, Custom);
1603   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1604   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1605   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1606   setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1607   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1608   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1609   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1610   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1611   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1612   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1613   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1614   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1615   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1616   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1617   setOperationAction(ISD::VSELECT, VT, Custom);
1618   setOperationAction(ISD::XOR, VT, Custom);
1619   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1620 }
1621 
addDRTypeForNEON(MVT VT)1622 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1623   addRegisterClass(VT, &AArch64::FPR64RegClass);
1624   addTypeForNEON(VT);
1625 }
1626 
addQRTypeForNEON(MVT VT)1627 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1628   addRegisterClass(VT, &AArch64::FPR128RegClass);
1629   addTypeForNEON(VT);
1630 }
1631 
getSetCCResultType(const DataLayout &,LLVMContext & C,EVT VT) const1632 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1633                                               LLVMContext &C, EVT VT) const {
1634   if (!VT.isVector())
1635     return MVT::i32;
1636   if (VT.isScalableVector())
1637     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1638   return VT.changeVectorElementTypeToInteger();
1639 }
1640 
optimizeLogicalImm(SDValue Op,unsigned Size,uint64_t Imm,const APInt & Demanded,TargetLowering::TargetLoweringOpt & TLO,unsigned NewOpc)1641 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1642                                const APInt &Demanded,
1643                                TargetLowering::TargetLoweringOpt &TLO,
1644                                unsigned NewOpc) {
1645   uint64_t OldImm = Imm, NewImm, Enc;
1646   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1647 
1648   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1649   // bimm64.
1650   if (Imm == 0 || Imm == Mask ||
1651       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1652     return false;
1653 
1654   unsigned EltSize = Size;
1655   uint64_t DemandedBits = Demanded.getZExtValue();
1656 
1657   // Clear bits that are not demanded.
1658   Imm &= DemandedBits;
1659 
1660   while (true) {
1661     // The goal here is to set the non-demanded bits in a way that minimizes
1662     // the number of switching between 0 and 1. In order to achieve this goal,
1663     // we set the non-demanded bits to the value of the preceding demanded bits.
1664     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1665     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1666     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1667     // The final result is 0b11000011.
1668     uint64_t NonDemandedBits = ~DemandedBits;
1669     uint64_t InvertedImm = ~Imm & DemandedBits;
1670     uint64_t RotatedImm =
1671         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1672         NonDemandedBits;
1673     uint64_t Sum = RotatedImm + NonDemandedBits;
1674     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1675     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1676     NewImm = (Imm | Ones) & Mask;
1677 
1678     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1679     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1680     // we halve the element size and continue the search.
1681     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1682       break;
1683 
1684     // We cannot shrink the element size any further if it is 2-bits.
1685     if (EltSize == 2)
1686       return false;
1687 
1688     EltSize /= 2;
1689     Mask >>= EltSize;
1690     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1691 
1692     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1693     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1694       return false;
1695 
1696     // Merge the upper and lower halves of Imm and DemandedBits.
1697     Imm |= Hi;
1698     DemandedBits |= DemandedBitsHi;
1699   }
1700 
1701   ++NumOptimizedImms;
1702 
1703   // Replicate the element across the register width.
1704   while (EltSize < Size) {
1705     NewImm |= NewImm << EltSize;
1706     EltSize *= 2;
1707   }
1708 
1709   (void)OldImm;
1710   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1711          "demanded bits should never be altered");
1712   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1713 
1714   // Create the new constant immediate node.
1715   EVT VT = Op.getValueType();
1716   SDLoc DL(Op);
1717   SDValue New;
1718 
1719   // If the new constant immediate is all-zeros or all-ones, let the target
1720   // independent DAG combine optimize this node.
1721   if (NewImm == 0 || NewImm == OrigMask) {
1722     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1723                           TLO.DAG.getConstant(NewImm, DL, VT));
1724   // Otherwise, create a machine node so that target independent DAG combine
1725   // doesn't undo this optimization.
1726   } else {
1727     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1728     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1729     New = SDValue(
1730         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1731   }
1732 
1733   return TLO.CombineTo(Op, New);
1734 }
1735 
targetShrinkDemandedConstant(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,TargetLoweringOpt & TLO) const1736 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1737     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1738     TargetLoweringOpt &TLO) const {
1739   // Delay this optimization to as late as possible.
1740   if (!TLO.LegalOps)
1741     return false;
1742 
1743   if (!EnableOptimizeLogicalImm)
1744     return false;
1745 
1746   EVT VT = Op.getValueType();
1747   if (VT.isVector())
1748     return false;
1749 
1750   unsigned Size = VT.getSizeInBits();
1751   assert((Size == 32 || Size == 64) &&
1752          "i32 or i64 is expected after legalization.");
1753 
1754   // Exit early if we demand all bits.
1755   if (DemandedBits.countPopulation() == Size)
1756     return false;
1757 
1758   unsigned NewOpc;
1759   switch (Op.getOpcode()) {
1760   default:
1761     return false;
1762   case ISD::AND:
1763     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1764     break;
1765   case ISD::OR:
1766     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1767     break;
1768   case ISD::XOR:
1769     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1770     break;
1771   }
1772   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1773   if (!C)
1774     return false;
1775   uint64_t Imm = C->getZExtValue();
1776   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1777 }
1778 
1779 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1780 /// Mask are known to be either zero or one and return them Known.
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const1781 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1782     const SDValue Op, KnownBits &Known,
1783     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1784   switch (Op.getOpcode()) {
1785   default:
1786     break;
1787   case AArch64ISD::CSEL: {
1788     KnownBits Known2;
1789     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1790     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1791     Known = KnownBits::commonBits(Known, Known2);
1792     break;
1793   }
1794   case AArch64ISD::LOADgot:
1795   case AArch64ISD::ADDlow: {
1796     if (!Subtarget->isTargetILP32())
1797       break;
1798     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1799     Known.Zero = APInt::getHighBitsSet(64, 32);
1800     break;
1801   }
1802   case AArch64ISD::ASSERT_ZEXT_BOOL: {
1803     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1804     Known.Zero |= APInt(Known.getBitWidth(), 0xFE);
1805     break;
1806   }
1807   case ISD::INTRINSIC_W_CHAIN: {
1808     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1809     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1810     switch (IntID) {
1811     default: return;
1812     case Intrinsic::aarch64_ldaxr:
1813     case Intrinsic::aarch64_ldxr: {
1814       unsigned BitWidth = Known.getBitWidth();
1815       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1816       unsigned MemBits = VT.getScalarSizeInBits();
1817       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1818       return;
1819     }
1820     }
1821     break;
1822   }
1823   case ISD::INTRINSIC_WO_CHAIN:
1824   case ISD::INTRINSIC_VOID: {
1825     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1826     switch (IntNo) {
1827     default:
1828       break;
1829     case Intrinsic::aarch64_neon_umaxv:
1830     case Intrinsic::aarch64_neon_uminv: {
1831       // Figure out the datatype of the vector operand. The UMINV instruction
1832       // will zero extend the result, so we can mark as known zero all the
1833       // bits larger than the element datatype. 32-bit or larget doesn't need
1834       // this as those are legal types and will be handled by isel directly.
1835       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1836       unsigned BitWidth = Known.getBitWidth();
1837       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1838         assert(BitWidth >= 8 && "Unexpected width!");
1839         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1840         Known.Zero |= Mask;
1841       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1842         assert(BitWidth >= 16 && "Unexpected width!");
1843         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1844         Known.Zero |= Mask;
1845       }
1846       break;
1847     } break;
1848     }
1849   }
1850   }
1851 }
1852 
getScalarShiftAmountTy(const DataLayout & DL,EVT) const1853 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1854                                                   EVT) const {
1855   return MVT::i64;
1856 }
1857 
allowsMisalignedMemoryAccesses(EVT VT,unsigned AddrSpace,Align Alignment,MachineMemOperand::Flags Flags,bool * Fast) const1858 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1859     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1860     bool *Fast) const {
1861   if (Subtarget->requiresStrictAlign())
1862     return false;
1863 
1864   if (Fast) {
1865     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1866     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1867             // See comments in performSTORECombine() for more details about
1868             // these conditions.
1869 
1870             // Code that uses clang vector extensions can mark that it
1871             // wants unaligned accesses to be treated as fast by
1872             // underspecifying alignment to be 1 or 2.
1873             Alignment <= 2 ||
1874 
1875             // Disregard v2i64. Memcpy lowering produces those and splitting
1876             // them regresses performance on micro-benchmarks and olden/bh.
1877             VT == MVT::v2i64;
1878   }
1879   return true;
1880 }
1881 
1882 // Same as above but handling LLTs instead.
allowsMisalignedMemoryAccesses(LLT Ty,unsigned AddrSpace,Align Alignment,MachineMemOperand::Flags Flags,bool * Fast) const1883 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1884     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1885     bool *Fast) const {
1886   if (Subtarget->requiresStrictAlign())
1887     return false;
1888 
1889   if (Fast) {
1890     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1891     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1892             Ty.getSizeInBytes() != 16 ||
1893             // See comments in performSTORECombine() for more details about
1894             // these conditions.
1895 
1896             // Code that uses clang vector extensions can mark that it
1897             // wants unaligned accesses to be treated as fast by
1898             // underspecifying alignment to be 1 or 2.
1899             Alignment <= 2 ||
1900 
1901             // Disregard v2i64. Memcpy lowering produces those and splitting
1902             // them regresses performance on micro-benchmarks and olden/bh.
1903             Ty == LLT::fixed_vector(2, 64);
1904   }
1905   return true;
1906 }
1907 
1908 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const1909 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1910                                       const TargetLibraryInfo *libInfo) const {
1911   return AArch64::createFastISel(funcInfo, libInfo);
1912 }
1913 
getTargetNodeName(unsigned Opcode) const1914 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1915 #define MAKE_CASE(V)                                                           \
1916   case V:                                                                      \
1917     return #V;
1918   switch ((AArch64ISD::NodeType)Opcode) {
1919   case AArch64ISD::FIRST_NUMBER:
1920     break;
1921     MAKE_CASE(AArch64ISD::CALL)
1922     MAKE_CASE(AArch64ISD::ADRP)
1923     MAKE_CASE(AArch64ISD::ADR)
1924     MAKE_CASE(AArch64ISD::ADDlow)
1925     MAKE_CASE(AArch64ISD::LOADgot)
1926     MAKE_CASE(AArch64ISD::RET_FLAG)
1927     MAKE_CASE(AArch64ISD::BRCOND)
1928     MAKE_CASE(AArch64ISD::CSEL)
1929     MAKE_CASE(AArch64ISD::CSINV)
1930     MAKE_CASE(AArch64ISD::CSNEG)
1931     MAKE_CASE(AArch64ISD::CSINC)
1932     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1933     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1934     MAKE_CASE(AArch64ISD::ADD_PRED)
1935     MAKE_CASE(AArch64ISD::MUL_PRED)
1936     MAKE_CASE(AArch64ISD::MULHS_PRED)
1937     MAKE_CASE(AArch64ISD::MULHU_PRED)
1938     MAKE_CASE(AArch64ISD::SDIV_PRED)
1939     MAKE_CASE(AArch64ISD::SHL_PRED)
1940     MAKE_CASE(AArch64ISD::SMAX_PRED)
1941     MAKE_CASE(AArch64ISD::SMIN_PRED)
1942     MAKE_CASE(AArch64ISD::SRA_PRED)
1943     MAKE_CASE(AArch64ISD::SRL_PRED)
1944     MAKE_CASE(AArch64ISD::SUB_PRED)
1945     MAKE_CASE(AArch64ISD::UDIV_PRED)
1946     MAKE_CASE(AArch64ISD::UMAX_PRED)
1947     MAKE_CASE(AArch64ISD::UMIN_PRED)
1948     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
1949     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
1950     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
1951     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
1952     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
1953     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
1954     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
1955     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
1956     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
1957     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
1958     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
1959     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
1960     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
1961     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
1962     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
1963     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
1964     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
1965     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
1966     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
1967     MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
1968     MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
1969     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1970     MAKE_CASE(AArch64ISD::ADC)
1971     MAKE_CASE(AArch64ISD::SBC)
1972     MAKE_CASE(AArch64ISD::ADDS)
1973     MAKE_CASE(AArch64ISD::SUBS)
1974     MAKE_CASE(AArch64ISD::ADCS)
1975     MAKE_CASE(AArch64ISD::SBCS)
1976     MAKE_CASE(AArch64ISD::ANDS)
1977     MAKE_CASE(AArch64ISD::CCMP)
1978     MAKE_CASE(AArch64ISD::CCMN)
1979     MAKE_CASE(AArch64ISD::FCCMP)
1980     MAKE_CASE(AArch64ISD::FCMP)
1981     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1982     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1983     MAKE_CASE(AArch64ISD::DUP)
1984     MAKE_CASE(AArch64ISD::DUPLANE8)
1985     MAKE_CASE(AArch64ISD::DUPLANE16)
1986     MAKE_CASE(AArch64ISD::DUPLANE32)
1987     MAKE_CASE(AArch64ISD::DUPLANE64)
1988     MAKE_CASE(AArch64ISD::MOVI)
1989     MAKE_CASE(AArch64ISD::MOVIshift)
1990     MAKE_CASE(AArch64ISD::MOVIedit)
1991     MAKE_CASE(AArch64ISD::MOVImsl)
1992     MAKE_CASE(AArch64ISD::FMOV)
1993     MAKE_CASE(AArch64ISD::MVNIshift)
1994     MAKE_CASE(AArch64ISD::MVNImsl)
1995     MAKE_CASE(AArch64ISD::BICi)
1996     MAKE_CASE(AArch64ISD::ORRi)
1997     MAKE_CASE(AArch64ISD::BSP)
1998     MAKE_CASE(AArch64ISD::EXTR)
1999     MAKE_CASE(AArch64ISD::ZIP1)
2000     MAKE_CASE(AArch64ISD::ZIP2)
2001     MAKE_CASE(AArch64ISD::UZP1)
2002     MAKE_CASE(AArch64ISD::UZP2)
2003     MAKE_CASE(AArch64ISD::TRN1)
2004     MAKE_CASE(AArch64ISD::TRN2)
2005     MAKE_CASE(AArch64ISD::REV16)
2006     MAKE_CASE(AArch64ISD::REV32)
2007     MAKE_CASE(AArch64ISD::REV64)
2008     MAKE_CASE(AArch64ISD::EXT)
2009     MAKE_CASE(AArch64ISD::SPLICE)
2010     MAKE_CASE(AArch64ISD::VSHL)
2011     MAKE_CASE(AArch64ISD::VLSHR)
2012     MAKE_CASE(AArch64ISD::VASHR)
2013     MAKE_CASE(AArch64ISD::VSLI)
2014     MAKE_CASE(AArch64ISD::VSRI)
2015     MAKE_CASE(AArch64ISD::CMEQ)
2016     MAKE_CASE(AArch64ISD::CMGE)
2017     MAKE_CASE(AArch64ISD::CMGT)
2018     MAKE_CASE(AArch64ISD::CMHI)
2019     MAKE_CASE(AArch64ISD::CMHS)
2020     MAKE_CASE(AArch64ISD::FCMEQ)
2021     MAKE_CASE(AArch64ISD::FCMGE)
2022     MAKE_CASE(AArch64ISD::FCMGT)
2023     MAKE_CASE(AArch64ISD::CMEQz)
2024     MAKE_CASE(AArch64ISD::CMGEz)
2025     MAKE_CASE(AArch64ISD::CMGTz)
2026     MAKE_CASE(AArch64ISD::CMLEz)
2027     MAKE_CASE(AArch64ISD::CMLTz)
2028     MAKE_CASE(AArch64ISD::FCMEQz)
2029     MAKE_CASE(AArch64ISD::FCMGEz)
2030     MAKE_CASE(AArch64ISD::FCMGTz)
2031     MAKE_CASE(AArch64ISD::FCMLEz)
2032     MAKE_CASE(AArch64ISD::FCMLTz)
2033     MAKE_CASE(AArch64ISD::SADDV)
2034     MAKE_CASE(AArch64ISD::UADDV)
2035     MAKE_CASE(AArch64ISD::SRHADD)
2036     MAKE_CASE(AArch64ISD::URHADD)
2037     MAKE_CASE(AArch64ISD::SHADD)
2038     MAKE_CASE(AArch64ISD::UHADD)
2039     MAKE_CASE(AArch64ISD::SDOT)
2040     MAKE_CASE(AArch64ISD::UDOT)
2041     MAKE_CASE(AArch64ISD::SMINV)
2042     MAKE_CASE(AArch64ISD::UMINV)
2043     MAKE_CASE(AArch64ISD::SMAXV)
2044     MAKE_CASE(AArch64ISD::UMAXV)
2045     MAKE_CASE(AArch64ISD::SADDV_PRED)
2046     MAKE_CASE(AArch64ISD::UADDV_PRED)
2047     MAKE_CASE(AArch64ISD::SMAXV_PRED)
2048     MAKE_CASE(AArch64ISD::UMAXV_PRED)
2049     MAKE_CASE(AArch64ISD::SMINV_PRED)
2050     MAKE_CASE(AArch64ISD::UMINV_PRED)
2051     MAKE_CASE(AArch64ISD::ORV_PRED)
2052     MAKE_CASE(AArch64ISD::EORV_PRED)
2053     MAKE_CASE(AArch64ISD::ANDV_PRED)
2054     MAKE_CASE(AArch64ISD::CLASTA_N)
2055     MAKE_CASE(AArch64ISD::CLASTB_N)
2056     MAKE_CASE(AArch64ISD::LASTA)
2057     MAKE_CASE(AArch64ISD::LASTB)
2058     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
2059     MAKE_CASE(AArch64ISD::LS64_BUILD)
2060     MAKE_CASE(AArch64ISD::LS64_EXTRACT)
2061     MAKE_CASE(AArch64ISD::TBL)
2062     MAKE_CASE(AArch64ISD::FADD_PRED)
2063     MAKE_CASE(AArch64ISD::FADDA_PRED)
2064     MAKE_CASE(AArch64ISD::FADDV_PRED)
2065     MAKE_CASE(AArch64ISD::FDIV_PRED)
2066     MAKE_CASE(AArch64ISD::FMA_PRED)
2067     MAKE_CASE(AArch64ISD::FMAX_PRED)
2068     MAKE_CASE(AArch64ISD::FMAXV_PRED)
2069     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
2070     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
2071     MAKE_CASE(AArch64ISD::FMIN_PRED)
2072     MAKE_CASE(AArch64ISD::FMINV_PRED)
2073     MAKE_CASE(AArch64ISD::FMINNM_PRED)
2074     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
2075     MAKE_CASE(AArch64ISD::FMUL_PRED)
2076     MAKE_CASE(AArch64ISD::FSUB_PRED)
2077     MAKE_CASE(AArch64ISD::BIC)
2078     MAKE_CASE(AArch64ISD::BIT)
2079     MAKE_CASE(AArch64ISD::CBZ)
2080     MAKE_CASE(AArch64ISD::CBNZ)
2081     MAKE_CASE(AArch64ISD::TBZ)
2082     MAKE_CASE(AArch64ISD::TBNZ)
2083     MAKE_CASE(AArch64ISD::TC_RETURN)
2084     MAKE_CASE(AArch64ISD::PREFETCH)
2085     MAKE_CASE(AArch64ISD::SITOF)
2086     MAKE_CASE(AArch64ISD::UITOF)
2087     MAKE_CASE(AArch64ISD::NVCAST)
2088     MAKE_CASE(AArch64ISD::MRS)
2089     MAKE_CASE(AArch64ISD::SQSHL_I)
2090     MAKE_CASE(AArch64ISD::UQSHL_I)
2091     MAKE_CASE(AArch64ISD::SRSHR_I)
2092     MAKE_CASE(AArch64ISD::URSHR_I)
2093     MAKE_CASE(AArch64ISD::SQSHLU_I)
2094     MAKE_CASE(AArch64ISD::WrapperLarge)
2095     MAKE_CASE(AArch64ISD::LD2post)
2096     MAKE_CASE(AArch64ISD::LD3post)
2097     MAKE_CASE(AArch64ISD::LD4post)
2098     MAKE_CASE(AArch64ISD::ST2post)
2099     MAKE_CASE(AArch64ISD::ST3post)
2100     MAKE_CASE(AArch64ISD::ST4post)
2101     MAKE_CASE(AArch64ISD::LD1x2post)
2102     MAKE_CASE(AArch64ISD::LD1x3post)
2103     MAKE_CASE(AArch64ISD::LD1x4post)
2104     MAKE_CASE(AArch64ISD::ST1x2post)
2105     MAKE_CASE(AArch64ISD::ST1x3post)
2106     MAKE_CASE(AArch64ISD::ST1x4post)
2107     MAKE_CASE(AArch64ISD::LD1DUPpost)
2108     MAKE_CASE(AArch64ISD::LD2DUPpost)
2109     MAKE_CASE(AArch64ISD::LD3DUPpost)
2110     MAKE_CASE(AArch64ISD::LD4DUPpost)
2111     MAKE_CASE(AArch64ISD::LD1LANEpost)
2112     MAKE_CASE(AArch64ISD::LD2LANEpost)
2113     MAKE_CASE(AArch64ISD::LD3LANEpost)
2114     MAKE_CASE(AArch64ISD::LD4LANEpost)
2115     MAKE_CASE(AArch64ISD::ST2LANEpost)
2116     MAKE_CASE(AArch64ISD::ST3LANEpost)
2117     MAKE_CASE(AArch64ISD::ST4LANEpost)
2118     MAKE_CASE(AArch64ISD::SMULL)
2119     MAKE_CASE(AArch64ISD::UMULL)
2120     MAKE_CASE(AArch64ISD::FRECPE)
2121     MAKE_CASE(AArch64ISD::FRECPS)
2122     MAKE_CASE(AArch64ISD::FRSQRTE)
2123     MAKE_CASE(AArch64ISD::FRSQRTS)
2124     MAKE_CASE(AArch64ISD::STG)
2125     MAKE_CASE(AArch64ISD::STZG)
2126     MAKE_CASE(AArch64ISD::ST2G)
2127     MAKE_CASE(AArch64ISD::STZ2G)
2128     MAKE_CASE(AArch64ISD::SUNPKHI)
2129     MAKE_CASE(AArch64ISD::SUNPKLO)
2130     MAKE_CASE(AArch64ISD::UUNPKHI)
2131     MAKE_CASE(AArch64ISD::UUNPKLO)
2132     MAKE_CASE(AArch64ISD::INSR)
2133     MAKE_CASE(AArch64ISD::PTEST)
2134     MAKE_CASE(AArch64ISD::PTRUE)
2135     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
2136     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
2137     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
2138     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
2139     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
2140     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
2141     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
2142     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
2143     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
2144     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
2145     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
2146     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
2147     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
2148     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
2149     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
2150     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
2151     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
2152     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
2153     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
2154     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
2155     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
2156     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
2157     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
2158     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
2159     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
2160     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
2161     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
2162     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
2163     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
2164     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
2165     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
2166     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
2167     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
2168     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
2169     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
2170     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
2171     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
2172     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
2173     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
2174     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
2175     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
2176     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
2177     MAKE_CASE(AArch64ISD::ST1_PRED)
2178     MAKE_CASE(AArch64ISD::SST1_PRED)
2179     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
2180     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
2181     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
2182     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
2183     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
2184     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
2185     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
2186     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
2187     MAKE_CASE(AArch64ISD::LDP)
2188     MAKE_CASE(AArch64ISD::STP)
2189     MAKE_CASE(AArch64ISD::STNP)
2190     MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
2191     MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
2192     MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
2193     MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
2194     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
2195     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
2196     MAKE_CASE(AArch64ISD::UADDLP)
2197     MAKE_CASE(AArch64ISD::CALL_RVMARKER)
2198     MAKE_CASE(AArch64ISD::ASSERT_ZEXT_BOOL)
2199   }
2200 #undef MAKE_CASE
2201   return nullptr;
2202 }
2203 
2204 MachineBasicBlock *
EmitF128CSEL(MachineInstr & MI,MachineBasicBlock * MBB) const2205 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
2206                                     MachineBasicBlock *MBB) const {
2207   // We materialise the F128CSEL pseudo-instruction as some control flow and a
2208   // phi node:
2209 
2210   // OrigBB:
2211   //     [... previous instrs leading to comparison ...]
2212   //     b.ne TrueBB
2213   //     b EndBB
2214   // TrueBB:
2215   //     ; Fallthrough
2216   // EndBB:
2217   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
2218 
2219   MachineFunction *MF = MBB->getParent();
2220   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2221   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2222   DebugLoc DL = MI.getDebugLoc();
2223   MachineFunction::iterator It = ++MBB->getIterator();
2224 
2225   Register DestReg = MI.getOperand(0).getReg();
2226   Register IfTrueReg = MI.getOperand(1).getReg();
2227   Register IfFalseReg = MI.getOperand(2).getReg();
2228   unsigned CondCode = MI.getOperand(3).getImm();
2229   bool NZCVKilled = MI.getOperand(4).isKill();
2230 
2231   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
2232   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
2233   MF->insert(It, TrueBB);
2234   MF->insert(It, EndBB);
2235 
2236   // Transfer rest of current basic-block to EndBB
2237   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
2238                 MBB->end());
2239   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
2240 
2241   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
2242   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
2243   MBB->addSuccessor(TrueBB);
2244   MBB->addSuccessor(EndBB);
2245 
2246   // TrueBB falls through to the end.
2247   TrueBB->addSuccessor(EndBB);
2248 
2249   if (!NZCVKilled) {
2250     TrueBB->addLiveIn(AArch64::NZCV);
2251     EndBB->addLiveIn(AArch64::NZCV);
2252   }
2253 
2254   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
2255       .addReg(IfTrueReg)
2256       .addMBB(TrueBB)
2257       .addReg(IfFalseReg)
2258       .addMBB(MBB);
2259 
2260   MI.eraseFromParent();
2261   return EndBB;
2262 }
2263 
EmitLoweredCatchRet(MachineInstr & MI,MachineBasicBlock * BB) const2264 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
2265        MachineInstr &MI, MachineBasicBlock *BB) const {
2266   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2267              BB->getParent()->getFunction().getPersonalityFn())) &&
2268          "SEH does not use catchret!");
2269   return BB;
2270 }
2271 
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const2272 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
2273     MachineInstr &MI, MachineBasicBlock *BB) const {
2274   switch (MI.getOpcode()) {
2275   default:
2276 #ifndef NDEBUG
2277     MI.dump();
2278 #endif
2279     llvm_unreachable("Unexpected instruction for custom inserter!");
2280 
2281   case AArch64::F128CSEL:
2282     return EmitF128CSEL(MI, BB);
2283 
2284   case TargetOpcode::STACKMAP:
2285   case TargetOpcode::PATCHPOINT:
2286   case TargetOpcode::STATEPOINT:
2287     return emitPatchPoint(MI, BB);
2288 
2289   case AArch64::CATCHRET:
2290     return EmitLoweredCatchRet(MI, BB);
2291   }
2292 }
2293 
2294 //===----------------------------------------------------------------------===//
2295 // AArch64 Lowering private implementation.
2296 //===----------------------------------------------------------------------===//
2297 
2298 //===----------------------------------------------------------------------===//
2299 // Lowering Code
2300 //===----------------------------------------------------------------------===//
2301 
2302 // Forward declarations of SVE fixed length lowering helpers
2303 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT);
2304 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2305 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2306 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
2307                                                 SelectionDAG &DAG);
2308 
2309 /// isZerosVector - Check whether SDNode N is a zero-filled vector.
isZerosVector(const SDNode * N)2310 static bool isZerosVector(const SDNode *N) {
2311   // Look through a bit convert.
2312   while (N->getOpcode() == ISD::BITCAST)
2313     N = N->getOperand(0).getNode();
2314 
2315   if (ISD::isConstantSplatVectorAllZeros(N))
2316     return true;
2317 
2318   if (N->getOpcode() != AArch64ISD::DUP)
2319     return false;
2320 
2321   auto Opnd0 = N->getOperand(0);
2322   auto *CINT = dyn_cast<ConstantSDNode>(Opnd0);
2323   auto *CFP = dyn_cast<ConstantFPSDNode>(Opnd0);
2324   return (CINT && CINT->isZero()) || (CFP && CFP->isZero());
2325 }
2326 
2327 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
2328 /// CC
changeIntCCToAArch64CC(ISD::CondCode CC)2329 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
2330   switch (CC) {
2331   default:
2332     llvm_unreachable("Unknown condition code!");
2333   case ISD::SETNE:
2334     return AArch64CC::NE;
2335   case ISD::SETEQ:
2336     return AArch64CC::EQ;
2337   case ISD::SETGT:
2338     return AArch64CC::GT;
2339   case ISD::SETGE:
2340     return AArch64CC::GE;
2341   case ISD::SETLT:
2342     return AArch64CC::LT;
2343   case ISD::SETLE:
2344     return AArch64CC::LE;
2345   case ISD::SETUGT:
2346     return AArch64CC::HI;
2347   case ISD::SETUGE:
2348     return AArch64CC::HS;
2349   case ISD::SETULT:
2350     return AArch64CC::LO;
2351   case ISD::SETULE:
2352     return AArch64CC::LS;
2353   }
2354 }
2355 
2356 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
changeFPCCToAArch64CC(ISD::CondCode CC,AArch64CC::CondCode & CondCode,AArch64CC::CondCode & CondCode2)2357 static void changeFPCCToAArch64CC(ISD::CondCode CC,
2358                                   AArch64CC::CondCode &CondCode,
2359                                   AArch64CC::CondCode &CondCode2) {
2360   CondCode2 = AArch64CC::AL;
2361   switch (CC) {
2362   default:
2363     llvm_unreachable("Unknown FP condition!");
2364   case ISD::SETEQ:
2365   case ISD::SETOEQ:
2366     CondCode = AArch64CC::EQ;
2367     break;
2368   case ISD::SETGT:
2369   case ISD::SETOGT:
2370     CondCode = AArch64CC::GT;
2371     break;
2372   case ISD::SETGE:
2373   case ISD::SETOGE:
2374     CondCode = AArch64CC::GE;
2375     break;
2376   case ISD::SETOLT:
2377     CondCode = AArch64CC::MI;
2378     break;
2379   case ISD::SETOLE:
2380     CondCode = AArch64CC::LS;
2381     break;
2382   case ISD::SETONE:
2383     CondCode = AArch64CC::MI;
2384     CondCode2 = AArch64CC::GT;
2385     break;
2386   case ISD::SETO:
2387     CondCode = AArch64CC::VC;
2388     break;
2389   case ISD::SETUO:
2390     CondCode = AArch64CC::VS;
2391     break;
2392   case ISD::SETUEQ:
2393     CondCode = AArch64CC::EQ;
2394     CondCode2 = AArch64CC::VS;
2395     break;
2396   case ISD::SETUGT:
2397     CondCode = AArch64CC::HI;
2398     break;
2399   case ISD::SETUGE:
2400     CondCode = AArch64CC::PL;
2401     break;
2402   case ISD::SETLT:
2403   case ISD::SETULT:
2404     CondCode = AArch64CC::LT;
2405     break;
2406   case ISD::SETLE:
2407   case ISD::SETULE:
2408     CondCode = AArch64CC::LE;
2409     break;
2410   case ISD::SETNE:
2411   case ISD::SETUNE:
2412     CondCode = AArch64CC::NE;
2413     break;
2414   }
2415 }
2416 
2417 /// Convert a DAG fp condition code to an AArch64 CC.
2418 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2419 /// should be AND'ed instead of OR'ed.
changeFPCCToANDAArch64CC(ISD::CondCode CC,AArch64CC::CondCode & CondCode,AArch64CC::CondCode & CondCode2)2420 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2421                                      AArch64CC::CondCode &CondCode,
2422                                      AArch64CC::CondCode &CondCode2) {
2423   CondCode2 = AArch64CC::AL;
2424   switch (CC) {
2425   default:
2426     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2427     assert(CondCode2 == AArch64CC::AL);
2428     break;
2429   case ISD::SETONE:
2430     // (a one b)
2431     // == ((a olt b) || (a ogt b))
2432     // == ((a ord b) && (a une b))
2433     CondCode = AArch64CC::VC;
2434     CondCode2 = AArch64CC::NE;
2435     break;
2436   case ISD::SETUEQ:
2437     // (a ueq b)
2438     // == ((a uno b) || (a oeq b))
2439     // == ((a ule b) && (a uge b))
2440     CondCode = AArch64CC::PL;
2441     CondCode2 = AArch64CC::LE;
2442     break;
2443   }
2444 }
2445 
2446 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2447 /// CC usable with the vector instructions. Fewer operations are available
2448 /// without a real NZCV register, so we have to use less efficient combinations
2449 /// to get the same effect.
changeVectorFPCCToAArch64CC(ISD::CondCode CC,AArch64CC::CondCode & CondCode,AArch64CC::CondCode & CondCode2,bool & Invert)2450 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2451                                         AArch64CC::CondCode &CondCode,
2452                                         AArch64CC::CondCode &CondCode2,
2453                                         bool &Invert) {
2454   Invert = false;
2455   switch (CC) {
2456   default:
2457     // Mostly the scalar mappings work fine.
2458     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2459     break;
2460   case ISD::SETUO:
2461     Invert = true;
2462     LLVM_FALLTHROUGH;
2463   case ISD::SETO:
2464     CondCode = AArch64CC::MI;
2465     CondCode2 = AArch64CC::GE;
2466     break;
2467   case ISD::SETUEQ:
2468   case ISD::SETULT:
2469   case ISD::SETULE:
2470   case ISD::SETUGT:
2471   case ISD::SETUGE:
2472     // All of the compare-mask comparisons are ordered, but we can switch
2473     // between the two by a double inversion. E.g. ULE == !OGT.
2474     Invert = true;
2475     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2476                           CondCode, CondCode2);
2477     break;
2478   }
2479 }
2480 
isLegalArithImmed(uint64_t C)2481 static bool isLegalArithImmed(uint64_t C) {
2482   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2483   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2484   LLVM_DEBUG(dbgs() << "Is imm " << C
2485                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2486   return IsLegal;
2487 }
2488 
2489 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
2490 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
2491 // can be set differently by this operation. It comes down to whether
2492 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
2493 // everything is fine. If not then the optimization is wrong. Thus general
2494 // comparisons are only valid if op2 != 0.
2495 //
2496 // So, finally, the only LLVM-native comparisons that don't mention C and V
2497 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
2498 // the absence of information about op2.
isCMN(SDValue Op,ISD::CondCode CC)2499 static bool isCMN(SDValue Op, ISD::CondCode CC) {
2500   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
2501          (CC == ISD::SETEQ || CC == ISD::SETNE);
2502 }
2503 
emitStrictFPComparison(SDValue LHS,SDValue RHS,const SDLoc & dl,SelectionDAG & DAG,SDValue Chain,bool IsSignaling)2504 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
2505                                       SelectionDAG &DAG, SDValue Chain,
2506                                       bool IsSignaling) {
2507   EVT VT = LHS.getValueType();
2508   assert(VT != MVT::f128);
2509   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
2510   unsigned Opcode =
2511       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
2512   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
2513 }
2514 
emitComparison(SDValue LHS,SDValue RHS,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG)2515 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2516                               const SDLoc &dl, SelectionDAG &DAG) {
2517   EVT VT = LHS.getValueType();
2518   const bool FullFP16 =
2519     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2520 
2521   if (VT.isFloatingPoint()) {
2522     assert(VT != MVT::f128);
2523     if (VT == MVT::f16 && !FullFP16) {
2524       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
2525       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
2526       VT = MVT::f32;
2527     }
2528     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
2529   }
2530 
2531   // The CMP instruction is just an alias for SUBS, and representing it as
2532   // SUBS means that it's possible to get CSE with subtract operations.
2533   // A later phase can perform the optimization of setting the destination
2534   // register to WZR/XZR if it ends up being unused.
2535   unsigned Opcode = AArch64ISD::SUBS;
2536 
2537   if (isCMN(RHS, CC)) {
2538     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2539     Opcode = AArch64ISD::ADDS;
2540     RHS = RHS.getOperand(1);
2541   } else if (isCMN(LHS, CC)) {
2542     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2543     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2544     Opcode = AArch64ISD::ADDS;
2545     LHS = LHS.getOperand(1);
2546   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2547     if (LHS.getOpcode() == ISD::AND) {
2548       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2549       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2550       // of the signed comparisons.
2551       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2552                                            DAG.getVTList(VT, MVT_CC),
2553                                            LHS.getOperand(0),
2554                                            LHS.getOperand(1));
2555       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2556       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2557       return ANDSNode.getValue(1);
2558     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2559       // Use result of ANDS
2560       return LHS.getValue(1);
2561     }
2562   }
2563 
2564   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2565       .getValue(1);
2566 }
2567 
2568 /// \defgroup AArch64CCMP CMP;CCMP matching
2569 ///
2570 /// These functions deal with the formation of CMP;CCMP;... sequences.
2571 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2572 /// a comparison. They set the NZCV flags to a predefined value if their
2573 /// predicate is false. This allows to express arbitrary conjunctions, for
2574 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2575 /// expressed as:
2576 ///   cmp A
2577 ///   ccmp B, inv(CB), CA
2578 ///   check for CB flags
2579 ///
2580 /// This naturally lets us implement chains of AND operations with SETCC
2581 /// operands. And we can even implement some other situations by transforming
2582 /// them:
2583 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2584 ///     negating the flags used in a CCMP/FCCMP operations.
2585 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2586 ///     by negating the flags we test for afterwards. i.e.
2587 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2588 ///   - Note that we can only ever negate all previously processed results.
2589 ///     What we can not implement by flipping the flags to test is a negation
2590 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2591 ///     far, so the 2nd sub-tree we emit would also affect the first).
2592 /// With those tools we can implement some OR operations:
2593 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2594 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2595 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2596 ///     elimination rules from earlier to implement the whole thing as a
2597 ///     CCMP/FCCMP chain.
2598 ///
2599 /// As complete example:
2600 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2601 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2602 /// can be reassociated to:
2603 ///     or (and (setCC (cmp C)) setCD (cmp D))
2604 //         (or (setCA (cmp A)) (setCB (cmp B)))
2605 /// can be transformed to:
2606 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2607 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2608 /// which can be implemented as:
2609 ///   cmp C
2610 ///   ccmp D, inv(CD), CC
2611 ///   ccmp A, CA, inv(CD)
2612 ///   ccmp B, CB, inv(CA)
2613 ///   check for CB flags
2614 ///
2615 /// A counterexample is "or (and A B) (and C D)" which translates to
2616 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2617 /// can only implement 1 of the inner (not) operations, but not both!
2618 /// @{
2619 
2620 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
emitConditionalComparison(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue CCOp,AArch64CC::CondCode Predicate,AArch64CC::CondCode OutCC,const SDLoc & DL,SelectionDAG & DAG)2621 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2622                                          ISD::CondCode CC, SDValue CCOp,
2623                                          AArch64CC::CondCode Predicate,
2624                                          AArch64CC::CondCode OutCC,
2625                                          const SDLoc &DL, SelectionDAG &DAG) {
2626   unsigned Opcode = 0;
2627   const bool FullFP16 =
2628     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2629 
2630   if (LHS.getValueType().isFloatingPoint()) {
2631     assert(LHS.getValueType() != MVT::f128);
2632     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2633       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2634       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2635     }
2636     Opcode = AArch64ISD::FCCMP;
2637   } else if (RHS.getOpcode() == ISD::SUB) {
2638     SDValue SubOp0 = RHS.getOperand(0);
2639     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2640       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2641       Opcode = AArch64ISD::CCMN;
2642       RHS = RHS.getOperand(1);
2643     }
2644   }
2645   if (Opcode == 0)
2646     Opcode = AArch64ISD::CCMP;
2647 
2648   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2649   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2650   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2651   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2652   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2653 }
2654 
2655 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2656 /// expressed as a conjunction. See \ref AArch64CCMP.
2657 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2658 ///                     changing the conditions on the SETCC tests.
2659 ///                     (this means we can call emitConjunctionRec() with
2660 ///                      Negate==true on this sub-tree)
2661 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2662 ///                     cannot do the negation naturally. We are required to
2663 ///                     emit the subtree first in this case.
2664 /// \param WillNegate   Is true if are called when the result of this
2665 ///                     subexpression must be negated. This happens when the
2666 ///                     outer expression is an OR. We can use this fact to know
2667 ///                     that we have a double negation (or (or ...) ...) that
2668 ///                     can be implemented for free.
canEmitConjunction(const SDValue Val,bool & CanNegate,bool & MustBeFirst,bool WillNegate,unsigned Depth=0)2669 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2670                                bool &MustBeFirst, bool WillNegate,
2671                                unsigned Depth = 0) {
2672   if (!Val.hasOneUse())
2673     return false;
2674   unsigned Opcode = Val->getOpcode();
2675   if (Opcode == ISD::SETCC) {
2676     if (Val->getOperand(0).getValueType() == MVT::f128)
2677       return false;
2678     CanNegate = true;
2679     MustBeFirst = false;
2680     return true;
2681   }
2682   // Protect against exponential runtime and stack overflow.
2683   if (Depth > 6)
2684     return false;
2685   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2686     bool IsOR = Opcode == ISD::OR;
2687     SDValue O0 = Val->getOperand(0);
2688     SDValue O1 = Val->getOperand(1);
2689     bool CanNegateL;
2690     bool MustBeFirstL;
2691     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2692       return false;
2693     bool CanNegateR;
2694     bool MustBeFirstR;
2695     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2696       return false;
2697 
2698     if (MustBeFirstL && MustBeFirstR)
2699       return false;
2700 
2701     if (IsOR) {
2702       // For an OR expression we need to be able to naturally negate at least
2703       // one side or we cannot do the transformation at all.
2704       if (!CanNegateL && !CanNegateR)
2705         return false;
2706       // If we the result of the OR will be negated and we can naturally negate
2707       // the leafs, then this sub-tree as a whole negates naturally.
2708       CanNegate = WillNegate && CanNegateL && CanNegateR;
2709       // If we cannot naturally negate the whole sub-tree, then this must be
2710       // emitted first.
2711       MustBeFirst = !CanNegate;
2712     } else {
2713       assert(Opcode == ISD::AND && "Must be OR or AND");
2714       // We cannot naturally negate an AND operation.
2715       CanNegate = false;
2716       MustBeFirst = MustBeFirstL || MustBeFirstR;
2717     }
2718     return true;
2719   }
2720   return false;
2721 }
2722 
2723 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2724 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2725 /// Tries to transform the given i1 producing node @p Val to a series compare
2726 /// and conditional compare operations. @returns an NZCV flags producing node
2727 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2728 /// transformation was not possible.
2729 /// \p Negate is true if we want this sub-tree being negated just by changing
2730 /// SETCC conditions.
emitConjunctionRec(SelectionDAG & DAG,SDValue Val,AArch64CC::CondCode & OutCC,bool Negate,SDValue CCOp,AArch64CC::CondCode Predicate)2731 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2732     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2733     AArch64CC::CondCode Predicate) {
2734   // We're at a tree leaf, produce a conditional comparison operation.
2735   unsigned Opcode = Val->getOpcode();
2736   if (Opcode == ISD::SETCC) {
2737     SDValue LHS = Val->getOperand(0);
2738     SDValue RHS = Val->getOperand(1);
2739     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2740     bool isInteger = LHS.getValueType().isInteger();
2741     if (Negate)
2742       CC = getSetCCInverse(CC, LHS.getValueType());
2743     SDLoc DL(Val);
2744     // Determine OutCC and handle FP special case.
2745     if (isInteger) {
2746       OutCC = changeIntCCToAArch64CC(CC);
2747     } else {
2748       assert(LHS.getValueType().isFloatingPoint());
2749       AArch64CC::CondCode ExtraCC;
2750       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2751       // Some floating point conditions can't be tested with a single condition
2752       // code. Construct an additional comparison in this case.
2753       if (ExtraCC != AArch64CC::AL) {
2754         SDValue ExtraCmp;
2755         if (!CCOp.getNode())
2756           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2757         else
2758           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2759                                                ExtraCC, DL, DAG);
2760         CCOp = ExtraCmp;
2761         Predicate = ExtraCC;
2762       }
2763     }
2764 
2765     // Produce a normal comparison if we are first in the chain
2766     if (!CCOp)
2767       return emitComparison(LHS, RHS, CC, DL, DAG);
2768     // Otherwise produce a ccmp.
2769     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2770                                      DAG);
2771   }
2772   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2773 
2774   bool IsOR = Opcode == ISD::OR;
2775 
2776   SDValue LHS = Val->getOperand(0);
2777   bool CanNegateL;
2778   bool MustBeFirstL;
2779   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2780   assert(ValidL && "Valid conjunction/disjunction tree");
2781   (void)ValidL;
2782 
2783   SDValue RHS = Val->getOperand(1);
2784   bool CanNegateR;
2785   bool MustBeFirstR;
2786   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2787   assert(ValidR && "Valid conjunction/disjunction tree");
2788   (void)ValidR;
2789 
2790   // Swap sub-tree that must come first to the right side.
2791   if (MustBeFirstL) {
2792     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2793     std::swap(LHS, RHS);
2794     std::swap(CanNegateL, CanNegateR);
2795     std::swap(MustBeFirstL, MustBeFirstR);
2796   }
2797 
2798   bool NegateR;
2799   bool NegateAfterR;
2800   bool NegateL;
2801   bool NegateAfterAll;
2802   if (Opcode == ISD::OR) {
2803     // Swap the sub-tree that we can negate naturally to the left.
2804     if (!CanNegateL) {
2805       assert(CanNegateR && "at least one side must be negatable");
2806       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2807       assert(!Negate);
2808       std::swap(LHS, RHS);
2809       NegateR = false;
2810       NegateAfterR = true;
2811     } else {
2812       // Negate the left sub-tree if possible, otherwise negate the result.
2813       NegateR = CanNegateR;
2814       NegateAfterR = !CanNegateR;
2815     }
2816     NegateL = true;
2817     NegateAfterAll = !Negate;
2818   } else {
2819     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2820     assert(!Negate && "Valid conjunction/disjunction tree");
2821 
2822     NegateL = false;
2823     NegateR = false;
2824     NegateAfterR = false;
2825     NegateAfterAll = false;
2826   }
2827 
2828   // Emit sub-trees.
2829   AArch64CC::CondCode RHSCC;
2830   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2831   if (NegateAfterR)
2832     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2833   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2834   if (NegateAfterAll)
2835     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2836   return CmpL;
2837 }
2838 
2839 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2840 /// In some cases this is even possible with OR operations in the expression.
2841 /// See \ref AArch64CCMP.
2842 /// \see emitConjunctionRec().
emitConjunction(SelectionDAG & DAG,SDValue Val,AArch64CC::CondCode & OutCC)2843 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2844                                AArch64CC::CondCode &OutCC) {
2845   bool DummyCanNegate;
2846   bool DummyMustBeFirst;
2847   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2848     return SDValue();
2849 
2850   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2851 }
2852 
2853 /// @}
2854 
2855 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2856 /// extension operations.
getCmpOperandFoldingProfit(SDValue Op)2857 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2858   auto isSupportedExtend = [&](SDValue V) {
2859     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2860       return true;
2861 
2862     if (V.getOpcode() == ISD::AND)
2863       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2864         uint64_t Mask = MaskCst->getZExtValue();
2865         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2866       }
2867 
2868     return false;
2869   };
2870 
2871   if (!Op.hasOneUse())
2872     return 0;
2873 
2874   if (isSupportedExtend(Op))
2875     return 1;
2876 
2877   unsigned Opc = Op.getOpcode();
2878   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2879     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2880       uint64_t Shift = ShiftCst->getZExtValue();
2881       if (isSupportedExtend(Op.getOperand(0)))
2882         return (Shift <= 4) ? 2 : 1;
2883       EVT VT = Op.getValueType();
2884       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2885         return 1;
2886     }
2887 
2888   return 0;
2889 }
2890 
getAArch64Cmp(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue & AArch64cc,SelectionDAG & DAG,const SDLoc & dl)2891 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2892                              SDValue &AArch64cc, SelectionDAG &DAG,
2893                              const SDLoc &dl) {
2894   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2895     EVT VT = RHS.getValueType();
2896     uint64_t C = RHSC->getZExtValue();
2897     if (!isLegalArithImmed(C)) {
2898       // Constant does not fit, try adjusting it by one?
2899       switch (CC) {
2900       default:
2901         break;
2902       case ISD::SETLT:
2903       case ISD::SETGE:
2904         if ((VT == MVT::i32 && C != 0x80000000 &&
2905              isLegalArithImmed((uint32_t)(C - 1))) ||
2906             (VT == MVT::i64 && C != 0x80000000ULL &&
2907              isLegalArithImmed(C - 1ULL))) {
2908           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2909           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2910           RHS = DAG.getConstant(C, dl, VT);
2911         }
2912         break;
2913       case ISD::SETULT:
2914       case ISD::SETUGE:
2915         if ((VT == MVT::i32 && C != 0 &&
2916              isLegalArithImmed((uint32_t)(C - 1))) ||
2917             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2918           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2919           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2920           RHS = DAG.getConstant(C, dl, VT);
2921         }
2922         break;
2923       case ISD::SETLE:
2924       case ISD::SETGT:
2925         if ((VT == MVT::i32 && C != INT32_MAX &&
2926              isLegalArithImmed((uint32_t)(C + 1))) ||
2927             (VT == MVT::i64 && C != INT64_MAX &&
2928              isLegalArithImmed(C + 1ULL))) {
2929           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2930           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2931           RHS = DAG.getConstant(C, dl, VT);
2932         }
2933         break;
2934       case ISD::SETULE:
2935       case ISD::SETUGT:
2936         if ((VT == MVT::i32 && C != UINT32_MAX &&
2937              isLegalArithImmed((uint32_t)(C + 1))) ||
2938             (VT == MVT::i64 && C != UINT64_MAX &&
2939              isLegalArithImmed(C + 1ULL))) {
2940           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2941           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2942           RHS = DAG.getConstant(C, dl, VT);
2943         }
2944         break;
2945       }
2946     }
2947   }
2948 
2949   // Comparisons are canonicalized so that the RHS operand is simpler than the
2950   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2951   // can fold some shift+extend operations on the RHS operand, so swap the
2952   // operands if that can be done.
2953   //
2954   // For example:
2955   //    lsl     w13, w11, #1
2956   //    cmp     w13, w12
2957   // can be turned into:
2958   //    cmp     w12, w11, lsl #1
2959   if (!isa<ConstantSDNode>(RHS) ||
2960       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2961     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2962 
2963     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2964       std::swap(LHS, RHS);
2965       CC = ISD::getSetCCSwappedOperands(CC);
2966     }
2967   }
2968 
2969   SDValue Cmp;
2970   AArch64CC::CondCode AArch64CC;
2971   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2972     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2973 
2974     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2975     // For the i8 operand, the largest immediate is 255, so this can be easily
2976     // encoded in the compare instruction. For the i16 operand, however, the
2977     // largest immediate cannot be encoded in the compare.
2978     // Therefore, use a sign extending load and cmn to avoid materializing the
2979     // -1 constant. For example,
2980     // movz w1, #65535
2981     // ldrh w0, [x0, #0]
2982     // cmp w0, w1
2983     // >
2984     // ldrsh w0, [x0, #0]
2985     // cmn w0, #1
2986     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2987     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2988     // ensure both the LHS and RHS are truly zero extended and to make sure the
2989     // transformation is profitable.
2990     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2991         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2992         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2993         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2994       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2995       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2996         SDValue SExt =
2997             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2998                         DAG.getValueType(MVT::i16));
2999         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
3000                                                    RHS.getValueType()),
3001                              CC, dl, DAG);
3002         AArch64CC = changeIntCCToAArch64CC(CC);
3003       }
3004     }
3005 
3006     if (!Cmp && (RHSC->isZero() || RHSC->isOne())) {
3007       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
3008         if ((CC == ISD::SETNE) ^ RHSC->isZero())
3009           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
3010       }
3011     }
3012   }
3013 
3014   if (!Cmp) {
3015     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3016     AArch64CC = changeIntCCToAArch64CC(CC);
3017   }
3018   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
3019   return Cmp;
3020 }
3021 
3022 static std::pair<SDValue, SDValue>
getAArch64XALUOOp(AArch64CC::CondCode & CC,SDValue Op,SelectionDAG & DAG)3023 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
3024   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
3025          "Unsupported value type");
3026   SDValue Value, Overflow;
3027   SDLoc DL(Op);
3028   SDValue LHS = Op.getOperand(0);
3029   SDValue RHS = Op.getOperand(1);
3030   unsigned Opc = 0;
3031   switch (Op.getOpcode()) {
3032   default:
3033     llvm_unreachable("Unknown overflow instruction!");
3034   case ISD::SADDO:
3035     Opc = AArch64ISD::ADDS;
3036     CC = AArch64CC::VS;
3037     break;
3038   case ISD::UADDO:
3039     Opc = AArch64ISD::ADDS;
3040     CC = AArch64CC::HS;
3041     break;
3042   case ISD::SSUBO:
3043     Opc = AArch64ISD::SUBS;
3044     CC = AArch64CC::VS;
3045     break;
3046   case ISD::USUBO:
3047     Opc = AArch64ISD::SUBS;
3048     CC = AArch64CC::LO;
3049     break;
3050   // Multiply needs a little bit extra work.
3051   case ISD::SMULO:
3052   case ISD::UMULO: {
3053     CC = AArch64CC::NE;
3054     bool IsSigned = Op.getOpcode() == ISD::SMULO;
3055     if (Op.getValueType() == MVT::i32) {
3056       // Extend to 64-bits, then perform a 64-bit multiply.
3057       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3058       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
3059       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
3060       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3061       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3062 
3063       // Check that the result fits into a 32-bit integer.
3064       SDVTList VTs = DAG.getVTList(MVT::i64, MVT_CC);
3065       if (IsSigned) {
3066         // cmp xreg, wreg, sxtw
3067         SDValue SExtMul = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Value);
3068         Overflow =
3069             DAG.getNode(AArch64ISD::SUBS, DL, VTs, Mul, SExtMul).getValue(1);
3070       } else {
3071         // tst xreg, #0xffffffff00000000
3072         SDValue UpperBits = DAG.getConstant(0xFFFFFFFF00000000, DL, MVT::i64);
3073         Overflow =
3074             DAG.getNode(AArch64ISD::ANDS, DL, VTs, Mul, UpperBits).getValue(1);
3075       }
3076       break;
3077     }
3078     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
3079     // For the 64 bit multiply
3080     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3081     if (IsSigned) {
3082       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
3083       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
3084                                       DAG.getConstant(63, DL, MVT::i64));
3085       // It is important that LowerBits is last, otherwise the arithmetic
3086       // shift will not be folded into the compare (SUBS).
3087       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3088       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
3089                      .getValue(1);
3090     } else {
3091       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
3092       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3093       Overflow =
3094           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
3095                       DAG.getConstant(0, DL, MVT::i64),
3096                       UpperBits).getValue(1);
3097     }
3098     break;
3099   }
3100   } // switch (...)
3101 
3102   if (Opc) {
3103     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
3104 
3105     // Emit the AArch64 operation with overflow check.
3106     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
3107     Overflow = Value.getValue(1);
3108   }
3109   return std::make_pair(Value, Overflow);
3110 }
3111 
LowerXOR(SDValue Op,SelectionDAG & DAG) const3112 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
3113   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3114     return LowerToScalableOp(Op, DAG);
3115 
3116   SDValue Sel = Op.getOperand(0);
3117   SDValue Other = Op.getOperand(1);
3118   SDLoc dl(Sel);
3119 
3120   // If the operand is an overflow checking operation, invert the condition
3121   // code and kill the Not operation. I.e., transform:
3122   // (xor (overflow_op_bool, 1))
3123   //   -->
3124   // (csel 1, 0, invert(cc), overflow_op_bool)
3125   // ... which later gets transformed to just a cset instruction with an
3126   // inverted condition code, rather than a cset + eor sequence.
3127   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
3128     // Only lower legal XALUO ops.
3129     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
3130       return SDValue();
3131 
3132     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3133     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3134     AArch64CC::CondCode CC;
3135     SDValue Value, Overflow;
3136     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
3137     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3138     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
3139                        CCVal, Overflow);
3140   }
3141   // If neither operand is a SELECT_CC, give up.
3142   if (Sel.getOpcode() != ISD::SELECT_CC)
3143     std::swap(Sel, Other);
3144   if (Sel.getOpcode() != ISD::SELECT_CC)
3145     return Op;
3146 
3147   // The folding we want to perform is:
3148   // (xor x, (select_cc a, b, cc, 0, -1) )
3149   //   -->
3150   // (csel x, (xor x, -1), cc ...)
3151   //
3152   // The latter will get matched to a CSINV instruction.
3153 
3154   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
3155   SDValue LHS = Sel.getOperand(0);
3156   SDValue RHS = Sel.getOperand(1);
3157   SDValue TVal = Sel.getOperand(2);
3158   SDValue FVal = Sel.getOperand(3);
3159 
3160   // FIXME: This could be generalized to non-integer comparisons.
3161   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
3162     return Op;
3163 
3164   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3165   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3166 
3167   // The values aren't constants, this isn't the pattern we're looking for.
3168   if (!CFVal || !CTVal)
3169     return Op;
3170 
3171   // We can commute the SELECT_CC by inverting the condition.  This
3172   // might be needed to make this fit into a CSINV pattern.
3173   if (CTVal->isAllOnes() && CFVal->isZero()) {
3174     std::swap(TVal, FVal);
3175     std::swap(CTVal, CFVal);
3176     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
3177   }
3178 
3179   // If the constants line up, perform the transform!
3180   if (CTVal->isZero() && CFVal->isAllOnes()) {
3181     SDValue CCVal;
3182     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3183 
3184     FVal = Other;
3185     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
3186                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
3187 
3188     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
3189                        CCVal, Cmp);
3190   }
3191 
3192   return Op;
3193 }
3194 
LowerADDC_ADDE_SUBC_SUBE(SDValue Op,SelectionDAG & DAG)3195 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
3196   EVT VT = Op.getValueType();
3197 
3198   // Let legalize expand this if it isn't a legal type yet.
3199   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3200     return SDValue();
3201 
3202   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3203 
3204   unsigned Opc;
3205   bool ExtraOp = false;
3206   switch (Op.getOpcode()) {
3207   default:
3208     llvm_unreachable("Invalid code");
3209   case ISD::ADDC:
3210     Opc = AArch64ISD::ADDS;
3211     break;
3212   case ISD::SUBC:
3213     Opc = AArch64ISD::SUBS;
3214     break;
3215   case ISD::ADDE:
3216     Opc = AArch64ISD::ADCS;
3217     ExtraOp = true;
3218     break;
3219   case ISD::SUBE:
3220     Opc = AArch64ISD::SBCS;
3221     ExtraOp = true;
3222     break;
3223   }
3224 
3225   if (!ExtraOp)
3226     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
3227   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
3228                      Op.getOperand(2));
3229 }
3230 
LowerXALUO(SDValue Op,SelectionDAG & DAG)3231 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
3232   // Let legalize expand this if it isn't a legal type yet.
3233   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3234     return SDValue();
3235 
3236   SDLoc dl(Op);
3237   AArch64CC::CondCode CC;
3238   // The actual operation that sets the overflow or carry flag.
3239   SDValue Value, Overflow;
3240   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
3241 
3242   // We use 0 and 1 as false and true values.
3243   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3244   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3245 
3246   // We use an inverted condition, because the conditional select is inverted
3247   // too. This will allow it to be selected to a single instruction:
3248   // CSINC Wd, WZR, WZR, invert(cond).
3249   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3250   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
3251                          CCVal, Overflow);
3252 
3253   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3254   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3255 }
3256 
3257 // Prefetch operands are:
3258 // 1: Address to prefetch
3259 // 2: bool isWrite
3260 // 3: int locality (0 = no locality ... 3 = extreme locality)
3261 // 4: bool isDataCache
LowerPREFETCH(SDValue Op,SelectionDAG & DAG)3262 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
3263   SDLoc DL(Op);
3264   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3265   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
3266   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3267 
3268   bool IsStream = !Locality;
3269   // When the locality number is set
3270   if (Locality) {
3271     // The front-end should have filtered out the out-of-range values
3272     assert(Locality <= 3 && "Prefetch locality out-of-range");
3273     // The locality degree is the opposite of the cache speed.
3274     // Put the number the other way around.
3275     // The encoding starts at 0 for level 1
3276     Locality = 3 - Locality;
3277   }
3278 
3279   // built the mask value encoding the expected behavior.
3280   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
3281                    (!IsData << 3) |     // IsDataCache bit
3282                    (Locality << 1) |    // Cache level bits
3283                    (unsigned)IsStream;  // Stream bit
3284   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
3285                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
3286 }
3287 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const3288 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
3289                                               SelectionDAG &DAG) const {
3290   EVT VT = Op.getValueType();
3291   if (VT.isScalableVector())
3292     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
3293 
3294   if (useSVEForFixedLengthVectorVT(VT))
3295     return LowerFixedLengthFPExtendToSVE(Op, DAG);
3296 
3297   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
3298   return SDValue();
3299 }
3300 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const3301 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
3302                                              SelectionDAG &DAG) const {
3303   if (Op.getValueType().isScalableVector())
3304     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
3305 
3306   bool IsStrict = Op->isStrictFPOpcode();
3307   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3308   EVT SrcVT = SrcVal.getValueType();
3309 
3310   if (useSVEForFixedLengthVectorVT(SrcVT))
3311     return LowerFixedLengthFPRoundToSVE(Op, DAG);
3312 
3313   if (SrcVT != MVT::f128) {
3314     // Expand cases where the input is a vector bigger than NEON.
3315     if (useSVEForFixedLengthVectorVT(SrcVT))
3316       return SDValue();
3317 
3318     // It's legal except when f128 is involved
3319     return Op;
3320   }
3321 
3322   return SDValue();
3323 }
3324 
LowerVectorFP_TO_INT(SDValue Op,SelectionDAG & DAG) const3325 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
3326                                                     SelectionDAG &DAG) const {
3327   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3328   // Any additional optimization in this function should be recorded
3329   // in the cost tables.
3330   EVT InVT = Op.getOperand(0).getValueType();
3331   EVT VT = Op.getValueType();
3332 
3333   if (VT.isScalableVector()) {
3334     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3335                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3336                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3337     return LowerToPredicatedOp(Op, DAG, Opcode);
3338   }
3339 
3340   if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
3341     return LowerFixedLengthFPToIntToSVE(Op, DAG);
3342 
3343   unsigned NumElts = InVT.getVectorNumElements();
3344 
3345   // f16 conversions are promoted to f32 when full fp16 is not supported.
3346   if (InVT.getVectorElementType() == MVT::f16 &&
3347       !Subtarget->hasFullFP16()) {
3348     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3349     SDLoc dl(Op);
3350     return DAG.getNode(
3351         Op.getOpcode(), dl, Op.getValueType(),
3352         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3353   }
3354 
3355   uint64_t VTSize = VT.getFixedSizeInBits();
3356   uint64_t InVTSize = InVT.getFixedSizeInBits();
3357   if (VTSize < InVTSize) {
3358     SDLoc dl(Op);
3359     SDValue Cv =
3360         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3361                     Op.getOperand(0));
3362     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3363   }
3364 
3365   if (VTSize > InVTSize) {
3366     SDLoc dl(Op);
3367     MVT ExtVT =
3368         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3369                          VT.getVectorNumElements());
3370     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3371     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3372   }
3373 
3374   // Type changing conversions are illegal.
3375   return Op;
3376 }
3377 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const3378 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3379                                               SelectionDAG &DAG) const {
3380   bool IsStrict = Op->isStrictFPOpcode();
3381   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3382 
3383   if (SrcVal.getValueType().isVector())
3384     return LowerVectorFP_TO_INT(Op, DAG);
3385 
3386   // f16 conversions are promoted to f32 when full fp16 is not supported.
3387   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3388     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3389     SDLoc dl(Op);
3390     return DAG.getNode(
3391         Op.getOpcode(), dl, Op.getValueType(),
3392         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3393   }
3394 
3395   if (SrcVal.getValueType() != MVT::f128) {
3396     // It's legal except when f128 is involved
3397     return Op;
3398   }
3399 
3400   return SDValue();
3401 }
3402 
3403 SDValue
LowerVectorFP_TO_INT_SAT(SDValue Op,SelectionDAG & DAG) const3404 AArch64TargetLowering::LowerVectorFP_TO_INT_SAT(SDValue Op,
3405                                                 SelectionDAG &DAG) const {
3406   // AArch64 FP-to-int conversions saturate to the destination element size, so
3407   // we can lower common saturating conversions to simple instructions.
3408   SDValue SrcVal = Op.getOperand(0);
3409   EVT SrcVT = SrcVal.getValueType();
3410   EVT DstVT = Op.getValueType();
3411   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3412 
3413   uint64_t SrcElementWidth = SrcVT.getScalarSizeInBits();
3414   uint64_t DstElementWidth = DstVT.getScalarSizeInBits();
3415   uint64_t SatWidth = SatVT.getScalarSizeInBits();
3416   assert(SatWidth <= DstElementWidth &&
3417          "Saturation width cannot exceed result width");
3418 
3419   // TODO: Consider lowering to SVE operations, as in LowerVectorFP_TO_INT.
3420   // Currently, the `llvm.fpto[su]i.sat.*` instrinsics don't accept scalable
3421   // types, so this is hard to reach.
3422   if (DstVT.isScalableVector())
3423     return SDValue();
3424 
3425   // TODO: Saturate to SatWidth explicitly.
3426   if (SatWidth != DstElementWidth)
3427     return SDValue();
3428 
3429   EVT SrcElementVT = SrcVT.getVectorElementType();
3430 
3431   // In the absence of FP16 support, promote f16 to f32, like
3432   // LowerVectorFP_TO_INT().
3433   if (SrcElementVT == MVT::f16 && !Subtarget->hasFullFP16()) {
3434     MVT F32VT = MVT::getVectorVT(MVT::f32, SrcVT.getVectorNumElements());
3435     return DAG.getNode(Op.getOpcode(), SDLoc(Op), DstVT,
3436                        DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), F32VT, SrcVal),
3437                        Op.getOperand(1));
3438   }
3439 
3440   // Cases that we can emit directly.
3441   if ((SrcElementWidth == DstElementWidth) &&
3442       (SrcElementVT == MVT::f64 || SrcElementVT == MVT::f32 ||
3443        (SrcElementVT == MVT::f16 && Subtarget->hasFullFP16()))) {
3444     return Op;
3445   }
3446 
3447   // For all other cases, fall back on the expanded form.
3448   return SDValue();
3449 }
3450 
LowerFP_TO_INT_SAT(SDValue Op,SelectionDAG & DAG) const3451 SDValue AArch64TargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
3452                                                   SelectionDAG &DAG) const {
3453   // AArch64 FP-to-int conversions saturate to the destination register size, so
3454   // we can lower common saturating conversions to simple instructions.
3455   SDValue SrcVal = Op.getOperand(0);
3456   EVT SrcVT = SrcVal.getValueType();
3457 
3458   if (SrcVT.isVector())
3459     return LowerVectorFP_TO_INT_SAT(Op, DAG);
3460 
3461   EVT DstVT = Op.getValueType();
3462   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3463   uint64_t SatWidth = SatVT.getScalarSizeInBits();
3464   uint64_t DstWidth = DstVT.getScalarSizeInBits();
3465   assert(SatWidth <= DstWidth && "Saturation width cannot exceed result width");
3466 
3467   // TODO: Saturate to SatWidth explicitly.
3468   if (SatWidth != DstWidth)
3469     return SDValue();
3470 
3471   // In the absence of FP16 support, promote f16 to f32, like LowerFP_TO_INT().
3472   if (SrcVT == MVT::f16 && !Subtarget->hasFullFP16())
3473     return DAG.getNode(Op.getOpcode(), SDLoc(Op), DstVT,
3474                        DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, SrcVal),
3475                        Op.getOperand(1));
3476 
3477   // Cases that we can emit directly.
3478   if ((SrcVT == MVT::f64 || SrcVT == MVT::f32 ||
3479        (SrcVT == MVT::f16 && Subtarget->hasFullFP16())) &&
3480       (DstVT == MVT::i64 || DstVT == MVT::i32))
3481     return Op;
3482 
3483   // For all other cases, fall back on the expanded form.
3484   return SDValue();
3485 }
3486 
LowerVectorINT_TO_FP(SDValue Op,SelectionDAG & DAG) const3487 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3488                                                     SelectionDAG &DAG) const {
3489   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3490   // Any additional optimization in this function should be recorded
3491   // in the cost tables.
3492   EVT VT = Op.getValueType();
3493   SDLoc dl(Op);
3494   SDValue In = Op.getOperand(0);
3495   EVT InVT = In.getValueType();
3496   unsigned Opc = Op.getOpcode();
3497   bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
3498 
3499   if (VT.isScalableVector()) {
3500     if (InVT.getVectorElementType() == MVT::i1) {
3501       // We can't directly extend an SVE predicate; extend it first.
3502       unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3503       EVT CastVT = getPromotedVTForPredicate(InVT);
3504       In = DAG.getNode(CastOpc, dl, CastVT, In);
3505       return DAG.getNode(Opc, dl, VT, In);
3506     }
3507 
3508     unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
3509                                : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
3510     return LowerToPredicatedOp(Op, DAG, Opcode);
3511   }
3512 
3513   if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
3514     return LowerFixedLengthIntToFPToSVE(Op, DAG);
3515 
3516   uint64_t VTSize = VT.getFixedSizeInBits();
3517   uint64_t InVTSize = InVT.getFixedSizeInBits();
3518   if (VTSize < InVTSize) {
3519     MVT CastVT =
3520         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3521                          InVT.getVectorNumElements());
3522     In = DAG.getNode(Opc, dl, CastVT, In);
3523     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3524   }
3525 
3526   if (VTSize > InVTSize) {
3527     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3528     EVT CastVT = VT.changeVectorElementTypeToInteger();
3529     In = DAG.getNode(CastOpc, dl, CastVT, In);
3530     return DAG.getNode(Opc, dl, VT, In);
3531   }
3532 
3533   return Op;
3534 }
3535 
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG) const3536 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3537                                             SelectionDAG &DAG) const {
3538   if (Op.getValueType().isVector())
3539     return LowerVectorINT_TO_FP(Op, DAG);
3540 
3541   bool IsStrict = Op->isStrictFPOpcode();
3542   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3543 
3544   // f16 conversions are promoted to f32 when full fp16 is not supported.
3545   if (Op.getValueType() == MVT::f16 &&
3546       !Subtarget->hasFullFP16()) {
3547     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3548     SDLoc dl(Op);
3549     return DAG.getNode(
3550         ISD::FP_ROUND, dl, MVT::f16,
3551         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3552         DAG.getIntPtrConstant(0, dl));
3553   }
3554 
3555   // i128 conversions are libcalls.
3556   if (SrcVal.getValueType() == MVT::i128)
3557     return SDValue();
3558 
3559   // Other conversions are legal, unless it's to the completely software-based
3560   // fp128.
3561   if (Op.getValueType() != MVT::f128)
3562     return Op;
3563   return SDValue();
3564 }
3565 
LowerFSINCOS(SDValue Op,SelectionDAG & DAG) const3566 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3567                                             SelectionDAG &DAG) const {
3568   // For iOS, we want to call an alternative entry point: __sincos_stret,
3569   // which returns the values in two S / D registers.
3570   SDLoc dl(Op);
3571   SDValue Arg = Op.getOperand(0);
3572   EVT ArgVT = Arg.getValueType();
3573   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3574 
3575   ArgListTy Args;
3576   ArgListEntry Entry;
3577 
3578   Entry.Node = Arg;
3579   Entry.Ty = ArgTy;
3580   Entry.IsSExt = false;
3581   Entry.IsZExt = false;
3582   Args.push_back(Entry);
3583 
3584   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3585                                         : RTLIB::SINCOS_STRET_F32;
3586   const char *LibcallName = getLibcallName(LC);
3587   SDValue Callee =
3588       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3589 
3590   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3591   TargetLowering::CallLoweringInfo CLI(DAG);
3592   CLI.setDebugLoc(dl)
3593       .setChain(DAG.getEntryNode())
3594       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3595 
3596   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3597   return CallResult.first;
3598 }
3599 
3600 static MVT getSVEContainerType(EVT ContentTy);
3601 
LowerBITCAST(SDValue Op,SelectionDAG & DAG) const3602 SDValue AArch64TargetLowering::LowerBITCAST(SDValue Op,
3603                                             SelectionDAG &DAG) const {
3604   EVT OpVT = Op.getValueType();
3605   EVT ArgVT = Op.getOperand(0).getValueType();
3606 
3607   if (useSVEForFixedLengthVectorVT(OpVT))
3608     return LowerFixedLengthBitcastToSVE(Op, DAG);
3609 
3610   if (OpVT.isScalableVector()) {
3611     if (isTypeLegal(OpVT) && !isTypeLegal(ArgVT)) {
3612       assert(OpVT.isFloatingPoint() && !ArgVT.isFloatingPoint() &&
3613              "Expected int->fp bitcast!");
3614       SDValue ExtResult =
3615           DAG.getNode(ISD::ANY_EXTEND, SDLoc(Op), getSVEContainerType(ArgVT),
3616                       Op.getOperand(0));
3617       return getSVESafeBitCast(OpVT, ExtResult, DAG);
3618     }
3619     return getSVESafeBitCast(OpVT, Op.getOperand(0), DAG);
3620   }
3621 
3622   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3623     return SDValue();
3624 
3625   assert(ArgVT == MVT::i16);
3626   SDLoc DL(Op);
3627 
3628   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3629   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3630   return SDValue(
3631       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3632                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3633       0);
3634 }
3635 
getExtensionTo64Bits(const EVT & OrigVT)3636 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3637   if (OrigVT.getSizeInBits() >= 64)
3638     return OrigVT;
3639 
3640   assert(OrigVT.isSimple() && "Expecting a simple value type");
3641 
3642   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3643   switch (OrigSimpleTy) {
3644   default: llvm_unreachable("Unexpected Vector Type");
3645   case MVT::v2i8:
3646   case MVT::v2i16:
3647      return MVT::v2i32;
3648   case MVT::v4i8:
3649     return  MVT::v4i16;
3650   }
3651 }
3652 
addRequiredExtensionForVectorMULL(SDValue N,SelectionDAG & DAG,const EVT & OrigTy,const EVT & ExtTy,unsigned ExtOpcode)3653 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3654                                                  const EVT &OrigTy,
3655                                                  const EVT &ExtTy,
3656                                                  unsigned ExtOpcode) {
3657   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3658   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3659   // 64-bits we need to insert a new extension so that it will be 64-bits.
3660   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3661   if (OrigTy.getSizeInBits() >= 64)
3662     return N;
3663 
3664   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3665   EVT NewVT = getExtensionTo64Bits(OrigTy);
3666 
3667   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3668 }
3669 
isExtendedBUILD_VECTOR(SDNode * N,SelectionDAG & DAG,bool isSigned)3670 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3671                                    bool isSigned) {
3672   EVT VT = N->getValueType(0);
3673 
3674   if (N->getOpcode() != ISD::BUILD_VECTOR)
3675     return false;
3676 
3677   for (const SDValue &Elt : N->op_values()) {
3678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3679       unsigned EltSize = VT.getScalarSizeInBits();
3680       unsigned HalfSize = EltSize / 2;
3681       if (isSigned) {
3682         if (!isIntN(HalfSize, C->getSExtValue()))
3683           return false;
3684       } else {
3685         if (!isUIntN(HalfSize, C->getZExtValue()))
3686           return false;
3687       }
3688       continue;
3689     }
3690     return false;
3691   }
3692 
3693   return true;
3694 }
3695 
skipExtensionForVectorMULL(SDNode * N,SelectionDAG & DAG)3696 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3697   if (N->getOpcode() == ISD::SIGN_EXTEND ||
3698       N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
3699     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3700                                              N->getOperand(0)->getValueType(0),
3701                                              N->getValueType(0),
3702                                              N->getOpcode());
3703 
3704   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3705   EVT VT = N->getValueType(0);
3706   SDLoc dl(N);
3707   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3708   unsigned NumElts = VT.getVectorNumElements();
3709   MVT TruncVT = MVT::getIntegerVT(EltSize);
3710   SmallVector<SDValue, 8> Ops;
3711   for (unsigned i = 0; i != NumElts; ++i) {
3712     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3713     const APInt &CInt = C->getAPIntValue();
3714     // Element types smaller than 32 bits are not legal, so use i32 elements.
3715     // The values are implicitly truncated so sext vs. zext doesn't matter.
3716     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3717   }
3718   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3719 }
3720 
isSignExtended(SDNode * N,SelectionDAG & DAG)3721 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3722   return N->getOpcode() == ISD::SIGN_EXTEND ||
3723          N->getOpcode() == ISD::ANY_EXTEND ||
3724          isExtendedBUILD_VECTOR(N, DAG, true);
3725 }
3726 
isZeroExtended(SDNode * N,SelectionDAG & DAG)3727 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3728   return N->getOpcode() == ISD::ZERO_EXTEND ||
3729          N->getOpcode() == ISD::ANY_EXTEND ||
3730          isExtendedBUILD_VECTOR(N, DAG, false);
3731 }
3732 
isAddSubSExt(SDNode * N,SelectionDAG & DAG)3733 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3734   unsigned Opcode = N->getOpcode();
3735   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3736     SDNode *N0 = N->getOperand(0).getNode();
3737     SDNode *N1 = N->getOperand(1).getNode();
3738     return N0->hasOneUse() && N1->hasOneUse() &&
3739       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3740   }
3741   return false;
3742 }
3743 
isAddSubZExt(SDNode * N,SelectionDAG & DAG)3744 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3745   unsigned Opcode = N->getOpcode();
3746   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3747     SDNode *N0 = N->getOperand(0).getNode();
3748     SDNode *N1 = N->getOperand(1).getNode();
3749     return N0->hasOneUse() && N1->hasOneUse() &&
3750       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3751   }
3752   return false;
3753 }
3754 
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const3755 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3756                                                 SelectionDAG &DAG) const {
3757   // The rounding mode is in bits 23:22 of the FPSCR.
3758   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3759   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3760   // so that the shift + and get folded into a bitfield extract.
3761   SDLoc dl(Op);
3762 
3763   SDValue Chain = Op.getOperand(0);
3764   SDValue FPCR_64 = DAG.getNode(
3765       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3766       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3767   Chain = FPCR_64.getValue(1);
3768   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3769   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3770                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3771   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3772                               DAG.getConstant(22, dl, MVT::i32));
3773   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3774                             DAG.getConstant(3, dl, MVT::i32));
3775   return DAG.getMergeValues({AND, Chain}, dl);
3776 }
3777 
LowerSET_ROUNDING(SDValue Op,SelectionDAG & DAG) const3778 SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op,
3779                                                  SelectionDAG &DAG) const {
3780   SDLoc DL(Op);
3781   SDValue Chain = Op->getOperand(0);
3782   SDValue RMValue = Op->getOperand(1);
3783 
3784   // The rounding mode is in bits 23:22 of the FPCR.
3785   // The llvm.set.rounding argument value to the rounding mode in FPCR mapping
3786   // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
3787   // ((arg - 1) & 3) << 22).
3788   //
3789   // The argument of llvm.set.rounding must be within the segment [0, 3], so
3790   // NearestTiesToAway (4) is not handled here. It is responsibility of the code
3791   // generated llvm.set.rounding to ensure this condition.
3792 
3793   // Calculate new value of FPCR[23:22].
3794   RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
3795                         DAG.getConstant(1, DL, MVT::i32));
3796   RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
3797                         DAG.getConstant(0x3, DL, MVT::i32));
3798   RMValue =
3799       DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
3800                   DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32));
3801   RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue);
3802 
3803   // Get current value of FPCR.
3804   SDValue Ops[] = {
3805       Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)};
3806   SDValue FPCR =
3807       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops);
3808   Chain = FPCR.getValue(1);
3809   FPCR = FPCR.getValue(0);
3810 
3811   // Put new rounding mode into FPSCR[23:22].
3812   const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos);
3813   FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR,
3814                      DAG.getConstant(RMMask, DL, MVT::i64));
3815   FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue);
3816   SDValue Ops2[] = {
3817       Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64),
3818       FPCR};
3819   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
3820 }
3821 
LowerMUL(SDValue Op,SelectionDAG & DAG) const3822 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3823   EVT VT = Op.getValueType();
3824 
3825   // If SVE is available then i64 vector multiplications can also be made legal.
3826   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3827 
3828   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3829     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3830 
3831   // Multiplications are only custom-lowered for 128-bit vectors so that
3832   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3833   assert(VT.is128BitVector() && VT.isInteger() &&
3834          "unexpected type for custom-lowering ISD::MUL");
3835   SDNode *N0 = Op.getOperand(0).getNode();
3836   SDNode *N1 = Op.getOperand(1).getNode();
3837   unsigned NewOpc = 0;
3838   bool isMLA = false;
3839   bool isN0SExt = isSignExtended(N0, DAG);
3840   bool isN1SExt = isSignExtended(N1, DAG);
3841   if (isN0SExt && isN1SExt)
3842     NewOpc = AArch64ISD::SMULL;
3843   else {
3844     bool isN0ZExt = isZeroExtended(N0, DAG);
3845     bool isN1ZExt = isZeroExtended(N1, DAG);
3846     if (isN0ZExt && isN1ZExt)
3847       NewOpc = AArch64ISD::UMULL;
3848     else if (isN1SExt || isN1ZExt) {
3849       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3850       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3851       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3852         NewOpc = AArch64ISD::SMULL;
3853         isMLA = true;
3854       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3855         NewOpc =  AArch64ISD::UMULL;
3856         isMLA = true;
3857       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3858         std::swap(N0, N1);
3859         NewOpc =  AArch64ISD::UMULL;
3860         isMLA = true;
3861       }
3862     }
3863 
3864     if (!NewOpc) {
3865       if (VT == MVT::v2i64)
3866         // Fall through to expand this.  It is not legal.
3867         return SDValue();
3868       else
3869         // Other vector multiplications are legal.
3870         return Op;
3871     }
3872   }
3873 
3874   // Legalize to a S/UMULL instruction
3875   SDLoc DL(Op);
3876   SDValue Op0;
3877   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3878   if (!isMLA) {
3879     Op0 = skipExtensionForVectorMULL(N0, DAG);
3880     assert(Op0.getValueType().is64BitVector() &&
3881            Op1.getValueType().is64BitVector() &&
3882            "unexpected types for extended operands to VMULL");
3883     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3884   }
3885   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3886   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3887   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3888   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3889   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3890   EVT Op1VT = Op1.getValueType();
3891   return DAG.getNode(N0->getOpcode(), DL, VT,
3892                      DAG.getNode(NewOpc, DL, VT,
3893                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3894                      DAG.getNode(NewOpc, DL, VT,
3895                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3896 }
3897 
getPTrue(SelectionDAG & DAG,SDLoc DL,EVT VT,int Pattern)3898 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3899                                int Pattern) {
3900   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3901                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3902 }
3903 
lowerConvertToSVBool(SDValue Op,SelectionDAG & DAG)3904 static SDValue lowerConvertToSVBool(SDValue Op, SelectionDAG &DAG) {
3905   SDLoc DL(Op);
3906   EVT OutVT = Op.getValueType();
3907   SDValue InOp = Op.getOperand(1);
3908   EVT InVT = InOp.getValueType();
3909 
3910   // Return the operand if the cast isn't changing type,
3911   // i.e. <n x 16 x i1> -> <n x 16 x i1>
3912   if (InVT == OutVT)
3913     return InOp;
3914 
3915   SDValue Reinterpret =
3916       DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, InOp);
3917 
3918   // If the argument converted to an svbool is a ptrue or a comparison, the
3919   // lanes introduced by the widening are zero by construction.
3920   switch (InOp.getOpcode()) {
3921   case AArch64ISD::SETCC_MERGE_ZERO:
3922     return Reinterpret;
3923   case ISD::INTRINSIC_WO_CHAIN:
3924     if (InOp.getConstantOperandVal(0) == Intrinsic::aarch64_sve_ptrue)
3925       return Reinterpret;
3926   }
3927 
3928   // Otherwise, zero the newly introduced lanes.
3929   SDValue Mask = getPTrue(DAG, DL, InVT, AArch64SVEPredPattern::all);
3930   SDValue MaskReinterpret =
3931       DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, Mask);
3932   return DAG.getNode(ISD::AND, DL, OutVT, Reinterpret, MaskReinterpret);
3933 }
3934 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const3935 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3936                                                      SelectionDAG &DAG) const {
3937   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3938   SDLoc dl(Op);
3939   switch (IntNo) {
3940   default: return SDValue();    // Don't custom lower most intrinsics.
3941   case Intrinsic::thread_pointer: {
3942     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3943     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3944   }
3945   case Intrinsic::aarch64_neon_abs: {
3946     EVT Ty = Op.getValueType();
3947     if (Ty == MVT::i64) {
3948       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3949                                    Op.getOperand(1));
3950       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3951       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3952     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3953       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3954     } else {
3955       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3956     }
3957   }
3958   case Intrinsic::aarch64_neon_smax:
3959     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3960                        Op.getOperand(1), Op.getOperand(2));
3961   case Intrinsic::aarch64_neon_umax:
3962     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3963                        Op.getOperand(1), Op.getOperand(2));
3964   case Intrinsic::aarch64_neon_smin:
3965     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3966                        Op.getOperand(1), Op.getOperand(2));
3967   case Intrinsic::aarch64_neon_umin:
3968     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3969                        Op.getOperand(1), Op.getOperand(2));
3970 
3971   case Intrinsic::aarch64_sve_sunpkhi:
3972     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3973                        Op.getOperand(1));
3974   case Intrinsic::aarch64_sve_sunpklo:
3975     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3976                        Op.getOperand(1));
3977   case Intrinsic::aarch64_sve_uunpkhi:
3978     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3979                        Op.getOperand(1));
3980   case Intrinsic::aarch64_sve_uunpklo:
3981     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3982                        Op.getOperand(1));
3983   case Intrinsic::aarch64_sve_clasta_n:
3984     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3985                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3986   case Intrinsic::aarch64_sve_clastb_n:
3987     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3988                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3989   case Intrinsic::aarch64_sve_lasta:
3990     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3991                        Op.getOperand(1), Op.getOperand(2));
3992   case Intrinsic::aarch64_sve_lastb:
3993     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3994                        Op.getOperand(1), Op.getOperand(2));
3995   case Intrinsic::aarch64_sve_rev:
3996     return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(),
3997                        Op.getOperand(1));
3998   case Intrinsic::aarch64_sve_tbl:
3999     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
4000                        Op.getOperand(1), Op.getOperand(2));
4001   case Intrinsic::aarch64_sve_trn1:
4002     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
4003                        Op.getOperand(1), Op.getOperand(2));
4004   case Intrinsic::aarch64_sve_trn2:
4005     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
4006                        Op.getOperand(1), Op.getOperand(2));
4007   case Intrinsic::aarch64_sve_uzp1:
4008     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
4009                        Op.getOperand(1), Op.getOperand(2));
4010   case Intrinsic::aarch64_sve_uzp2:
4011     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
4012                        Op.getOperand(1), Op.getOperand(2));
4013   case Intrinsic::aarch64_sve_zip1:
4014     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
4015                        Op.getOperand(1), Op.getOperand(2));
4016   case Intrinsic::aarch64_sve_zip2:
4017     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
4018                        Op.getOperand(1), Op.getOperand(2));
4019   case Intrinsic::aarch64_sve_splice:
4020     return DAG.getNode(AArch64ISD::SPLICE, dl, Op.getValueType(),
4021                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4022   case Intrinsic::aarch64_sve_ptrue:
4023     return getPTrue(DAG, dl, Op.getValueType(),
4024                     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
4025   case Intrinsic::aarch64_sve_clz:
4026     return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
4027                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4028   case Intrinsic::aarch64_sve_cnt: {
4029     SDValue Data = Op.getOperand(3);
4030     // CTPOP only supports integer operands.
4031     if (Data.getValueType().isFloatingPoint())
4032       Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
4033     return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
4034                        Op.getOperand(2), Data, Op.getOperand(1));
4035   }
4036   case Intrinsic::aarch64_sve_dupq_lane:
4037     return LowerDUPQLane(Op, DAG);
4038   case Intrinsic::aarch64_sve_convert_from_svbool:
4039     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
4040                        Op.getOperand(1));
4041   case Intrinsic::aarch64_sve_convert_to_svbool:
4042     return lowerConvertToSVBool(Op, DAG);
4043   case Intrinsic::aarch64_sve_fneg:
4044     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
4045                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4046   case Intrinsic::aarch64_sve_frintp:
4047     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
4048                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4049   case Intrinsic::aarch64_sve_frintm:
4050     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
4051                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4052   case Intrinsic::aarch64_sve_frinti:
4053     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
4054                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4055   case Intrinsic::aarch64_sve_frintx:
4056     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
4057                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4058   case Intrinsic::aarch64_sve_frinta:
4059     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
4060                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4061   case Intrinsic::aarch64_sve_frintn:
4062     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
4063                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4064   case Intrinsic::aarch64_sve_frintz:
4065     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
4066                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4067   case Intrinsic::aarch64_sve_ucvtf:
4068     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
4069                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4070                        Op.getOperand(1));
4071   case Intrinsic::aarch64_sve_scvtf:
4072     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
4073                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4074                        Op.getOperand(1));
4075   case Intrinsic::aarch64_sve_fcvtzu:
4076     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
4077                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4078                        Op.getOperand(1));
4079   case Intrinsic::aarch64_sve_fcvtzs:
4080     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
4081                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4082                        Op.getOperand(1));
4083   case Intrinsic::aarch64_sve_fsqrt:
4084     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
4085                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4086   case Intrinsic::aarch64_sve_frecpx:
4087     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
4088                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4089   case Intrinsic::aarch64_sve_fabs:
4090     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
4091                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4092   case Intrinsic::aarch64_sve_abs:
4093     return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
4094                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4095   case Intrinsic::aarch64_sve_neg:
4096     return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
4097                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4098   case Intrinsic::aarch64_sve_insr: {
4099     SDValue Scalar = Op.getOperand(2);
4100     EVT ScalarTy = Scalar.getValueType();
4101     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
4102       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
4103 
4104     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
4105                        Op.getOperand(1), Scalar);
4106   }
4107   case Intrinsic::aarch64_sve_rbit:
4108     return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
4109                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4110                        Op.getOperand(1));
4111   case Intrinsic::aarch64_sve_revb:
4112     return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
4113                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4114   case Intrinsic::aarch64_sve_sxtb:
4115     return DAG.getNode(
4116         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4117         Op.getOperand(2), Op.getOperand(3),
4118         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
4119         Op.getOperand(1));
4120   case Intrinsic::aarch64_sve_sxth:
4121     return DAG.getNode(
4122         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4123         Op.getOperand(2), Op.getOperand(3),
4124         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
4125         Op.getOperand(1));
4126   case Intrinsic::aarch64_sve_sxtw:
4127     return DAG.getNode(
4128         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4129         Op.getOperand(2), Op.getOperand(3),
4130         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
4131         Op.getOperand(1));
4132   case Intrinsic::aarch64_sve_uxtb:
4133     return DAG.getNode(
4134         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4135         Op.getOperand(2), Op.getOperand(3),
4136         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
4137         Op.getOperand(1));
4138   case Intrinsic::aarch64_sve_uxth:
4139     return DAG.getNode(
4140         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4141         Op.getOperand(2), Op.getOperand(3),
4142         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
4143         Op.getOperand(1));
4144   case Intrinsic::aarch64_sve_uxtw:
4145     return DAG.getNode(
4146         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4147         Op.getOperand(2), Op.getOperand(3),
4148         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
4149         Op.getOperand(1));
4150 
4151   case Intrinsic::localaddress: {
4152     const auto &MF = DAG.getMachineFunction();
4153     const auto *RegInfo = Subtarget->getRegisterInfo();
4154     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
4155     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
4156                               Op.getSimpleValueType());
4157   }
4158 
4159   case Intrinsic::eh_recoverfp: {
4160     // FIXME: This needs to be implemented to correctly handle highly aligned
4161     // stack objects. For now we simply return the incoming FP. Refer D53541
4162     // for more details.
4163     SDValue FnOp = Op.getOperand(1);
4164     SDValue IncomingFPOp = Op.getOperand(2);
4165     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
4166     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
4167     if (!Fn)
4168       report_fatal_error(
4169           "llvm.eh.recoverfp must take a function as the first argument");
4170     return IncomingFPOp;
4171   }
4172 
4173   case Intrinsic::aarch64_neon_vsri:
4174   case Intrinsic::aarch64_neon_vsli: {
4175     EVT Ty = Op.getValueType();
4176 
4177     if (!Ty.isVector())
4178       report_fatal_error("Unexpected type for aarch64_neon_vsli");
4179 
4180     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
4181 
4182     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
4183     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
4184     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
4185                        Op.getOperand(3));
4186   }
4187 
4188   case Intrinsic::aarch64_neon_srhadd:
4189   case Intrinsic::aarch64_neon_urhadd:
4190   case Intrinsic::aarch64_neon_shadd:
4191   case Intrinsic::aarch64_neon_uhadd: {
4192     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
4193                         IntNo == Intrinsic::aarch64_neon_shadd);
4194     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
4195                           IntNo == Intrinsic::aarch64_neon_urhadd);
4196     unsigned Opcode =
4197         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
4198                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
4199     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4200                        Op.getOperand(2));
4201   }
4202   case Intrinsic::aarch64_neon_sabd:
4203   case Intrinsic::aarch64_neon_uabd: {
4204     unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uabd ? ISD::ABDU
4205                                                             : ISD::ABDS;
4206     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4207                        Op.getOperand(2));
4208   }
4209   case Intrinsic::aarch64_neon_uaddlp: {
4210     unsigned Opcode = AArch64ISD::UADDLP;
4211     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1));
4212   }
4213   case Intrinsic::aarch64_neon_sdot:
4214   case Intrinsic::aarch64_neon_udot:
4215   case Intrinsic::aarch64_sve_sdot:
4216   case Intrinsic::aarch64_sve_udot: {
4217     unsigned Opcode = (IntNo == Intrinsic::aarch64_neon_udot ||
4218                        IntNo == Intrinsic::aarch64_sve_udot)
4219                           ? AArch64ISD::UDOT
4220                           : AArch64ISD::SDOT;
4221     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4222                        Op.getOperand(2), Op.getOperand(3));
4223   }
4224   }
4225 }
4226 
shouldExtendGSIndex(EVT VT,EVT & EltTy) const4227 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const {
4228   if (VT.getVectorElementType() == MVT::i8 ||
4229       VT.getVectorElementType() == MVT::i16) {
4230     EltTy = MVT::i32;
4231     return true;
4232   }
4233   return false;
4234 }
4235 
shouldRemoveExtendFromGSIndex(EVT VT) const4236 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
4237   if (VT.getVectorElementType() == MVT::i32 &&
4238       VT.getVectorElementCount().getKnownMinValue() >= 4 &&
4239       !VT.isFixedLengthVector())
4240     return true;
4241 
4242   return false;
4243 }
4244 
isVectorLoadExtDesirable(SDValue ExtVal) const4245 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
4246   return ExtVal.getValueType().isScalableVector() ||
4247          useSVEForFixedLengthVectorVT(ExtVal.getValueType(),
4248                                       /*OverrideNEON=*/true);
4249 }
4250 
getGatherVecOpcode(bool IsScaled,bool IsSigned,bool NeedsExtend)4251 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
4252   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
4253       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
4254        AArch64ISD::GLD1_MERGE_ZERO},
4255       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
4256        AArch64ISD::GLD1_UXTW_MERGE_ZERO},
4257       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
4258        AArch64ISD::GLD1_MERGE_ZERO},
4259       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
4260        AArch64ISD::GLD1_SXTW_MERGE_ZERO},
4261       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
4262        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
4263       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
4264        AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
4265       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
4266        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
4267       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
4268        AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
4269   };
4270   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
4271   return AddrModes.find(Key)->second;
4272 }
4273 
getScatterVecOpcode(bool IsScaled,bool IsSigned,bool NeedsExtend)4274 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
4275   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
4276       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
4277        AArch64ISD::SST1_PRED},
4278       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
4279        AArch64ISD::SST1_UXTW_PRED},
4280       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
4281        AArch64ISD::SST1_PRED},
4282       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
4283        AArch64ISD::SST1_SXTW_PRED},
4284       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
4285        AArch64ISD::SST1_SCALED_PRED},
4286       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
4287        AArch64ISD::SST1_UXTW_SCALED_PRED},
4288       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
4289        AArch64ISD::SST1_SCALED_PRED},
4290       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
4291        AArch64ISD::SST1_SXTW_SCALED_PRED},
4292   };
4293   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
4294   return AddrModes.find(Key)->second;
4295 }
4296 
getSignExtendedGatherOpcode(unsigned Opcode)4297 unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
4298   switch (Opcode) {
4299   default:
4300     llvm_unreachable("unimplemented opcode");
4301     return Opcode;
4302   case AArch64ISD::GLD1_MERGE_ZERO:
4303     return AArch64ISD::GLD1S_MERGE_ZERO;
4304   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
4305     return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
4306   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
4307     return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
4308   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
4309     return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
4310   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
4311     return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
4312   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
4313     return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
4314   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
4315     return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
4316   }
4317 }
4318 
getGatherScatterIndexIsExtended(SDValue Index)4319 bool getGatherScatterIndexIsExtended(SDValue Index) {
4320   unsigned Opcode = Index.getOpcode();
4321   if (Opcode == ISD::SIGN_EXTEND_INREG)
4322     return true;
4323 
4324   if (Opcode == ISD::AND) {
4325     SDValue Splat = Index.getOperand(1);
4326     if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
4327       return false;
4328     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
4329     if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
4330       return false;
4331     return true;
4332   }
4333 
4334   return false;
4335 }
4336 
4337 // If the base pointer of a masked gather or scatter is null, we
4338 // may be able to swap BasePtr & Index and use the vector + register
4339 // or vector + immediate addressing mode, e.g.
4340 // VECTOR + REGISTER:
4341 //    getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices)
4342 // -> getelementptr %offset, <vscale x N x T> %indices
4343 // VECTOR + IMMEDIATE:
4344 //    getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices)
4345 // -> getelementptr #x, <vscale x N x T> %indices
selectGatherScatterAddrMode(SDValue & BasePtr,SDValue & Index,EVT MemVT,unsigned & Opcode,bool IsGather,SelectionDAG & DAG)4346 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT,
4347                                  unsigned &Opcode, bool IsGather,
4348                                  SelectionDAG &DAG) {
4349   if (!isNullConstant(BasePtr))
4350     return;
4351 
4352   // FIXME: This will not match for fixed vector type codegen as the nodes in
4353   // question will have fixed<->scalable conversions around them. This should be
4354   // moved to a DAG combine or complex pattern so that is executes after all of
4355   // the fixed vector insert and extracts have been removed. This deficiency
4356   // will result in a sub-optimal addressing mode being used, i.e. an ADD not
4357   // being folded into the scatter/gather.
4358   ConstantSDNode *Offset = nullptr;
4359   if (Index.getOpcode() == ISD::ADD)
4360     if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) {
4361       if (isa<ConstantSDNode>(SplatVal))
4362         Offset = cast<ConstantSDNode>(SplatVal);
4363       else {
4364         BasePtr = SplatVal;
4365         Index = Index->getOperand(0);
4366         return;
4367       }
4368     }
4369 
4370   unsigned NewOp =
4371       IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED;
4372 
4373   if (!Offset) {
4374     std::swap(BasePtr, Index);
4375     Opcode = NewOp;
4376     return;
4377   }
4378 
4379   uint64_t OffsetVal = Offset->getZExtValue();
4380   unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8;
4381   auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64);
4382 
4383   if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) {
4384     // Index is out of range for the immediate addressing mode
4385     BasePtr = ConstOffset;
4386     Index = Index->getOperand(0);
4387     return;
4388   }
4389 
4390   // Immediate is in range
4391   Opcode = NewOp;
4392   BasePtr = Index->getOperand(0);
4393   Index = ConstOffset;
4394 }
4395 
LowerMGATHER(SDValue Op,SelectionDAG & DAG) const4396 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
4397                                             SelectionDAG &DAG) const {
4398   SDLoc DL(Op);
4399   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
4400   assert(MGT && "Can only custom lower gather load nodes");
4401 
4402   bool IsFixedLength = MGT->getMemoryVT().isFixedLengthVector();
4403 
4404   SDValue Index = MGT->getIndex();
4405   SDValue Chain = MGT->getChain();
4406   SDValue PassThru = MGT->getPassThru();
4407   SDValue Mask = MGT->getMask();
4408   SDValue BasePtr = MGT->getBasePtr();
4409   ISD::LoadExtType ExtTy = MGT->getExtensionType();
4410 
4411   ISD::MemIndexType IndexType = MGT->getIndexType();
4412   bool IsScaled =
4413       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4414   bool IsSigned =
4415       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4416   bool IdxNeedsExtend =
4417       getGatherScatterIndexIsExtended(Index) ||
4418       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4419   bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD;
4420 
4421   EVT VT = PassThru.getSimpleValueType();
4422   EVT IndexVT = Index.getSimpleValueType();
4423   EVT MemVT = MGT->getMemoryVT();
4424   SDValue InputVT = DAG.getValueType(MemVT);
4425 
4426   if (VT.getVectorElementType() == MVT::bf16 &&
4427       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4428     return SDValue();
4429 
4430   if (IsFixedLength) {
4431     assert(Subtarget->useSVEForFixedLengthVectors() &&
4432            "Cannot lower when not using SVE for fixed vectors");
4433     if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
4434       IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
4435       MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
4436     } else {
4437       MemVT = getContainerForFixedLengthVector(DAG, MemVT);
4438       IndexVT = MemVT.changeTypeToInteger();
4439     }
4440     InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
4441     Mask = DAG.getNode(
4442         ISD::ZERO_EXTEND, DL,
4443         VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
4444   }
4445 
4446   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
4447     PassThru = SDValue();
4448 
4449   if (VT.isFloatingPoint() && !IsFixedLength) {
4450     // Handle FP data by using an integer gather and casting the result.
4451     if (PassThru) {
4452       EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4453       PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG);
4454     }
4455     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4456   }
4457 
4458   SDVTList VTs = DAG.getVTList(IndexVT, MVT::Other);
4459 
4460   if (getGatherScatterIndexIsExtended(Index))
4461     Index = Index.getOperand(0);
4462 
4463   unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend);
4464   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4465                               /*isGather=*/true, DAG);
4466 
4467   if (ResNeedsSignExtend)
4468     Opcode = getSignExtendedGatherOpcode(Opcode);
4469 
4470   if (IsFixedLength) {
4471     if (Index.getSimpleValueType().isFixedLengthVector())
4472       Index = convertToScalableVector(DAG, IndexVT, Index);
4473     if (BasePtr.getSimpleValueType().isFixedLengthVector())
4474       BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
4475     Mask = convertFixedMaskToScalableVector(Mask, DAG);
4476   }
4477 
4478   SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT};
4479   SDValue Result = DAG.getNode(Opcode, DL, VTs, Ops);
4480   Chain = Result.getValue(1);
4481 
4482   if (IsFixedLength) {
4483     Result = convertFromScalableVector(
4484         DAG, VT.changeVectorElementType(IndexVT.getVectorElementType()),
4485         Result);
4486     Result = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Result);
4487     Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
4488 
4489     if (PassThru)
4490       Result = DAG.getSelect(DL, VT, MGT->getMask(), Result, PassThru);
4491   } else {
4492     if (PassThru)
4493       Result = DAG.getSelect(DL, IndexVT, Mask, Result, PassThru);
4494 
4495     if (VT.isFloatingPoint())
4496       Result = getSVESafeBitCast(VT, Result, DAG);
4497   }
4498 
4499   return DAG.getMergeValues({Result, Chain}, DL);
4500 }
4501 
LowerMSCATTER(SDValue Op,SelectionDAG & DAG) const4502 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
4503                                              SelectionDAG &DAG) const {
4504   SDLoc DL(Op);
4505   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
4506   assert(MSC && "Can only custom lower scatter store nodes");
4507 
4508   bool IsFixedLength = MSC->getMemoryVT().isFixedLengthVector();
4509 
4510   SDValue Index = MSC->getIndex();
4511   SDValue Chain = MSC->getChain();
4512   SDValue StoreVal = MSC->getValue();
4513   SDValue Mask = MSC->getMask();
4514   SDValue BasePtr = MSC->getBasePtr();
4515 
4516   ISD::MemIndexType IndexType = MSC->getIndexType();
4517   bool IsScaled =
4518       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4519   bool IsSigned =
4520       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4521   bool NeedsExtend =
4522       getGatherScatterIndexIsExtended(Index) ||
4523       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4524 
4525   EVT VT = StoreVal.getSimpleValueType();
4526   EVT IndexVT = Index.getSimpleValueType();
4527   SDVTList VTs = DAG.getVTList(MVT::Other);
4528   EVT MemVT = MSC->getMemoryVT();
4529   SDValue InputVT = DAG.getValueType(MemVT);
4530 
4531   if (VT.getVectorElementType() == MVT::bf16 &&
4532       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4533     return SDValue();
4534 
4535   if (IsFixedLength) {
4536     assert(Subtarget->useSVEForFixedLengthVectors() &&
4537            "Cannot lower when not using SVE for fixed vectors");
4538     if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
4539       IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
4540       MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
4541     } else {
4542       MemVT = getContainerForFixedLengthVector(DAG, MemVT);
4543       IndexVT = MemVT.changeTypeToInteger();
4544     }
4545     InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
4546 
4547     StoreVal =
4548         DAG.getNode(ISD::BITCAST, DL, VT.changeTypeToInteger(), StoreVal);
4549     StoreVal = DAG.getNode(
4550         ISD::ANY_EXTEND, DL,
4551         VT.changeVectorElementType(IndexVT.getVectorElementType()), StoreVal);
4552     StoreVal = convertToScalableVector(DAG, IndexVT, StoreVal);
4553     Mask = DAG.getNode(
4554         ISD::ZERO_EXTEND, DL,
4555         VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
4556   } else if (VT.isFloatingPoint()) {
4557     // Handle FP data by casting the data so an integer scatter can be used.
4558     EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4559     StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG);
4560     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4561   }
4562 
4563   if (getGatherScatterIndexIsExtended(Index))
4564     Index = Index.getOperand(0);
4565 
4566   unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend);
4567   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4568                               /*isGather=*/false, DAG);
4569 
4570   if (IsFixedLength) {
4571     if (Index.getSimpleValueType().isFixedLengthVector())
4572       Index = convertToScalableVector(DAG, IndexVT, Index);
4573     if (BasePtr.getSimpleValueType().isFixedLengthVector())
4574       BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
4575     Mask = convertFixedMaskToScalableVector(Mask, DAG);
4576   }
4577 
4578   SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
4579   return DAG.getNode(Opcode, DL, VTs, Ops);
4580 }
4581 
LowerMLOAD(SDValue Op,SelectionDAG & DAG) const4582 SDValue AArch64TargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
4583   SDLoc DL(Op);
4584   MaskedLoadSDNode *LoadNode = cast<MaskedLoadSDNode>(Op);
4585   assert(LoadNode && "Expected custom lowering of a masked load node");
4586   EVT VT = Op->getValueType(0);
4587 
4588   if (useSVEForFixedLengthVectorVT(VT, true))
4589     return LowerFixedLengthVectorMLoadToSVE(Op, DAG);
4590 
4591   SDValue PassThru = LoadNode->getPassThru();
4592   SDValue Mask = LoadNode->getMask();
4593 
4594   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
4595     return Op;
4596 
4597   SDValue Load = DAG.getMaskedLoad(
4598       VT, DL, LoadNode->getChain(), LoadNode->getBasePtr(),
4599       LoadNode->getOffset(), Mask, DAG.getUNDEF(VT), LoadNode->getMemoryVT(),
4600       LoadNode->getMemOperand(), LoadNode->getAddressingMode(),
4601       LoadNode->getExtensionType());
4602 
4603   SDValue Result = DAG.getSelect(DL, VT, Mask, Load, PassThru);
4604 
4605   return DAG.getMergeValues({Result, Load.getValue(1)}, DL);
4606 }
4607 
4608 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
LowerTruncateVectorStore(SDLoc DL,StoreSDNode * ST,EVT VT,EVT MemVT,SelectionDAG & DAG)4609 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
4610                                         EVT VT, EVT MemVT,
4611                                         SelectionDAG &DAG) {
4612   assert(VT.isVector() && "VT should be a vector type");
4613   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
4614 
4615   SDValue Value = ST->getValue();
4616 
4617   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
4618   // the word lane which represent the v4i8 subvector.  It optimizes the store
4619   // to:
4620   //
4621   //   xtn  v0.8b, v0.8h
4622   //   str  s0, [x0]
4623 
4624   SDValue Undef = DAG.getUNDEF(MVT::i16);
4625   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
4626                                         {Undef, Undef, Undef, Undef});
4627 
4628   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
4629                                  Value, UndefVec);
4630   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
4631 
4632   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
4633   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
4634                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
4635 
4636   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
4637                       ST->getBasePtr(), ST->getMemOperand());
4638 }
4639 
4640 // Custom lowering for any store, vector or scalar and/or default or with
4641 // a truncate operations.  Currently only custom lower truncate operation
4642 // from vector v4i16 to v4i8 or volatile stores of i128.
LowerSTORE(SDValue Op,SelectionDAG & DAG) const4643 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
4644                                           SelectionDAG &DAG) const {
4645   SDLoc Dl(Op);
4646   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
4647   assert (StoreNode && "Can only custom lower store nodes");
4648 
4649   SDValue Value = StoreNode->getValue();
4650 
4651   EVT VT = Value.getValueType();
4652   EVT MemVT = StoreNode->getMemoryVT();
4653 
4654   if (VT.isVector()) {
4655     if (useSVEForFixedLengthVectorVT(VT, true))
4656       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
4657 
4658     unsigned AS = StoreNode->getAddressSpace();
4659     Align Alignment = StoreNode->getAlign();
4660     if (Alignment < MemVT.getStoreSize() &&
4661         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment,
4662                                         StoreNode->getMemOperand()->getFlags(),
4663                                         nullptr)) {
4664       return scalarizeVectorStore(StoreNode, DAG);
4665     }
4666 
4667     if (StoreNode->isTruncatingStore() && VT == MVT::v4i16 &&
4668         MemVT == MVT::v4i8) {
4669       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
4670     }
4671     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
4672     // the custom lowering, as there are no un-paired non-temporal stores and
4673     // legalization will break up 256 bit inputs.
4674     ElementCount EC = MemVT.getVectorElementCount();
4675     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
4676         EC.isKnownEven() &&
4677         ((MemVT.getScalarSizeInBits() == 8u ||
4678           MemVT.getScalarSizeInBits() == 16u ||
4679           MemVT.getScalarSizeInBits() == 32u ||
4680           MemVT.getScalarSizeInBits() == 64u))) {
4681       SDValue Lo =
4682           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4683                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4684                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
4685       SDValue Hi =
4686           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4687                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4688                       StoreNode->getValue(),
4689                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
4690       SDValue Result = DAG.getMemIntrinsicNode(
4691           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
4692           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4693           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4694       return Result;
4695     }
4696   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
4697     return LowerStore128(Op, DAG);
4698   } else if (MemVT == MVT::i64x8) {
4699     SDValue Value = StoreNode->getValue();
4700     assert(Value->getValueType(0) == MVT::i64x8);
4701     SDValue Chain = StoreNode->getChain();
4702     SDValue Base = StoreNode->getBasePtr();
4703     EVT PtrVT = Base.getValueType();
4704     for (unsigned i = 0; i < 8; i++) {
4705       SDValue Part = DAG.getNode(AArch64ISD::LS64_EXTRACT, Dl, MVT::i64,
4706                                  Value, DAG.getConstant(i, Dl, MVT::i32));
4707       SDValue Ptr = DAG.getNode(ISD::ADD, Dl, PtrVT, Base,
4708                                 DAG.getConstant(i * 8, Dl, PtrVT));
4709       Chain = DAG.getStore(Chain, Dl, Part, Ptr, StoreNode->getPointerInfo(),
4710                            StoreNode->getOriginalAlign());
4711     }
4712     return Chain;
4713   }
4714 
4715   return SDValue();
4716 }
4717 
4718 /// Lower atomic or volatile 128-bit stores to a single STP instruction.
LowerStore128(SDValue Op,SelectionDAG & DAG) const4719 SDValue AArch64TargetLowering::LowerStore128(SDValue Op,
4720                                              SelectionDAG &DAG) const {
4721   MemSDNode *StoreNode = cast<MemSDNode>(Op);
4722   assert(StoreNode->getMemoryVT() == MVT::i128);
4723   assert(StoreNode->isVolatile() || StoreNode->isAtomic());
4724   assert(!StoreNode->isAtomic() ||
4725          StoreNode->getMergedOrdering() == AtomicOrdering::Unordered ||
4726          StoreNode->getMergedOrdering() == AtomicOrdering::Monotonic);
4727 
4728   SDValue Value = StoreNode->getOpcode() == ISD::STORE
4729                       ? StoreNode->getOperand(1)
4730                       : StoreNode->getOperand(2);
4731   SDLoc DL(Op);
4732   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
4733                            DAG.getConstant(0, DL, MVT::i64));
4734   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
4735                            DAG.getConstant(1, DL, MVT::i64));
4736   SDValue Result = DAG.getMemIntrinsicNode(
4737       AArch64ISD::STP, DL, DAG.getVTList(MVT::Other),
4738       {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4739       StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4740   return Result;
4741 }
4742 
LowerLOAD(SDValue Op,SelectionDAG & DAG) const4743 SDValue AArch64TargetLowering::LowerLOAD(SDValue Op,
4744                                          SelectionDAG &DAG) const {
4745   SDLoc DL(Op);
4746   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
4747   assert(LoadNode && "Expected custom lowering of a load node");
4748 
4749   if (LoadNode->getMemoryVT() == MVT::i64x8) {
4750     SmallVector<SDValue, 8> Ops;
4751     SDValue Base = LoadNode->getBasePtr();
4752     SDValue Chain = LoadNode->getChain();
4753     EVT PtrVT = Base.getValueType();
4754     for (unsigned i = 0; i < 8; i++) {
4755       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
4756                                 DAG.getConstant(i * 8, DL, PtrVT));
4757       SDValue Part = DAG.getLoad(MVT::i64, DL, Chain, Ptr,
4758                                  LoadNode->getPointerInfo(),
4759                                  LoadNode->getOriginalAlign());
4760       Ops.push_back(Part);
4761       Chain = SDValue(Part.getNode(), 1);
4762     }
4763     SDValue Loaded = DAG.getNode(AArch64ISD::LS64_BUILD, DL, MVT::i64x8, Ops);
4764     return DAG.getMergeValues({Loaded, Chain}, DL);
4765   }
4766 
4767   // Custom lowering for extending v4i8 vector loads.
4768   EVT VT = Op->getValueType(0);
4769   assert((VT == MVT::v4i16 || VT == MVT::v4i32) && "Expected v4i16 or v4i32");
4770 
4771   if (LoadNode->getMemoryVT() != MVT::v4i8)
4772     return SDValue();
4773 
4774   unsigned ExtType;
4775   if (LoadNode->getExtensionType() == ISD::SEXTLOAD)
4776     ExtType = ISD::SIGN_EXTEND;
4777   else if (LoadNode->getExtensionType() == ISD::ZEXTLOAD ||
4778            LoadNode->getExtensionType() == ISD::EXTLOAD)
4779     ExtType = ISD::ZERO_EXTEND;
4780   else
4781     return SDValue();
4782 
4783   SDValue Load = DAG.getLoad(MVT::f32, DL, LoadNode->getChain(),
4784                              LoadNode->getBasePtr(), MachinePointerInfo());
4785   SDValue Chain = Load.getValue(1);
4786   SDValue Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f32, Load);
4787   SDValue BC = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Vec);
4788   SDValue Ext = DAG.getNode(ExtType, DL, MVT::v8i16, BC);
4789   Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Ext,
4790                     DAG.getConstant(0, DL, MVT::i64));
4791   if (VT == MVT::v4i32)
4792     Ext = DAG.getNode(ExtType, DL, MVT::v4i32, Ext);
4793   return DAG.getMergeValues({Ext, Chain}, DL);
4794 }
4795 
4796 // Generate SUBS and CSEL for integer abs.
LowerABS(SDValue Op,SelectionDAG & DAG) const4797 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
4798   MVT VT = Op.getSimpleValueType();
4799 
4800   if (VT.isVector())
4801     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
4802 
4803   SDLoc DL(Op);
4804   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4805                             Op.getOperand(0));
4806   // Generate SUBS & CSEL.
4807   SDValue Cmp =
4808       DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
4809                   Op.getOperand(0), DAG.getConstant(0, DL, VT));
4810   return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
4811                      DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
4812                      Cmp.getValue(1));
4813 }
4814 
LowerOperation(SDValue Op,SelectionDAG & DAG) const4815 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
4816                                               SelectionDAG &DAG) const {
4817   LLVM_DEBUG(dbgs() << "Custom lowering: ");
4818   LLVM_DEBUG(Op.dump());
4819 
4820   switch (Op.getOpcode()) {
4821   default:
4822     llvm_unreachable("unimplemented operand");
4823     return SDValue();
4824   case ISD::BITCAST:
4825     return LowerBITCAST(Op, DAG);
4826   case ISD::GlobalAddress:
4827     return LowerGlobalAddress(Op, DAG);
4828   case ISD::GlobalTLSAddress:
4829     return LowerGlobalTLSAddress(Op, DAG);
4830   case ISD::SETCC:
4831   case ISD::STRICT_FSETCC:
4832   case ISD::STRICT_FSETCCS:
4833     return LowerSETCC(Op, DAG);
4834   case ISD::BR_CC:
4835     return LowerBR_CC(Op, DAG);
4836   case ISD::SELECT:
4837     return LowerSELECT(Op, DAG);
4838   case ISD::SELECT_CC:
4839     return LowerSELECT_CC(Op, DAG);
4840   case ISD::JumpTable:
4841     return LowerJumpTable(Op, DAG);
4842   case ISD::BR_JT:
4843     return LowerBR_JT(Op, DAG);
4844   case ISD::ConstantPool:
4845     return LowerConstantPool(Op, DAG);
4846   case ISD::BlockAddress:
4847     return LowerBlockAddress(Op, DAG);
4848   case ISD::VASTART:
4849     return LowerVASTART(Op, DAG);
4850   case ISD::VACOPY:
4851     return LowerVACOPY(Op, DAG);
4852   case ISD::VAARG:
4853     return LowerVAARG(Op, DAG);
4854   case ISD::ADDC:
4855   case ISD::ADDE:
4856   case ISD::SUBC:
4857   case ISD::SUBE:
4858     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
4859   case ISD::SADDO:
4860   case ISD::UADDO:
4861   case ISD::SSUBO:
4862   case ISD::USUBO:
4863   case ISD::SMULO:
4864   case ISD::UMULO:
4865     return LowerXALUO(Op, DAG);
4866   case ISD::FADD:
4867     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
4868   case ISD::FSUB:
4869     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
4870   case ISD::FMUL:
4871     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
4872   case ISD::FMA:
4873     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
4874   case ISD::FDIV:
4875     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
4876   case ISD::FNEG:
4877     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
4878   case ISD::FCEIL:
4879     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
4880   case ISD::FFLOOR:
4881     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
4882   case ISD::FNEARBYINT:
4883     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
4884   case ISD::FRINT:
4885     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
4886   case ISD::FROUND:
4887     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
4888   case ISD::FROUNDEVEN:
4889     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
4890   case ISD::FTRUNC:
4891     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
4892   case ISD::FSQRT:
4893     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
4894   case ISD::FABS:
4895     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
4896   case ISD::FP_ROUND:
4897   case ISD::STRICT_FP_ROUND:
4898     return LowerFP_ROUND(Op, DAG);
4899   case ISD::FP_EXTEND:
4900     return LowerFP_EXTEND(Op, DAG);
4901   case ISD::FRAMEADDR:
4902     return LowerFRAMEADDR(Op, DAG);
4903   case ISD::SPONENTRY:
4904     return LowerSPONENTRY(Op, DAG);
4905   case ISD::RETURNADDR:
4906     return LowerRETURNADDR(Op, DAG);
4907   case ISD::ADDROFRETURNADDR:
4908     return LowerADDROFRETURNADDR(Op, DAG);
4909   case ISD::CONCAT_VECTORS:
4910     return LowerCONCAT_VECTORS(Op, DAG);
4911   case ISD::INSERT_VECTOR_ELT:
4912     return LowerINSERT_VECTOR_ELT(Op, DAG);
4913   case ISD::EXTRACT_VECTOR_ELT:
4914     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4915   case ISD::BUILD_VECTOR:
4916     return LowerBUILD_VECTOR(Op, DAG);
4917   case ISD::VECTOR_SHUFFLE:
4918     return LowerVECTOR_SHUFFLE(Op, DAG);
4919   case ISD::SPLAT_VECTOR:
4920     return LowerSPLAT_VECTOR(Op, DAG);
4921   case ISD::EXTRACT_SUBVECTOR:
4922     return LowerEXTRACT_SUBVECTOR(Op, DAG);
4923   case ISD::INSERT_SUBVECTOR:
4924     return LowerINSERT_SUBVECTOR(Op, DAG);
4925   case ISD::SDIV:
4926   case ISD::UDIV:
4927     return LowerDIV(Op, DAG);
4928   case ISD::SMIN:
4929   case ISD::UMIN:
4930   case ISD::SMAX:
4931   case ISD::UMAX:
4932     return LowerMinMax(Op, DAG);
4933   case ISD::SRA:
4934   case ISD::SRL:
4935   case ISD::SHL:
4936     return LowerVectorSRA_SRL_SHL(Op, DAG);
4937   case ISD::SHL_PARTS:
4938   case ISD::SRL_PARTS:
4939   case ISD::SRA_PARTS:
4940     return LowerShiftParts(Op, DAG);
4941   case ISD::CTPOP:
4942     return LowerCTPOP(Op, DAG);
4943   case ISD::FCOPYSIGN:
4944     return LowerFCOPYSIGN(Op, DAG);
4945   case ISD::OR:
4946     return LowerVectorOR(Op, DAG);
4947   case ISD::XOR:
4948     return LowerXOR(Op, DAG);
4949   case ISD::PREFETCH:
4950     return LowerPREFETCH(Op, DAG);
4951   case ISD::SINT_TO_FP:
4952   case ISD::UINT_TO_FP:
4953   case ISD::STRICT_SINT_TO_FP:
4954   case ISD::STRICT_UINT_TO_FP:
4955     return LowerINT_TO_FP(Op, DAG);
4956   case ISD::FP_TO_SINT:
4957   case ISD::FP_TO_UINT:
4958   case ISD::STRICT_FP_TO_SINT:
4959   case ISD::STRICT_FP_TO_UINT:
4960     return LowerFP_TO_INT(Op, DAG);
4961   case ISD::FP_TO_SINT_SAT:
4962   case ISD::FP_TO_UINT_SAT:
4963     return LowerFP_TO_INT_SAT(Op, DAG);
4964   case ISD::FSINCOS:
4965     return LowerFSINCOS(Op, DAG);
4966   case ISD::FLT_ROUNDS_:
4967     return LowerFLT_ROUNDS_(Op, DAG);
4968   case ISD::SET_ROUNDING:
4969     return LowerSET_ROUNDING(Op, DAG);
4970   case ISD::MUL:
4971     return LowerMUL(Op, DAG);
4972   case ISD::MULHS:
4973     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHS_PRED,
4974                                /*OverrideNEON=*/true);
4975   case ISD::MULHU:
4976     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHU_PRED,
4977                                /*OverrideNEON=*/true);
4978   case ISD::INTRINSIC_WO_CHAIN:
4979     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4980   case ISD::ATOMIC_STORE:
4981     if (cast<MemSDNode>(Op)->getMemoryVT() == MVT::i128) {
4982       assert(Subtarget->hasLSE2());
4983       return LowerStore128(Op, DAG);
4984     }
4985     return SDValue();
4986   case ISD::STORE:
4987     return LowerSTORE(Op, DAG);
4988   case ISD::MSTORE:
4989     return LowerFixedLengthVectorMStoreToSVE(Op, DAG);
4990   case ISD::MGATHER:
4991     return LowerMGATHER(Op, DAG);
4992   case ISD::MSCATTER:
4993     return LowerMSCATTER(Op, DAG);
4994   case ISD::VECREDUCE_SEQ_FADD:
4995     return LowerVECREDUCE_SEQ_FADD(Op, DAG);
4996   case ISD::VECREDUCE_ADD:
4997   case ISD::VECREDUCE_AND:
4998   case ISD::VECREDUCE_OR:
4999   case ISD::VECREDUCE_XOR:
5000   case ISD::VECREDUCE_SMAX:
5001   case ISD::VECREDUCE_SMIN:
5002   case ISD::VECREDUCE_UMAX:
5003   case ISD::VECREDUCE_UMIN:
5004   case ISD::VECREDUCE_FADD:
5005   case ISD::VECREDUCE_FMAX:
5006   case ISD::VECREDUCE_FMIN:
5007     return LowerVECREDUCE(Op, DAG);
5008   case ISD::ATOMIC_LOAD_SUB:
5009     return LowerATOMIC_LOAD_SUB(Op, DAG);
5010   case ISD::ATOMIC_LOAD_AND:
5011     return LowerATOMIC_LOAD_AND(Op, DAG);
5012   case ISD::DYNAMIC_STACKALLOC:
5013     return LowerDYNAMIC_STACKALLOC(Op, DAG);
5014   case ISD::VSCALE:
5015     return LowerVSCALE(Op, DAG);
5016   case ISD::ANY_EXTEND:
5017   case ISD::SIGN_EXTEND:
5018   case ISD::ZERO_EXTEND:
5019     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
5020   case ISD::SIGN_EXTEND_INREG: {
5021     // Only custom lower when ExtraVT has a legal byte based element type.
5022     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5023     EVT ExtraEltVT = ExtraVT.getVectorElementType();
5024     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
5025         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
5026       return SDValue();
5027 
5028     return LowerToPredicatedOp(Op, DAG,
5029                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
5030   }
5031   case ISD::TRUNCATE:
5032     return LowerTRUNCATE(Op, DAG);
5033   case ISD::MLOAD:
5034     return LowerMLOAD(Op, DAG);
5035   case ISD::LOAD:
5036     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
5037       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
5038     return LowerLOAD(Op, DAG);
5039   case ISD::ADD:
5040     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
5041   case ISD::AND:
5042     return LowerToScalableOp(Op, DAG);
5043   case ISD::SUB:
5044     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
5045   case ISD::FMAXIMUM:
5046     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED);
5047   case ISD::FMAXNUM:
5048     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
5049   case ISD::FMINIMUM:
5050     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED);
5051   case ISD::FMINNUM:
5052     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
5053   case ISD::VSELECT:
5054     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
5055   case ISD::ABS:
5056     return LowerABS(Op, DAG);
5057   case ISD::BITREVERSE:
5058     return LowerBitreverse(Op, DAG);
5059   case ISD::BSWAP:
5060     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
5061   case ISD::CTLZ:
5062     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU,
5063                                /*OverrideNEON=*/true);
5064   case ISD::CTTZ:
5065     return LowerCTTZ(Op, DAG);
5066   case ISD::VECTOR_SPLICE:
5067     return LowerVECTOR_SPLICE(Op, DAG);
5068   }
5069 }
5070 
mergeStoresAfterLegalization(EVT VT) const5071 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
5072   return !Subtarget->useSVEForFixedLengthVectors();
5073 }
5074 
useSVEForFixedLengthVectorVT(EVT VT,bool OverrideNEON) const5075 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
5076     EVT VT, bool OverrideNEON) const {
5077   if (!Subtarget->useSVEForFixedLengthVectors())
5078     return false;
5079 
5080   if (!VT.isFixedLengthVector())
5081     return false;
5082 
5083   // Don't use SVE for vectors we cannot scalarize if required.
5084   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
5085   // Fixed length predicates should be promoted to i8.
5086   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
5087   case MVT::i1:
5088   default:
5089     return false;
5090   case MVT::i8:
5091   case MVT::i16:
5092   case MVT::i32:
5093   case MVT::i64:
5094   case MVT::f16:
5095   case MVT::f32:
5096   case MVT::f64:
5097     break;
5098   }
5099 
5100   // All SVE implementations support NEON sized vectors.
5101   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
5102     return true;
5103 
5104   // Ensure NEON MVTs only belong to a single register class.
5105   if (VT.getFixedSizeInBits() <= 128)
5106     return false;
5107 
5108   // Don't use SVE for types that don't fit.
5109   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
5110     return false;
5111 
5112   // TODO: Perhaps an artificial restriction, but worth having whilst getting
5113   // the base fixed length SVE support in place.
5114   if (!VT.isPow2VectorType())
5115     return false;
5116 
5117   return true;
5118 }
5119 
5120 //===----------------------------------------------------------------------===//
5121 //                      Calling Convention Implementation
5122 //===----------------------------------------------------------------------===//
5123 
5124 /// Selects the correct CCAssignFn for a given CallingConvention value.
CCAssignFnForCall(CallingConv::ID CC,bool IsVarArg) const5125 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
5126                                                      bool IsVarArg) const {
5127   switch (CC) {
5128   default:
5129     report_fatal_error("Unsupported calling convention.");
5130   case CallingConv::WebKit_JS:
5131     return CC_AArch64_WebKit_JS;
5132   case CallingConv::GHC:
5133     return CC_AArch64_GHC;
5134   case CallingConv::C:
5135   case CallingConv::Fast:
5136   case CallingConv::PreserveMost:
5137   case CallingConv::CXX_FAST_TLS:
5138   case CallingConv::Swift:
5139   case CallingConv::SwiftTail:
5140   case CallingConv::Tail:
5141     if (Subtarget->isTargetWindows() && IsVarArg)
5142       return CC_AArch64_Win64_VarArg;
5143     if (!Subtarget->isTargetDarwin())
5144       return CC_AArch64_AAPCS;
5145     if (!IsVarArg)
5146       return CC_AArch64_DarwinPCS;
5147     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
5148                                       : CC_AArch64_DarwinPCS_VarArg;
5149    case CallingConv::Win64:
5150     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
5151    case CallingConv::CFGuard_Check:
5152      return CC_AArch64_Win64_CFGuard_Check;
5153    case CallingConv::AArch64_VectorCall:
5154    case CallingConv::AArch64_SVE_VectorCall:
5155      return CC_AArch64_AAPCS;
5156   }
5157 }
5158 
5159 CCAssignFn *
CCAssignFnForReturn(CallingConv::ID CC) const5160 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
5161   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
5162                                       : RetCC_AArch64_AAPCS;
5163 }
5164 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const5165 SDValue AArch64TargetLowering::LowerFormalArguments(
5166     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
5167     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5168     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5169   MachineFunction &MF = DAG.getMachineFunction();
5170   MachineFrameInfo &MFI = MF.getFrameInfo();
5171   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
5172 
5173   // Assign locations to all of the incoming arguments.
5174   SmallVector<CCValAssign, 16> ArgLocs;
5175   DenseMap<unsigned, SDValue> CopiedRegs;
5176   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5177 
5178   // At this point, Ins[].VT may already be promoted to i32. To correctly
5179   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
5180   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
5181   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
5182   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
5183   // LocVT.
5184   unsigned NumArgs = Ins.size();
5185   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
5186   unsigned CurArgIdx = 0;
5187   for (unsigned i = 0; i != NumArgs; ++i) {
5188     MVT ValVT = Ins[i].VT;
5189     if (Ins[i].isOrigArg()) {
5190       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
5191       CurArgIdx = Ins[i].getOrigArgIndex();
5192 
5193       // Get type of the original argument.
5194       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
5195                                   /*AllowUnknown*/ true);
5196       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
5197       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5198       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
5199         ValVT = MVT::i8;
5200       else if (ActualMVT == MVT::i16)
5201         ValVT = MVT::i16;
5202     }
5203     bool UseVarArgCC = false;
5204     if (IsWin64)
5205       UseVarArgCC = isVarArg;
5206     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
5207     bool Res =
5208         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
5209     assert(!Res && "Call operand has unhandled type");
5210     (void)Res;
5211   }
5212   SmallVector<SDValue, 16> ArgValues;
5213   unsigned ExtraArgLocs = 0;
5214   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5215     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
5216 
5217     if (Ins[i].Flags.isByVal()) {
5218       // Byval is used for HFAs in the PCS, but the system should work in a
5219       // non-compliant manner for larger structs.
5220       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5221       int Size = Ins[i].Flags.getByValSize();
5222       unsigned NumRegs = (Size + 7) / 8;
5223 
5224       // FIXME: This works on big-endian for composite byvals, which are the common
5225       // case. It should also work for fundamental types too.
5226       unsigned FrameIdx =
5227         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
5228       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
5229       InVals.push_back(FrameIdxN);
5230 
5231       continue;
5232     }
5233 
5234     if (Ins[i].Flags.isSwiftAsync())
5235       MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
5236 
5237     SDValue ArgValue;
5238     if (VA.isRegLoc()) {
5239       // Arguments stored in registers.
5240       EVT RegVT = VA.getLocVT();
5241       const TargetRegisterClass *RC;
5242 
5243       if (RegVT == MVT::i32)
5244         RC = &AArch64::GPR32RegClass;
5245       else if (RegVT == MVT::i64)
5246         RC = &AArch64::GPR64RegClass;
5247       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
5248         RC = &AArch64::FPR16RegClass;
5249       else if (RegVT == MVT::f32)
5250         RC = &AArch64::FPR32RegClass;
5251       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
5252         RC = &AArch64::FPR64RegClass;
5253       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
5254         RC = &AArch64::FPR128RegClass;
5255       else if (RegVT.isScalableVector() &&
5256                RegVT.getVectorElementType() == MVT::i1)
5257         RC = &AArch64::PPRRegClass;
5258       else if (RegVT.isScalableVector())
5259         RC = &AArch64::ZPRRegClass;
5260       else
5261         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
5262 
5263       // Transform the arguments in physical registers into virtual ones.
5264       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
5265       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
5266 
5267       // If this is an 8, 16 or 32-bit value, it is really passed promoted
5268       // to 64 bits.  Insert an assert[sz]ext to capture this, then
5269       // truncate to the right size.
5270       switch (VA.getLocInfo()) {
5271       default:
5272         llvm_unreachable("Unknown loc info!");
5273       case CCValAssign::Full:
5274         break;
5275       case CCValAssign::Indirect:
5276         assert(VA.getValVT().isScalableVector() &&
5277                "Only scalable vectors can be passed indirectly");
5278         break;
5279       case CCValAssign::BCvt:
5280         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
5281         break;
5282       case CCValAssign::AExt:
5283       case CCValAssign::SExt:
5284       case CCValAssign::ZExt:
5285         break;
5286       case CCValAssign::AExtUpper:
5287         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
5288                                DAG.getConstant(32, DL, RegVT));
5289         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
5290         break;
5291       }
5292     } else { // VA.isRegLoc()
5293       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
5294       unsigned ArgOffset = VA.getLocMemOffset();
5295       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
5296                               ? VA.getLocVT().getSizeInBits()
5297                               : VA.getValVT().getSizeInBits()) / 8;
5298 
5299       uint32_t BEAlign = 0;
5300       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
5301           !Ins[i].Flags.isInConsecutiveRegs())
5302         BEAlign = 8 - ArgSize;
5303 
5304       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
5305 
5306       // Create load nodes to retrieve arguments from the stack.
5307       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
5308 
5309       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
5310       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5311       MVT MemVT = VA.getValVT();
5312 
5313       switch (VA.getLocInfo()) {
5314       default:
5315         break;
5316       case CCValAssign::Trunc:
5317       case CCValAssign::BCvt:
5318         MemVT = VA.getLocVT();
5319         break;
5320       case CCValAssign::Indirect:
5321         assert(VA.getValVT().isScalableVector() &&
5322                "Only scalable vectors can be passed indirectly");
5323         MemVT = VA.getLocVT();
5324         break;
5325       case CCValAssign::SExt:
5326         ExtType = ISD::SEXTLOAD;
5327         break;
5328       case CCValAssign::ZExt:
5329         ExtType = ISD::ZEXTLOAD;
5330         break;
5331       case CCValAssign::AExt:
5332         ExtType = ISD::EXTLOAD;
5333         break;
5334       }
5335 
5336       ArgValue =
5337           DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
5338                          MachinePointerInfo::getFixedStack(MF, FI), MemVT);
5339     }
5340 
5341     if (VA.getLocInfo() == CCValAssign::Indirect) {
5342       assert(VA.getValVT().isScalableVector() &&
5343            "Only scalable vectors can be passed indirectly");
5344 
5345       uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize();
5346       unsigned NumParts = 1;
5347       if (Ins[i].Flags.isInConsecutiveRegs()) {
5348         assert(!Ins[i].Flags.isInConsecutiveRegsLast());
5349         while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
5350           ++NumParts;
5351       }
5352 
5353       MVT PartLoad = VA.getValVT();
5354       SDValue Ptr = ArgValue;
5355 
5356       // Ensure we generate all loads for each tuple part, whilst updating the
5357       // pointer after each load correctly using vscale.
5358       while (NumParts > 0) {
5359         ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
5360         InVals.push_back(ArgValue);
5361         NumParts--;
5362         if (NumParts > 0) {
5363           SDValue BytesIncrement = DAG.getVScale(
5364               DL, Ptr.getValueType(),
5365               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
5366           SDNodeFlags Flags;
5367           Flags.setNoUnsignedWrap(true);
5368           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5369                             BytesIncrement, Flags);
5370           ExtraArgLocs++;
5371           i++;
5372         }
5373       }
5374     } else {
5375       if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
5376         ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
5377                                ArgValue, DAG.getValueType(MVT::i32));
5378 
5379       // i1 arguments are zero-extended to i8 by the caller. Emit a
5380       // hint to reflect this.
5381       if (Ins[i].isOrigArg()) {
5382         Argument *OrigArg = MF.getFunction().getArg(Ins[i].getOrigArgIndex());
5383         if (OrigArg->getType()->isIntegerTy(1)) {
5384           if (!Ins[i].Flags.isZExt()) {
5385             ArgValue = DAG.getNode(AArch64ISD::ASSERT_ZEXT_BOOL, DL,
5386                                    ArgValue.getValueType(), ArgValue);
5387           }
5388         }
5389       }
5390 
5391       InVals.push_back(ArgValue);
5392     }
5393   }
5394   assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
5395 
5396   // varargs
5397   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5398   if (isVarArg) {
5399     if (!Subtarget->isTargetDarwin() || IsWin64) {
5400       // The AAPCS variadic function ABI is identical to the non-variadic
5401       // one. As a result there may be more arguments in registers and we should
5402       // save them for future reference.
5403       // Win64 variadic functions also pass arguments in registers, but all float
5404       // arguments are passed in integer registers.
5405       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
5406     }
5407 
5408     // This will point to the next argument passed via stack.
5409     unsigned StackOffset = CCInfo.getNextStackOffset();
5410     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
5411     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
5412     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
5413 
5414     if (MFI.hasMustTailInVarArgFunc()) {
5415       SmallVector<MVT, 2> RegParmTypes;
5416       RegParmTypes.push_back(MVT::i64);
5417       RegParmTypes.push_back(MVT::f128);
5418       // Compute the set of forwarded registers. The rest are scratch.
5419       SmallVectorImpl<ForwardedRegister> &Forwards =
5420                                        FuncInfo->getForwardedMustTailRegParms();
5421       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
5422                                                CC_AArch64_AAPCS);
5423 
5424       // Conservatively forward X8, since it might be used for aggregate return.
5425       if (!CCInfo.isAllocated(AArch64::X8)) {
5426         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
5427         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
5428       }
5429     }
5430   }
5431 
5432   // On Windows, InReg pointers must be returned, so record the pointer in a
5433   // virtual register at the start of the function so it can be returned in the
5434   // epilogue.
5435   if (IsWin64) {
5436     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
5437       if (Ins[I].Flags.isInReg()) {
5438         assert(!FuncInfo->getSRetReturnReg());
5439 
5440         MVT PtrTy = getPointerTy(DAG.getDataLayout());
5441         Register Reg =
5442             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
5443         FuncInfo->setSRetReturnReg(Reg);
5444 
5445         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
5446         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
5447         break;
5448       }
5449     }
5450   }
5451 
5452   unsigned StackArgSize = CCInfo.getNextStackOffset();
5453   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
5454   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
5455     // This is a non-standard ABI so by fiat I say we're allowed to make full
5456     // use of the stack area to be popped, which must be aligned to 16 bytes in
5457     // any case:
5458     StackArgSize = alignTo(StackArgSize, 16);
5459 
5460     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
5461     // a multiple of 16.
5462     FuncInfo->setArgumentStackToRestore(StackArgSize);
5463 
5464     // This realignment carries over to the available bytes below. Our own
5465     // callers will guarantee the space is free by giving an aligned value to
5466     // CALLSEQ_START.
5467   }
5468   // Even if we're not expected to free up the space, it's useful to know how
5469   // much is there while considering tail calls (because we can reuse it).
5470   FuncInfo->setBytesInStackArgArea(StackArgSize);
5471 
5472   if (Subtarget->hasCustomCallingConv())
5473     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
5474 
5475   return Chain;
5476 }
5477 
saveVarArgRegisters(CCState & CCInfo,SelectionDAG & DAG,const SDLoc & DL,SDValue & Chain) const5478 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
5479                                                 SelectionDAG &DAG,
5480                                                 const SDLoc &DL,
5481                                                 SDValue &Chain) const {
5482   MachineFunction &MF = DAG.getMachineFunction();
5483   MachineFrameInfo &MFI = MF.getFrameInfo();
5484   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5485   auto PtrVT = getPointerTy(DAG.getDataLayout());
5486   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
5487 
5488   SmallVector<SDValue, 8> MemOps;
5489 
5490   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
5491                                           AArch64::X3, AArch64::X4, AArch64::X5,
5492                                           AArch64::X6, AArch64::X7 };
5493   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
5494   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
5495 
5496   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
5497   int GPRIdx = 0;
5498   if (GPRSaveSize != 0) {
5499     if (IsWin64) {
5500       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
5501       if (GPRSaveSize & 15)
5502         // The extra size here, if triggered, will always be 8.
5503         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
5504     } else
5505       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
5506 
5507     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
5508 
5509     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
5510       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
5511       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
5512       SDValue Store =
5513           DAG.getStore(Val.getValue(1), DL, Val, FIN,
5514                        IsWin64 ? MachinePointerInfo::getFixedStack(
5515                                      MF, GPRIdx, (i - FirstVariadicGPR) * 8)
5516                                : MachinePointerInfo::getStack(MF, i * 8));
5517       MemOps.push_back(Store);
5518       FIN =
5519           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
5520     }
5521   }
5522   FuncInfo->setVarArgsGPRIndex(GPRIdx);
5523   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
5524 
5525   if (Subtarget->hasFPARMv8() && !IsWin64) {
5526     static const MCPhysReg FPRArgRegs[] = {
5527         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
5528         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
5529     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
5530     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
5531 
5532     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
5533     int FPRIdx = 0;
5534     if (FPRSaveSize != 0) {
5535       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
5536 
5537       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
5538 
5539       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
5540         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
5541         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
5542 
5543         SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
5544                                      MachinePointerInfo::getStack(MF, i * 16));
5545         MemOps.push_back(Store);
5546         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
5547                           DAG.getConstant(16, DL, PtrVT));
5548       }
5549     }
5550     FuncInfo->setVarArgsFPRIndex(FPRIdx);
5551     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
5552   }
5553 
5554   if (!MemOps.empty()) {
5555     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5556   }
5557 }
5558 
5559 /// LowerCallResult - Lower the result values of a call into the
5560 /// appropriate copies out of appropriate physical registers.
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool isThisReturn,SDValue ThisVal) const5561 SDValue AArch64TargetLowering::LowerCallResult(
5562     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5563     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5564     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
5565     SDValue ThisVal) const {
5566   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5567   // Assign locations to each value returned by this call.
5568   SmallVector<CCValAssign, 16> RVLocs;
5569   DenseMap<unsigned, SDValue> CopiedRegs;
5570   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5571                  *DAG.getContext());
5572   CCInfo.AnalyzeCallResult(Ins, RetCC);
5573 
5574   // Copy all of the result registers out of their specified physreg.
5575   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5576     CCValAssign VA = RVLocs[i];
5577 
5578     // Pass 'this' value directly from the argument to return value, to avoid
5579     // reg unit interference
5580     if (i == 0 && isThisReturn) {
5581       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
5582              "unexpected return calling convention register assignment");
5583       InVals.push_back(ThisVal);
5584       continue;
5585     }
5586 
5587     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
5588     // allows one use of a physreg per block.
5589     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
5590     if (!Val) {
5591       Val =
5592           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
5593       Chain = Val.getValue(1);
5594       InFlag = Val.getValue(2);
5595       CopiedRegs[VA.getLocReg()] = Val;
5596     }
5597 
5598     switch (VA.getLocInfo()) {
5599     default:
5600       llvm_unreachable("Unknown loc info!");
5601     case CCValAssign::Full:
5602       break;
5603     case CCValAssign::BCvt:
5604       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
5605       break;
5606     case CCValAssign::AExtUpper:
5607       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
5608                         DAG.getConstant(32, DL, VA.getLocVT()));
5609       LLVM_FALLTHROUGH;
5610     case CCValAssign::AExt:
5611       LLVM_FALLTHROUGH;
5612     case CCValAssign::ZExt:
5613       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
5614       break;
5615     }
5616 
5617     InVals.push_back(Val);
5618   }
5619 
5620   return Chain;
5621 }
5622 
5623 /// Return true if the calling convention is one that we can guarantee TCO for.
canGuaranteeTCO(CallingConv::ID CC,bool GuaranteeTailCalls)5624 static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
5625   return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
5626          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
5627 }
5628 
5629 /// Return true if we might ever do TCO for calls with this calling convention.
mayTailCallThisCC(CallingConv::ID CC)5630 static bool mayTailCallThisCC(CallingConv::ID CC) {
5631   switch (CC) {
5632   case CallingConv::C:
5633   case CallingConv::AArch64_SVE_VectorCall:
5634   case CallingConv::PreserveMost:
5635   case CallingConv::Swift:
5636   case CallingConv::SwiftTail:
5637   case CallingConv::Tail:
5638   case CallingConv::Fast:
5639     return true;
5640   default:
5641     return false;
5642   }
5643 }
5644 
isEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const5645 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
5646     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
5647     const SmallVectorImpl<ISD::OutputArg> &Outs,
5648     const SmallVectorImpl<SDValue> &OutVals,
5649     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
5650   if (!mayTailCallThisCC(CalleeCC))
5651     return false;
5652 
5653   MachineFunction &MF = DAG.getMachineFunction();
5654   const Function &CallerF = MF.getFunction();
5655   CallingConv::ID CallerCC = CallerF.getCallingConv();
5656 
5657   // Functions using the C or Fast calling convention that have an SVE signature
5658   // preserve more registers and should assume the SVE_VectorCall CC.
5659   // The check for matching callee-saved regs will determine whether it is
5660   // eligible for TCO.
5661   if ((CallerCC == CallingConv::C || CallerCC == CallingConv::Fast) &&
5662       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
5663     CallerCC = CallingConv::AArch64_SVE_VectorCall;
5664 
5665   bool CCMatch = CallerCC == CalleeCC;
5666 
5667   // When using the Windows calling convention on a non-windows OS, we want
5668   // to back up and restore X18 in such functions; we can't do a tail call
5669   // from those functions.
5670   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
5671       CalleeCC != CallingConv::Win64)
5672     return false;
5673 
5674   // Byval parameters hand the function a pointer directly into the stack area
5675   // we want to reuse during a tail call. Working around this *is* possible (see
5676   // X86) but less efficient and uglier in LowerCall.
5677   for (Function::const_arg_iterator i = CallerF.arg_begin(),
5678                                     e = CallerF.arg_end();
5679        i != e; ++i) {
5680     if (i->hasByValAttr())
5681       return false;
5682 
5683     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
5684     // In this case, it is necessary to save/restore X0 in the callee. Tail
5685     // call opt interferes with this. So we disable tail call opt when the
5686     // caller has an argument with "inreg" attribute.
5687 
5688     // FIXME: Check whether the callee also has an "inreg" argument.
5689     if (i->hasInRegAttr())
5690       return false;
5691   }
5692 
5693   if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
5694     return CCMatch;
5695 
5696   // Externally-defined functions with weak linkage should not be
5697   // tail-called on AArch64 when the OS does not support dynamic
5698   // pre-emption of symbols, as the AAELF spec requires normal calls
5699   // to undefined weak functions to be replaced with a NOP or jump to the
5700   // next instruction. The behaviour of branch instructions in this
5701   // situation (as used for tail calls) is implementation-defined, so we
5702   // cannot rely on the linker replacing the tail call with a return.
5703   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5704     const GlobalValue *GV = G->getGlobal();
5705     const Triple &TT = getTargetMachine().getTargetTriple();
5706     if (GV->hasExternalWeakLinkage() &&
5707         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
5708       return false;
5709   }
5710 
5711   // Now we search for cases where we can use a tail call without changing the
5712   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
5713   // concept.
5714 
5715   // I want anyone implementing a new calling convention to think long and hard
5716   // about this assert.
5717   assert((!isVarArg || CalleeCC == CallingConv::C) &&
5718          "Unexpected variadic calling convention");
5719 
5720   LLVMContext &C = *DAG.getContext();
5721   if (isVarArg && !Outs.empty()) {
5722     // At least two cases here: if caller is fastcc then we can't have any
5723     // memory arguments (we'd be expected to clean up the stack afterwards). If
5724     // caller is C then we could potentially use its argument area.
5725 
5726     // FIXME: for now we take the most conservative of these in both cases:
5727     // disallow all variadic memory operands.
5728     SmallVector<CCValAssign, 16> ArgLocs;
5729     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5730 
5731     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
5732     for (const CCValAssign &ArgLoc : ArgLocs)
5733       if (!ArgLoc.isRegLoc())
5734         return false;
5735   }
5736 
5737   // Check that the call results are passed in the same way.
5738   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
5739                                   CCAssignFnForCall(CalleeCC, isVarArg),
5740                                   CCAssignFnForCall(CallerCC, isVarArg)))
5741     return false;
5742   // The callee has to preserve all registers the caller needs to preserve.
5743   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5744   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5745   if (!CCMatch) {
5746     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5747     if (Subtarget->hasCustomCallingConv()) {
5748       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
5749       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
5750     }
5751     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5752       return false;
5753   }
5754 
5755   // Nothing more to check if the callee is taking no arguments
5756   if (Outs.empty())
5757     return true;
5758 
5759   SmallVector<CCValAssign, 16> ArgLocs;
5760   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5761 
5762   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
5763 
5764   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5765 
5766   // If any of the arguments is passed indirectly, it must be SVE, so the
5767   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
5768   // allocate space on the stack. That is why we determine this explicitly here
5769   // the call cannot be a tailcall.
5770   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
5771         assert((A.getLocInfo() != CCValAssign::Indirect ||
5772                 A.getValVT().isScalableVector()) &&
5773                "Expected value to be scalable");
5774         return A.getLocInfo() == CCValAssign::Indirect;
5775       }))
5776     return false;
5777 
5778   // If the stack arguments for this call do not fit into our own save area then
5779   // the call cannot be made tail.
5780   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
5781     return false;
5782 
5783   const MachineRegisterInfo &MRI = MF.getRegInfo();
5784   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
5785     return false;
5786 
5787   return true;
5788 }
5789 
addTokenForArgument(SDValue Chain,SelectionDAG & DAG,MachineFrameInfo & MFI,int ClobberedFI) const5790 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
5791                                                    SelectionDAG &DAG,
5792                                                    MachineFrameInfo &MFI,
5793                                                    int ClobberedFI) const {
5794   SmallVector<SDValue, 8> ArgChains;
5795   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
5796   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
5797 
5798   // Include the original chain at the beginning of the list. When this is
5799   // used by target LowerCall hooks, this helps legalize find the
5800   // CALLSEQ_BEGIN node.
5801   ArgChains.push_back(Chain);
5802 
5803   // Add a chain value for each stack argument corresponding
5804   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
5805                             UE = DAG.getEntryNode().getNode()->use_end();
5806        U != UE; ++U)
5807     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5808       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5809         if (FI->getIndex() < 0) {
5810           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
5811           int64_t InLastByte = InFirstByte;
5812           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
5813 
5814           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
5815               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
5816             ArgChains.push_back(SDValue(L, 1));
5817         }
5818 
5819   // Build a tokenfactor for all the chains.
5820   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5821 }
5822 
DoesCalleeRestoreStack(CallingConv::ID CallCC,bool TailCallOpt) const5823 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
5824                                                    bool TailCallOpt) const {
5825   return (CallCC == CallingConv::Fast && TailCallOpt) ||
5826          CallCC == CallingConv::Tail || CallCC == CallingConv::SwiftTail;
5827 }
5828 
5829 // Check if the value is zero-extended from i1 to i8
checkZExtBool(SDValue Arg,const SelectionDAG & DAG)5830 static bool checkZExtBool(SDValue Arg, const SelectionDAG &DAG) {
5831   unsigned SizeInBits = Arg.getValueType().getSizeInBits();
5832   if (SizeInBits < 8)
5833     return false;
5834 
5835   APInt LowBits(SizeInBits, 0xFF);
5836   APInt RequredZero(SizeInBits, 0xFE);
5837   KnownBits Bits = DAG.computeKnownBits(Arg, LowBits, 4);
5838   bool ZExtBool = (Bits.Zero & RequredZero) == RequredZero;
5839   return ZExtBool;
5840 }
5841 
5842 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
5843 /// and add input and output parameter nodes.
5844 SDValue
LowerCall(CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const5845 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
5846                                  SmallVectorImpl<SDValue> &InVals) const {
5847   SelectionDAG &DAG = CLI.DAG;
5848   SDLoc &DL = CLI.DL;
5849   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
5850   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
5851   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
5852   SDValue Chain = CLI.Chain;
5853   SDValue Callee = CLI.Callee;
5854   bool &IsTailCall = CLI.IsTailCall;
5855   CallingConv::ID CallConv = CLI.CallConv;
5856   bool IsVarArg = CLI.IsVarArg;
5857 
5858   MachineFunction &MF = DAG.getMachineFunction();
5859   MachineFunction::CallSiteInfo CSInfo;
5860   bool IsThisReturn = false;
5861 
5862   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5863   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
5864   bool IsSibCall = false;
5865   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CallConv);
5866 
5867   // Check callee args/returns for SVE registers and set calling convention
5868   // accordingly.
5869   if (CallConv == CallingConv::C || CallConv == CallingConv::Fast) {
5870     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
5871       return Out.VT.isScalableVector();
5872     });
5873     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
5874       return In.VT.isScalableVector();
5875     });
5876 
5877     if (CalleeInSVE || CalleeOutSVE)
5878       CallConv = CallingConv::AArch64_SVE_VectorCall;
5879   }
5880 
5881   if (IsTailCall) {
5882     // Check if it's really possible to do a tail call.
5883     IsTailCall = isEligibleForTailCallOptimization(
5884         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
5885 
5886     // A sibling call is one where we're under the usual C ABI and not planning
5887     // to change that but can still do a tail call:
5888     if (!TailCallOpt && IsTailCall && CallConv != CallingConv::Tail &&
5889         CallConv != CallingConv::SwiftTail)
5890       IsSibCall = true;
5891 
5892     if (IsTailCall)
5893       ++NumTailCalls;
5894   }
5895 
5896   if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
5897     report_fatal_error("failed to perform tail call elimination on a call "
5898                        "site marked musttail");
5899 
5900   // Analyze operands of the call, assigning locations to each operand.
5901   SmallVector<CCValAssign, 16> ArgLocs;
5902   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5903 
5904   if (IsVarArg) {
5905     // Handle fixed and variable vector arguments differently.
5906     // Variable vector arguments always go into memory.
5907     unsigned NumArgs = Outs.size();
5908 
5909     for (unsigned i = 0; i != NumArgs; ++i) {
5910       MVT ArgVT = Outs[i].VT;
5911       if (!Outs[i].IsFixed && ArgVT.isScalableVector())
5912         report_fatal_error("Passing SVE types to variadic functions is "
5913                            "currently not supported");
5914 
5915       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5916       bool UseVarArgCC = !Outs[i].IsFixed;
5917       // On Windows, the fixed arguments in a vararg call are passed in GPRs
5918       // too, so use the vararg CC to force them to integer registers.
5919       if (IsCalleeWin64)
5920         UseVarArgCC = true;
5921       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
5922       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
5923       assert(!Res && "Call operand has unhandled type");
5924       (void)Res;
5925     }
5926   } else {
5927     // At this point, Outs[].VT may already be promoted to i32. To correctly
5928     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
5929     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
5930     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
5931     // we use a special version of AnalyzeCallOperands to pass in ValVT and
5932     // LocVT.
5933     unsigned NumArgs = Outs.size();
5934     for (unsigned i = 0; i != NumArgs; ++i) {
5935       MVT ValVT = Outs[i].VT;
5936       // Get type of the original argument.
5937       EVT ActualVT = getValueType(DAG.getDataLayout(),
5938                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
5939                                   /*AllowUnknown*/ true);
5940       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
5941       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5942       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5943       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
5944         ValVT = MVT::i8;
5945       else if (ActualMVT == MVT::i16)
5946         ValVT = MVT::i16;
5947 
5948       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
5949       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
5950       assert(!Res && "Call operand has unhandled type");
5951       (void)Res;
5952     }
5953   }
5954 
5955   // Get a count of how many bytes are to be pushed on the stack.
5956   unsigned NumBytes = CCInfo.getNextStackOffset();
5957 
5958   if (IsSibCall) {
5959     // Since we're not changing the ABI to make this a tail call, the memory
5960     // operands are already available in the caller's incoming argument space.
5961     NumBytes = 0;
5962   }
5963 
5964   // FPDiff is the byte offset of the call's argument area from the callee's.
5965   // Stores to callee stack arguments will be placed in FixedStackSlots offset
5966   // by this amount for a tail call. In a sibling call it must be 0 because the
5967   // caller will deallocate the entire stack and the callee still expects its
5968   // arguments to begin at SP+0. Completely unused for non-tail calls.
5969   int FPDiff = 0;
5970 
5971   if (IsTailCall && !IsSibCall) {
5972     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
5973 
5974     // Since callee will pop argument stack as a tail call, we must keep the
5975     // popped size 16-byte aligned.
5976     NumBytes = alignTo(NumBytes, 16);
5977 
5978     // FPDiff will be negative if this tail call requires more space than we
5979     // would automatically have in our incoming argument space. Positive if we
5980     // can actually shrink the stack.
5981     FPDiff = NumReusableBytes - NumBytes;
5982 
5983     // Update the required reserved area if this is the tail call requiring the
5984     // most argument stack space.
5985     if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
5986       FuncInfo->setTailCallReservedStack(-FPDiff);
5987 
5988     // The stack pointer must be 16-byte aligned at all times it's used for a
5989     // memory operation, which in practice means at *all* times and in
5990     // particular across call boundaries. Therefore our own arguments started at
5991     // a 16-byte aligned SP and the delta applied for the tail call should
5992     // satisfy the same constraint.
5993     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
5994   }
5995 
5996   // Adjust the stack pointer for the new arguments...
5997   // These operations are automatically eliminated by the prolog/epilog pass
5998   if (!IsSibCall)
5999     Chain = DAG.getCALLSEQ_START(Chain, IsTailCall ? 0 : NumBytes, 0, DL);
6000 
6001   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
6002                                         getPointerTy(DAG.getDataLayout()));
6003 
6004   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6005   SmallSet<unsigned, 8> RegsUsed;
6006   SmallVector<SDValue, 8> MemOpChains;
6007   auto PtrVT = getPointerTy(DAG.getDataLayout());
6008 
6009   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
6010     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
6011     for (const auto &F : Forwards) {
6012       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
6013        RegsToPass.emplace_back(F.PReg, Val);
6014     }
6015   }
6016 
6017   // Walk the register/memloc assignments, inserting copies/loads.
6018   unsigned ExtraArgLocs = 0;
6019   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
6020     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
6021     SDValue Arg = OutVals[i];
6022     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6023 
6024     // Promote the value if needed.
6025     switch (VA.getLocInfo()) {
6026     default:
6027       llvm_unreachable("Unknown loc info!");
6028     case CCValAssign::Full:
6029       break;
6030     case CCValAssign::SExt:
6031       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
6032       break;
6033     case CCValAssign::ZExt:
6034       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
6035       break;
6036     case CCValAssign::AExt:
6037       if (Outs[i].ArgVT == MVT::i1) {
6038         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
6039         //
6040         // Check if we actually have to do this, because the value may
6041         // already be zero-extended.
6042         //
6043         // We cannot just emit a (zext i8 (trunc (assert-zext i8)))
6044         // and rely on DAGCombiner to fold this, because the following
6045         // (anyext i32) is combined with (zext i8) in DAG.getNode:
6046         //
6047         //   (ext (zext x)) -> (zext x)
6048         //
6049         // This will give us (zext i32), which we cannot remove, so
6050         // try to check this beforehand.
6051         if (!checkZExtBool(Arg, DAG)) {
6052           Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
6053           Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
6054         }
6055       }
6056       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
6057       break;
6058     case CCValAssign::AExtUpper:
6059       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
6060       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
6061       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
6062                         DAG.getConstant(32, DL, VA.getLocVT()));
6063       break;
6064     case CCValAssign::BCvt:
6065       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
6066       break;
6067     case CCValAssign::Trunc:
6068       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6069       break;
6070     case CCValAssign::FPExt:
6071       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
6072       break;
6073     case CCValAssign::Indirect:
6074       assert(VA.getValVT().isScalableVector() &&
6075              "Only scalable vectors can be passed indirectly");
6076 
6077       uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize();
6078       uint64_t PartSize = StoreSize;
6079       unsigned NumParts = 1;
6080       if (Outs[i].Flags.isInConsecutiveRegs()) {
6081         assert(!Outs[i].Flags.isInConsecutiveRegsLast());
6082         while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
6083           ++NumParts;
6084         StoreSize *= NumParts;
6085       }
6086 
6087       MachineFrameInfo &MFI = MF.getFrameInfo();
6088       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
6089       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
6090       int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
6091       MFI.setStackID(FI, TargetStackID::ScalableVector);
6092 
6093       MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6094       SDValue Ptr = DAG.getFrameIndex(
6095           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
6096       SDValue SpillSlot = Ptr;
6097 
6098       // Ensure we generate all stores for each tuple part, whilst updating the
6099       // pointer after each store correctly using vscale.
6100       while (NumParts) {
6101         Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
6102         NumParts--;
6103         if (NumParts > 0) {
6104           SDValue BytesIncrement = DAG.getVScale(
6105               DL, Ptr.getValueType(),
6106               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
6107           SDNodeFlags Flags;
6108           Flags.setNoUnsignedWrap(true);
6109 
6110           MPI = MachinePointerInfo(MPI.getAddrSpace());
6111           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6112                             BytesIncrement, Flags);
6113           ExtraArgLocs++;
6114           i++;
6115         }
6116       }
6117 
6118       Arg = SpillSlot;
6119       break;
6120     }
6121 
6122     if (VA.isRegLoc()) {
6123       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
6124           Outs[0].VT == MVT::i64) {
6125         assert(VA.getLocVT() == MVT::i64 &&
6126                "unexpected calling convention register assignment");
6127         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
6128                "unexpected use of 'returned'");
6129         IsThisReturn = true;
6130       }
6131       if (RegsUsed.count(VA.getLocReg())) {
6132         // If this register has already been used then we're trying to pack
6133         // parts of an [N x i32] into an X-register. The extension type will
6134         // take care of putting the two halves in the right place but we have to
6135         // combine them.
6136         SDValue &Bits =
6137             llvm::find_if(RegsToPass,
6138                           [=](const std::pair<unsigned, SDValue> &Elt) {
6139                             return Elt.first == VA.getLocReg();
6140                           })
6141                 ->second;
6142         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
6143         // Call site info is used for function's parameter entry value
6144         // tracking. For now we track only simple cases when parameter
6145         // is transferred through whole register.
6146         llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
6147           return ArgReg.Reg == VA.getLocReg();
6148         });
6149       } else {
6150         RegsToPass.emplace_back(VA.getLocReg(), Arg);
6151         RegsUsed.insert(VA.getLocReg());
6152         const TargetOptions &Options = DAG.getTarget().Options;
6153         if (Options.EmitCallSiteInfo)
6154           CSInfo.emplace_back(VA.getLocReg(), i);
6155       }
6156     } else {
6157       assert(VA.isMemLoc());
6158 
6159       SDValue DstAddr;
6160       MachinePointerInfo DstInfo;
6161 
6162       // FIXME: This works on big-endian for composite byvals, which are the
6163       // common case. It should also work for fundamental types too.
6164       uint32_t BEAlign = 0;
6165       unsigned OpSize;
6166       if (VA.getLocInfo() == CCValAssign::Indirect ||
6167           VA.getLocInfo() == CCValAssign::Trunc)
6168         OpSize = VA.getLocVT().getFixedSizeInBits();
6169       else
6170         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
6171                                  : VA.getValVT().getSizeInBits();
6172       OpSize = (OpSize + 7) / 8;
6173       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
6174           !Flags.isInConsecutiveRegs()) {
6175         if (OpSize < 8)
6176           BEAlign = 8 - OpSize;
6177       }
6178       unsigned LocMemOffset = VA.getLocMemOffset();
6179       int32_t Offset = LocMemOffset + BEAlign;
6180       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
6181       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
6182 
6183       if (IsTailCall) {
6184         Offset = Offset + FPDiff;
6185         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
6186 
6187         DstAddr = DAG.getFrameIndex(FI, PtrVT);
6188         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
6189 
6190         // Make sure any stack arguments overlapping with where we're storing
6191         // are loaded before this eventual operation. Otherwise they'll be
6192         // clobbered.
6193         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
6194       } else {
6195         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
6196 
6197         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
6198         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
6199       }
6200 
6201       if (Outs[i].Flags.isByVal()) {
6202         SDValue SizeNode =
6203             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
6204         SDValue Cpy = DAG.getMemcpy(
6205             Chain, DL, DstAddr, Arg, SizeNode,
6206             Outs[i].Flags.getNonZeroByValAlign(),
6207             /*isVol = */ false, /*AlwaysInline = */ false,
6208             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
6209 
6210         MemOpChains.push_back(Cpy);
6211       } else {
6212         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
6213         // promoted to a legal register type i32, we should truncate Arg back to
6214         // i1/i8/i16.
6215         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
6216             VA.getValVT() == MVT::i16)
6217           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
6218 
6219         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
6220         MemOpChains.push_back(Store);
6221       }
6222     }
6223   }
6224 
6225   if (!MemOpChains.empty())
6226     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
6227 
6228   // Build a sequence of copy-to-reg nodes chained together with token chain
6229   // and flag operands which copy the outgoing args into the appropriate regs.
6230   SDValue InFlag;
6231   for (auto &RegToPass : RegsToPass) {
6232     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
6233                              RegToPass.second, InFlag);
6234     InFlag = Chain.getValue(1);
6235   }
6236 
6237   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
6238   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
6239   // node so that legalize doesn't hack it.
6240   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
6241     auto GV = G->getGlobal();
6242     unsigned OpFlags =
6243         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
6244     if (OpFlags & AArch64II::MO_GOT) {
6245       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
6246       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
6247     } else {
6248       const GlobalValue *GV = G->getGlobal();
6249       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
6250     }
6251   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
6252     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6253         Subtarget->isTargetMachO()) {
6254       const char *Sym = S->getSymbol();
6255       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
6256       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
6257     } else {
6258       const char *Sym = S->getSymbol();
6259       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
6260     }
6261   }
6262 
6263   // We don't usually want to end the call-sequence here because we would tidy
6264   // the frame up *after* the call, however in the ABI-changing tail-call case
6265   // we've carefully laid out the parameters so that when sp is reset they'll be
6266   // in the correct location.
6267   if (IsTailCall && !IsSibCall) {
6268     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
6269                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
6270     InFlag = Chain.getValue(1);
6271   }
6272 
6273   std::vector<SDValue> Ops;
6274   Ops.push_back(Chain);
6275   Ops.push_back(Callee);
6276 
6277   if (IsTailCall) {
6278     // Each tail call may have to adjust the stack by a different amount, so
6279     // this information must travel along with the operation for eventual
6280     // consumption by emitEpilogue.
6281     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
6282   }
6283 
6284   // Add argument registers to the end of the list so that they are known live
6285   // into the call.
6286   for (auto &RegToPass : RegsToPass)
6287     Ops.push_back(DAG.getRegister(RegToPass.first,
6288                                   RegToPass.second.getValueType()));
6289 
6290   // Add a register mask operand representing the call-preserved registers.
6291   const uint32_t *Mask;
6292   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6293   if (IsThisReturn) {
6294     // For 'this' returns, use the X0-preserving mask if applicable
6295     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
6296     if (!Mask) {
6297       IsThisReturn = false;
6298       Mask = TRI->getCallPreservedMask(MF, CallConv);
6299     }
6300   } else
6301     Mask = TRI->getCallPreservedMask(MF, CallConv);
6302 
6303   if (Subtarget->hasCustomCallingConv())
6304     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
6305 
6306   if (TRI->isAnyArgRegReserved(MF))
6307     TRI->emitReservedArgRegCallError(MF);
6308 
6309   assert(Mask && "Missing call preserved mask for calling convention");
6310   Ops.push_back(DAG.getRegisterMask(Mask));
6311 
6312   if (InFlag.getNode())
6313     Ops.push_back(InFlag);
6314 
6315   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6316 
6317   // If we're doing a tall call, use a TC_RETURN here rather than an
6318   // actual call instruction.
6319   if (IsTailCall) {
6320     MF.getFrameInfo().setHasTailCall();
6321     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
6322     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
6323     return Ret;
6324   }
6325 
6326   unsigned CallOpc = AArch64ISD::CALL;
6327   // Calls with operand bundle "clang.arc.attachedcall" are special. They should
6328   // be expanded to the call, directly followed by a special marker sequence.
6329   // Use the CALL_RVMARKER to do that.
6330   if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
6331     assert(!IsTailCall &&
6332            "tail calls cannot be marked with clang.arc.attachedcall");
6333     CallOpc = AArch64ISD::CALL_RVMARKER;
6334   }
6335 
6336   // Returns a chain and a flag for retval copy to use.
6337   Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
6338   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
6339   InFlag = Chain.getValue(1);
6340   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
6341 
6342   uint64_t CalleePopBytes =
6343       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
6344 
6345   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
6346                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
6347                              InFlag, DL);
6348   if (!Ins.empty())
6349     InFlag = Chain.getValue(1);
6350 
6351   // Handle result values, copying them out of physregs into vregs that we
6352   // return.
6353   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
6354                          InVals, IsThisReturn,
6355                          IsThisReturn ? OutVals[0] : SDValue());
6356 }
6357 
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const6358 bool AArch64TargetLowering::CanLowerReturn(
6359     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
6360     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
6361   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
6362   SmallVector<CCValAssign, 16> RVLocs;
6363   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6364   return CCInfo.CheckReturn(Outs, RetCC);
6365 }
6366 
6367 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const6368 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6369                                    bool isVarArg,
6370                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
6371                                    const SmallVectorImpl<SDValue> &OutVals,
6372                                    const SDLoc &DL, SelectionDAG &DAG) const {
6373   auto &MF = DAG.getMachineFunction();
6374   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6375 
6376   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
6377   SmallVector<CCValAssign, 16> RVLocs;
6378   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
6379   CCInfo.AnalyzeReturn(Outs, RetCC);
6380 
6381   // Copy the result values into the output registers.
6382   SDValue Flag;
6383   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
6384   SmallSet<unsigned, 4> RegsUsed;
6385   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
6386        ++i, ++realRVLocIdx) {
6387     CCValAssign &VA = RVLocs[i];
6388     assert(VA.isRegLoc() && "Can only return in registers!");
6389     SDValue Arg = OutVals[realRVLocIdx];
6390 
6391     switch (VA.getLocInfo()) {
6392     default:
6393       llvm_unreachable("Unknown loc info!");
6394     case CCValAssign::Full:
6395       if (Outs[i].ArgVT == MVT::i1) {
6396         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
6397         // value. This is strictly redundant on Darwin (which uses "zeroext
6398         // i1"), but will be optimised out before ISel.
6399         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
6400         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
6401       }
6402       break;
6403     case CCValAssign::BCvt:
6404       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
6405       break;
6406     case CCValAssign::AExt:
6407     case CCValAssign::ZExt:
6408       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6409       break;
6410     case CCValAssign::AExtUpper:
6411       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
6412       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6413       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
6414                         DAG.getConstant(32, DL, VA.getLocVT()));
6415       break;
6416     }
6417 
6418     if (RegsUsed.count(VA.getLocReg())) {
6419       SDValue &Bits =
6420           llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
6421             return Elt.first == VA.getLocReg();
6422           })->second;
6423       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
6424     } else {
6425       RetVals.emplace_back(VA.getLocReg(), Arg);
6426       RegsUsed.insert(VA.getLocReg());
6427     }
6428   }
6429 
6430   SmallVector<SDValue, 4> RetOps(1, Chain);
6431   for (auto &RetVal : RetVals) {
6432     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
6433     Flag = Chain.getValue(1);
6434     RetOps.push_back(
6435         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
6436   }
6437 
6438   // Windows AArch64 ABIs require that for returning structs by value we copy
6439   // the sret argument into X0 for the return.
6440   // We saved the argument into a virtual register in the entry block,
6441   // so now we copy the value out and into X0.
6442   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
6443     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
6444                                      getPointerTy(MF.getDataLayout()));
6445 
6446     unsigned RetValReg = AArch64::X0;
6447     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
6448     Flag = Chain.getValue(1);
6449 
6450     RetOps.push_back(
6451       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
6452   }
6453 
6454   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6455   const MCPhysReg *I = TRI->getCalleeSavedRegsViaCopy(&MF);
6456   if (I) {
6457     for (; *I; ++I) {
6458       if (AArch64::GPR64RegClass.contains(*I))
6459         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6460       else if (AArch64::FPR64RegClass.contains(*I))
6461         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6462       else
6463         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6464     }
6465   }
6466 
6467   RetOps[0] = Chain; // Update chain.
6468 
6469   // Add the flag if we have it.
6470   if (Flag.getNode())
6471     RetOps.push_back(Flag);
6472 
6473   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
6474 }
6475 
6476 //===----------------------------------------------------------------------===//
6477 //  Other Lowering Code
6478 //===----------------------------------------------------------------------===//
6479 
getTargetNode(GlobalAddressSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const6480 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
6481                                              SelectionDAG &DAG,
6482                                              unsigned Flag) const {
6483   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
6484                                     N->getOffset(), Flag);
6485 }
6486 
getTargetNode(JumpTableSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const6487 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
6488                                              SelectionDAG &DAG,
6489                                              unsigned Flag) const {
6490   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
6491 }
6492 
getTargetNode(ConstantPoolSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const6493 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
6494                                              SelectionDAG &DAG,
6495                                              unsigned Flag) const {
6496   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
6497                                    N->getOffset(), Flag);
6498 }
6499 
getTargetNode(BlockAddressSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const6500 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
6501                                              SelectionDAG &DAG,
6502                                              unsigned Flag) const {
6503   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
6504 }
6505 
6506 // (loadGOT sym)
6507 template <class NodeTy>
getGOT(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const6508 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
6509                                       unsigned Flags) const {
6510   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
6511   SDLoc DL(N);
6512   EVT Ty = getPointerTy(DAG.getDataLayout());
6513   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
6514   // FIXME: Once remat is capable of dealing with instructions with register
6515   // operands, expand this into two nodes instead of using a wrapper node.
6516   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
6517 }
6518 
6519 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
6520 template <class NodeTy>
getAddrLarge(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const6521 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
6522                                             unsigned Flags) const {
6523   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
6524   SDLoc DL(N);
6525   EVT Ty = getPointerTy(DAG.getDataLayout());
6526   const unsigned char MO_NC = AArch64II::MO_NC;
6527   return DAG.getNode(
6528       AArch64ISD::WrapperLarge, DL, Ty,
6529       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
6530       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
6531       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
6532       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
6533 }
6534 
6535 // (addlow (adrp %hi(sym)) %lo(sym))
6536 template <class NodeTy>
getAddr(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const6537 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
6538                                        unsigned Flags) const {
6539   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
6540   SDLoc DL(N);
6541   EVT Ty = getPointerTy(DAG.getDataLayout());
6542   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
6543   SDValue Lo = getTargetNode(N, Ty, DAG,
6544                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
6545   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
6546   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
6547 }
6548 
6549 // (adr sym)
6550 template <class NodeTy>
getAddrTiny(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const6551 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
6552                                            unsigned Flags) const {
6553   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
6554   SDLoc DL(N);
6555   EVT Ty = getPointerTy(DAG.getDataLayout());
6556   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
6557   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
6558 }
6559 
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const6560 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
6561                                                   SelectionDAG &DAG) const {
6562   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
6563   const GlobalValue *GV = GN->getGlobal();
6564   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6565 
6566   if (OpFlags != AArch64II::MO_NO_FLAG)
6567     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
6568            "unexpected offset in global node");
6569 
6570   // This also catches the large code model case for Darwin, and tiny code
6571   // model with got relocations.
6572   if ((OpFlags & AArch64II::MO_GOT) != 0) {
6573     return getGOT(GN, DAG, OpFlags);
6574   }
6575 
6576   SDValue Result;
6577   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6578     Result = getAddrLarge(GN, DAG, OpFlags);
6579   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6580     Result = getAddrTiny(GN, DAG, OpFlags);
6581   } else {
6582     Result = getAddr(GN, DAG, OpFlags);
6583   }
6584   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6585   SDLoc DL(GN);
6586   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
6587     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
6588                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
6589   return Result;
6590 }
6591 
6592 /// Convert a TLS address reference into the correct sequence of loads
6593 /// and calls to compute the variable's address (for Darwin, currently) and
6594 /// return an SDValue containing the final node.
6595 
6596 /// Darwin only has one TLS scheme which must be capable of dealing with the
6597 /// fully general situation, in the worst case. This means:
6598 ///     + "extern __thread" declaration.
6599 ///     + Defined in a possibly unknown dynamic library.
6600 ///
6601 /// The general system is that each __thread variable has a [3 x i64] descriptor
6602 /// which contains information used by the runtime to calculate the address. The
6603 /// only part of this the compiler needs to know about is the first xword, which
6604 /// contains a function pointer that must be called with the address of the
6605 /// entire descriptor in "x0".
6606 ///
6607 /// Since this descriptor may be in a different unit, in general even the
6608 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
6609 /// is:
6610 ///     adrp x0, _var@TLVPPAGE
6611 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
6612 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
6613 ///                                      ; the function pointer
6614 ///     blr x1                           ; Uses descriptor address in x0
6615 ///     ; Address of _var is now in x0.
6616 ///
6617 /// If the address of _var's descriptor *is* known to the linker, then it can
6618 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
6619 /// a slight efficiency gain.
6620 SDValue
LowerDarwinGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const6621 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
6622                                                    SelectionDAG &DAG) const {
6623   assert(Subtarget->isTargetDarwin() &&
6624          "This function expects a Darwin target");
6625 
6626   SDLoc DL(Op);
6627   MVT PtrVT = getPointerTy(DAG.getDataLayout());
6628   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6629   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6630 
6631   SDValue TLVPAddr =
6632       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6633   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
6634 
6635   // The first entry in the descriptor is a function pointer that we must call
6636   // to obtain the address of the variable.
6637   SDValue Chain = DAG.getEntryNode();
6638   SDValue FuncTLVGet = DAG.getLoad(
6639       PtrMemVT, DL, Chain, DescAddr,
6640       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
6641       Align(PtrMemVT.getSizeInBits() / 8),
6642       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6643   Chain = FuncTLVGet.getValue(1);
6644 
6645   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
6646   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
6647 
6648   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6649   MFI.setAdjustsStack(true);
6650 
6651   // TLS calls preserve all registers except those that absolutely must be
6652   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
6653   // silly).
6654   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6655   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
6656   if (Subtarget->hasCustomCallingConv())
6657     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
6658 
6659   // Finally, we can make the call. This is just a degenerate version of a
6660   // normal AArch64 call node: x0 takes the address of the descriptor, and
6661   // returns the address of the variable in this thread.
6662   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
6663   Chain =
6664       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
6665                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
6666                   DAG.getRegisterMask(Mask), Chain.getValue(1));
6667   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
6668 }
6669 
6670 /// Convert a thread-local variable reference into a sequence of instructions to
6671 /// compute the variable's address for the local exec TLS model of ELF targets.
6672 /// The sequence depends on the maximum TLS area size.
LowerELFTLSLocalExec(const GlobalValue * GV,SDValue ThreadBase,const SDLoc & DL,SelectionDAG & DAG) const6673 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
6674                                                     SDValue ThreadBase,
6675                                                     const SDLoc &DL,
6676                                                     SelectionDAG &DAG) const {
6677   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6678   SDValue TPOff, Addr;
6679 
6680   switch (DAG.getTarget().Options.TLSSize) {
6681   default:
6682     llvm_unreachable("Unexpected TLS size");
6683 
6684   case 12: {
6685     // mrs   x0, TPIDR_EL0
6686     // add   x0, x0, :tprel_lo12:a
6687     SDValue Var = DAG.getTargetGlobalAddress(
6688         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
6689     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6690                                       Var,
6691                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6692                    0);
6693   }
6694 
6695   case 24: {
6696     // mrs   x0, TPIDR_EL0
6697     // add   x0, x0, :tprel_hi12:a
6698     // add   x0, x0, :tprel_lo12_nc:a
6699     SDValue HiVar = DAG.getTargetGlobalAddress(
6700         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6701     SDValue LoVar = DAG.getTargetGlobalAddress(
6702         GV, DL, PtrVT, 0,
6703         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6704     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6705                                       HiVar,
6706                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6707                    0);
6708     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
6709                                       LoVar,
6710                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6711                    0);
6712   }
6713 
6714   case 32: {
6715     // mrs   x1, TPIDR_EL0
6716     // movz  x0, #:tprel_g1:a
6717     // movk  x0, #:tprel_g0_nc:a
6718     // add   x0, x1, x0
6719     SDValue HiVar = DAG.getTargetGlobalAddress(
6720         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
6721     SDValue LoVar = DAG.getTargetGlobalAddress(
6722         GV, DL, PtrVT, 0,
6723         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6724     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6725                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6726                     0);
6727     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6728                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6729                     0);
6730     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6731   }
6732 
6733   case 48: {
6734     // mrs   x1, TPIDR_EL0
6735     // movz  x0, #:tprel_g2:a
6736     // movk  x0, #:tprel_g1_nc:a
6737     // movk  x0, #:tprel_g0_nc:a
6738     // add   x0, x1, x0
6739     SDValue HiVar = DAG.getTargetGlobalAddress(
6740         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
6741     SDValue MiVar = DAG.getTargetGlobalAddress(
6742         GV, DL, PtrVT, 0,
6743         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
6744     SDValue LoVar = DAG.getTargetGlobalAddress(
6745         GV, DL, PtrVT, 0,
6746         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6747     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6748                                        DAG.getTargetConstant(32, DL, MVT::i32)),
6749                     0);
6750     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
6751                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6752                     0);
6753     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6754                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6755                     0);
6756     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6757   }
6758   }
6759 }
6760 
6761 /// When accessing thread-local variables under either the general-dynamic or
6762 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
6763 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
6764 /// is a function pointer to carry out the resolution.
6765 ///
6766 /// The sequence is:
6767 ///    adrp  x0, :tlsdesc:var
6768 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
6769 ///    add   x0, x0, #:tlsdesc_lo12:var
6770 ///    .tlsdesccall var
6771 ///    blr   x1
6772 ///    (TPIDR_EL0 offset now in x0)
6773 ///
6774 ///  The above sequence must be produced unscheduled, to enable the linker to
6775 ///  optimize/relax this sequence.
6776 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
6777 ///  above sequence, and expanded really late in the compilation flow, to ensure
6778 ///  the sequence is produced as per above.
LowerELFTLSDescCallSeq(SDValue SymAddr,const SDLoc & DL,SelectionDAG & DAG) const6779 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
6780                                                       const SDLoc &DL,
6781                                                       SelectionDAG &DAG) const {
6782   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6783 
6784   SDValue Chain = DAG.getEntryNode();
6785   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6786 
6787   Chain =
6788       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
6789   SDValue Glue = Chain.getValue(1);
6790 
6791   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
6792 }
6793 
6794 SDValue
LowerELFGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const6795 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
6796                                                 SelectionDAG &DAG) const {
6797   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
6798 
6799   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6800 
6801   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
6802 
6803   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
6804     if (Model == TLSModel::LocalDynamic)
6805       Model = TLSModel::GeneralDynamic;
6806   }
6807 
6808   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6809       Model != TLSModel::LocalExec)
6810     report_fatal_error("ELF TLS only supported in small memory model or "
6811                        "in local exec TLS model");
6812   // Different choices can be made for the maximum size of the TLS area for a
6813   // module. For the small address model, the default TLS size is 16MiB and the
6814   // maximum TLS size is 4GiB.
6815   // FIXME: add tiny and large code model support for TLS access models other
6816   // than local exec. We currently generate the same code as small for tiny,
6817   // which may be larger than needed.
6818 
6819   SDValue TPOff;
6820   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6821   SDLoc DL(Op);
6822   const GlobalValue *GV = GA->getGlobal();
6823 
6824   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
6825 
6826   if (Model == TLSModel::LocalExec) {
6827     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
6828   } else if (Model == TLSModel::InitialExec) {
6829     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6830     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
6831   } else if (Model == TLSModel::LocalDynamic) {
6832     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
6833     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
6834     // the beginning of the module's TLS region, followed by a DTPREL offset
6835     // calculation.
6836 
6837     // These accesses will need deduplicating if there's more than one.
6838     AArch64FunctionInfo *MFI =
6839         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6840     MFI->incNumLocalDynamicTLSAccesses();
6841 
6842     // The call needs a relocation too for linker relaxation. It doesn't make
6843     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
6844     // the address.
6845     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
6846                                                   AArch64II::MO_TLS);
6847 
6848     // Now we can calculate the offset from TPIDR_EL0 to this module's
6849     // thread-local area.
6850     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
6851 
6852     // Now use :dtprel_whatever: operations to calculate this variable's offset
6853     // in its thread-storage area.
6854     SDValue HiVar = DAG.getTargetGlobalAddress(
6855         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6856     SDValue LoVar = DAG.getTargetGlobalAddress(
6857         GV, DL, MVT::i64, 0,
6858         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6859 
6860     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
6861                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6862                     0);
6863     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
6864                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6865                     0);
6866   } else if (Model == TLSModel::GeneralDynamic) {
6867     // The call needs a relocation too for linker relaxation. It doesn't make
6868     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
6869     // the address.
6870     SDValue SymAddr =
6871         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6872 
6873     // Finally we can make a call to calculate the offset from tpidr_el0.
6874     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
6875   } else
6876     llvm_unreachable("Unsupported ELF TLS access model");
6877 
6878   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6879 }
6880 
6881 SDValue
LowerWindowsGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const6882 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
6883                                                     SelectionDAG &DAG) const {
6884   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
6885 
6886   SDValue Chain = DAG.getEntryNode();
6887   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6888   SDLoc DL(Op);
6889 
6890   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
6891 
6892   // Load the ThreadLocalStoragePointer from the TEB
6893   // A pointer to the TLS array is located at offset 0x58 from the TEB.
6894   SDValue TLSArray =
6895       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
6896   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
6897   Chain = TLSArray.getValue(1);
6898 
6899   // Load the TLS index from the C runtime;
6900   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
6901   // This also does the same as LOADgot, but using a generic i32 load,
6902   // while LOADgot only loads i64.
6903   SDValue TLSIndexHi =
6904       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
6905   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
6906       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6907   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
6908   SDValue TLSIndex =
6909       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
6910   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
6911   Chain = TLSIndex.getValue(1);
6912 
6913   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
6914   // offset into the TLSArray.
6915   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
6916   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
6917                              DAG.getConstant(3, DL, PtrVT));
6918   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
6919                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
6920                             MachinePointerInfo());
6921   Chain = TLS.getValue(1);
6922 
6923   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6924   const GlobalValue *GV = GA->getGlobal();
6925   SDValue TGAHi = DAG.getTargetGlobalAddress(
6926       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6927   SDValue TGALo = DAG.getTargetGlobalAddress(
6928       GV, DL, PtrVT, 0,
6929       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6930 
6931   // Add the offset from the start of the .tls section (section base).
6932   SDValue Addr =
6933       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
6934                                  DAG.getTargetConstant(0, DL, MVT::i32)),
6935               0);
6936   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
6937   return Addr;
6938 }
6939 
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const6940 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
6941                                                      SelectionDAG &DAG) const {
6942   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6943   if (DAG.getTarget().useEmulatedTLS())
6944     return LowerToTLSEmulatedModel(GA, DAG);
6945 
6946   if (Subtarget->isTargetDarwin())
6947     return LowerDarwinGlobalTLSAddress(Op, DAG);
6948   if (Subtarget->isTargetELF())
6949     return LowerELFGlobalTLSAddress(Op, DAG);
6950   if (Subtarget->isTargetWindows())
6951     return LowerWindowsGlobalTLSAddress(Op, DAG);
6952 
6953   llvm_unreachable("Unexpected platform trying to use TLS");
6954 }
6955 
6956 // Looks through \param Val to determine the bit that can be used to
6957 // check the sign of the value. It returns the unextended value and
6958 // the sign bit position.
lookThroughSignExtension(SDValue Val)6959 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
6960   if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
6961     return {Val.getOperand(0),
6962             cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
6963                 1};
6964 
6965   if (Val.getOpcode() == ISD::SIGN_EXTEND)
6966     return {Val.getOperand(0),
6967             Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
6968 
6969   return {Val, Val.getValueSizeInBits() - 1};
6970 }
6971 
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const6972 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
6973   SDValue Chain = Op.getOperand(0);
6974   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
6975   SDValue LHS = Op.getOperand(2);
6976   SDValue RHS = Op.getOperand(3);
6977   SDValue Dest = Op.getOperand(4);
6978   SDLoc dl(Op);
6979 
6980   MachineFunction &MF = DAG.getMachineFunction();
6981   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
6982   // will not be produced, as they are conditional branch instructions that do
6983   // not set flags.
6984   bool ProduceNonFlagSettingCondBr =
6985       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
6986 
6987   // Handle f128 first, since lowering it will result in comparing the return
6988   // value of a libcall against zero, which is just what the rest of LowerBR_CC
6989   // is expecting to deal with.
6990   if (LHS.getValueType() == MVT::f128) {
6991     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
6992 
6993     // If softenSetCCOperands returned a scalar, we need to compare the result
6994     // against zero to select between true and false values.
6995     if (!RHS.getNode()) {
6996       RHS = DAG.getConstant(0, dl, LHS.getValueType());
6997       CC = ISD::SETNE;
6998     }
6999   }
7000 
7001   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
7002   // instruction.
7003   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
7004       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7005     // Only lower legal XALUO ops.
7006     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
7007       return SDValue();
7008 
7009     // The actual operation with overflow check.
7010     AArch64CC::CondCode OFCC;
7011     SDValue Value, Overflow;
7012     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
7013 
7014     if (CC == ISD::SETNE)
7015       OFCC = getInvertedCondCode(OFCC);
7016     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
7017 
7018     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
7019                        Overflow);
7020   }
7021 
7022   if (LHS.getValueType().isInteger()) {
7023     assert((LHS.getValueType() == RHS.getValueType()) &&
7024            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
7025 
7026     // If the RHS of the comparison is zero, we can potentially fold this
7027     // to a specialized branch.
7028     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
7029     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
7030       if (CC == ISD::SETEQ) {
7031         // See if we can use a TBZ to fold in an AND as well.
7032         // TBZ has a smaller branch displacement than CBZ.  If the offset is
7033         // out of bounds, a late MI-layer pass rewrites branches.
7034         // 403.gcc is an example that hits this case.
7035         if (LHS.getOpcode() == ISD::AND &&
7036             isa<ConstantSDNode>(LHS.getOperand(1)) &&
7037             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
7038           SDValue Test = LHS.getOperand(0);
7039           uint64_t Mask = LHS.getConstantOperandVal(1);
7040           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
7041                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
7042                              Dest);
7043         }
7044 
7045         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
7046       } else if (CC == ISD::SETNE) {
7047         // See if we can use a TBZ to fold in an AND as well.
7048         // TBZ has a smaller branch displacement than CBZ.  If the offset is
7049         // out of bounds, a late MI-layer pass rewrites branches.
7050         // 403.gcc is an example that hits this case.
7051         if (LHS.getOpcode() == ISD::AND &&
7052             isa<ConstantSDNode>(LHS.getOperand(1)) &&
7053             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
7054           SDValue Test = LHS.getOperand(0);
7055           uint64_t Mask = LHS.getConstantOperandVal(1);
7056           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
7057                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
7058                              Dest);
7059         }
7060 
7061         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
7062       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
7063         // Don't combine AND since emitComparison converts the AND to an ANDS
7064         // (a.k.a. TST) and the test in the test bit and branch instruction
7065         // becomes redundant.  This would also increase register pressure.
7066         uint64_t SignBitPos;
7067         std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
7068         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
7069                            DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
7070       }
7071     }
7072     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
7073         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
7074       // Don't combine AND since emitComparison converts the AND to an ANDS
7075       // (a.k.a. TST) and the test in the test bit and branch instruction
7076       // becomes redundant.  This would also increase register pressure.
7077       uint64_t SignBitPos;
7078       std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
7079       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
7080                          DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
7081     }
7082 
7083     SDValue CCVal;
7084     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
7085     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
7086                        Cmp);
7087   }
7088 
7089   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
7090          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
7091 
7092   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7093   // clean.  Some of them require two branches to implement.
7094   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7095   AArch64CC::CondCode CC1, CC2;
7096   changeFPCCToAArch64CC(CC, CC1, CC2);
7097   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7098   SDValue BR1 =
7099       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
7100   if (CC2 != AArch64CC::AL) {
7101     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7102     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
7103                        Cmp);
7104   }
7105 
7106   return BR1;
7107 }
7108 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const7109 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
7110                                               SelectionDAG &DAG) const {
7111   EVT VT = Op.getValueType();
7112   SDLoc DL(Op);
7113 
7114   SDValue In1 = Op.getOperand(0);
7115   SDValue In2 = Op.getOperand(1);
7116   EVT SrcVT = In2.getValueType();
7117 
7118   if (VT.isScalableVector()) {
7119     if (VT != SrcVT)
7120       return SDValue();
7121 
7122     // copysign(x,y) -> (y & SIGN_MASK) | (x & ~SIGN_MASK)
7123     //
7124     // A possible alternative sequence involves using FNEG_MERGE_PASSTHRU;
7125     // maybe useful for copysign operations with mismatched VTs.
7126     //
7127     // IntVT here is chosen so it's a legal type with the same element width
7128     // as the input.
7129     EVT IntVT =
7130         getPackedSVEVectorVT(VT.getVectorElementType().changeTypeToInteger());
7131     unsigned NumBits = VT.getScalarSizeInBits();
7132     SDValue SignMask = DAG.getConstant(APInt::getSignMask(NumBits), DL, IntVT);
7133     SDValue InvSignMask = DAG.getNOT(DL, SignMask, IntVT);
7134     SDValue Sign = DAG.getNode(ISD::AND, DL, IntVT, SignMask,
7135                                getSVESafeBitCast(IntVT, In2, DAG));
7136     SDValue Magnitude = DAG.getNode(ISD::AND, DL, IntVT, InvSignMask,
7137                                     getSVESafeBitCast(IntVT, In1, DAG));
7138     SDValue IntResult = DAG.getNode(ISD::OR, DL, IntVT, Sign, Magnitude);
7139     return getSVESafeBitCast(VT, IntResult, DAG);
7140   }
7141 
7142   if (SrcVT.bitsLT(VT))
7143     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
7144   else if (SrcVT.bitsGT(VT))
7145     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
7146 
7147   EVT VecVT;
7148   uint64_t EltMask;
7149   SDValue VecVal1, VecVal2;
7150 
7151   auto setVecVal = [&] (int Idx) {
7152     if (!VT.isVector()) {
7153       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
7154                                           DAG.getUNDEF(VecVT), In1);
7155       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
7156                                           DAG.getUNDEF(VecVT), In2);
7157     } else {
7158       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
7159       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
7160     }
7161   };
7162 
7163   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
7164     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
7165     EltMask = 0x80000000ULL;
7166     setVecVal(AArch64::ssub);
7167   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
7168     VecVT = MVT::v2i64;
7169 
7170     // We want to materialize a mask with the high bit set, but the AdvSIMD
7171     // immediate moves cannot materialize that in a single instruction for
7172     // 64-bit elements. Instead, materialize zero and then negate it.
7173     EltMask = 0;
7174 
7175     setVecVal(AArch64::dsub);
7176   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
7177     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
7178     EltMask = 0x8000ULL;
7179     setVecVal(AArch64::hsub);
7180   } else {
7181     llvm_unreachable("Invalid type for copysign!");
7182   }
7183 
7184   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
7185 
7186   // If we couldn't materialize the mask above, then the mask vector will be
7187   // the zero vector, and we need to negate it here.
7188   if (VT == MVT::f64 || VT == MVT::v2f64) {
7189     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
7190     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
7191     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
7192   }
7193 
7194   SDValue Sel =
7195       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
7196 
7197   if (VT == MVT::f16)
7198     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
7199   if (VT == MVT::f32)
7200     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
7201   else if (VT == MVT::f64)
7202     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
7203   else
7204     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
7205 }
7206 
LowerCTPOP(SDValue Op,SelectionDAG & DAG) const7207 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
7208   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7209           Attribute::NoImplicitFloat))
7210     return SDValue();
7211 
7212   if (!Subtarget->hasNEON())
7213     return SDValue();
7214 
7215   // While there is no integer popcount instruction, it can
7216   // be more efficiently lowered to the following sequence that uses
7217   // AdvSIMD registers/instructions as long as the copies to/from
7218   // the AdvSIMD registers are cheap.
7219   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
7220   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
7221   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
7222   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
7223   SDValue Val = Op.getOperand(0);
7224   SDLoc DL(Op);
7225   EVT VT = Op.getValueType();
7226 
7227   if (VT == MVT::i32 || VT == MVT::i64) {
7228     if (VT == MVT::i32)
7229       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
7230     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
7231 
7232     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
7233     SDValue UaddLV = DAG.getNode(
7234         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
7235         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
7236 
7237     if (VT == MVT::i64)
7238       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
7239     return UaddLV;
7240   } else if (VT == MVT::i128) {
7241     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
7242 
7243     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
7244     SDValue UaddLV = DAG.getNode(
7245         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
7246         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
7247 
7248     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
7249   }
7250 
7251   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
7252     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
7253 
7254   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
7255           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
7256          "Unexpected type for custom ctpop lowering");
7257 
7258   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
7259   Val = DAG.getBitcast(VT8Bit, Val);
7260   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
7261 
7262   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
7263   unsigned EltSize = 8;
7264   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
7265   while (EltSize != VT.getScalarSizeInBits()) {
7266     EltSize *= 2;
7267     NumElts /= 2;
7268     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
7269     Val = DAG.getNode(
7270         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
7271         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
7272   }
7273 
7274   return Val;
7275 }
7276 
LowerCTTZ(SDValue Op,SelectionDAG & DAG) const7277 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7278   EVT VT = Op.getValueType();
7279   assert(VT.isScalableVector() ||
7280          useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true));
7281 
7282   SDLoc DL(Op);
7283   SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
7284   return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
7285 }
7286 
LowerMinMax(SDValue Op,SelectionDAG & DAG) const7287 SDValue AArch64TargetLowering::LowerMinMax(SDValue Op,
7288                                            SelectionDAG &DAG) const {
7289 
7290   EVT VT = Op.getValueType();
7291   SDLoc DL(Op);
7292   unsigned Opcode = Op.getOpcode();
7293   ISD::CondCode CC;
7294   switch (Opcode) {
7295   default:
7296     llvm_unreachable("Wrong instruction");
7297   case ISD::SMAX:
7298     CC = ISD::SETGT;
7299     break;
7300   case ISD::SMIN:
7301     CC = ISD::SETLT;
7302     break;
7303   case ISD::UMAX:
7304     CC = ISD::SETUGT;
7305     break;
7306   case ISD::UMIN:
7307     CC = ISD::SETULT;
7308     break;
7309   }
7310 
7311   if (VT.isScalableVector() ||
7312       useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) {
7313     switch (Opcode) {
7314     default:
7315       llvm_unreachable("Wrong instruction");
7316     case ISD::SMAX:
7317       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
7318                                  /*OverrideNEON=*/true);
7319     case ISD::SMIN:
7320       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
7321                                  /*OverrideNEON=*/true);
7322     case ISD::UMAX:
7323       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
7324                                  /*OverrideNEON=*/true);
7325     case ISD::UMIN:
7326       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
7327                                  /*OverrideNEON=*/true);
7328     }
7329   }
7330 
7331   SDValue Op0 = Op.getOperand(0);
7332   SDValue Op1 = Op.getOperand(1);
7333   SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC);
7334   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
7335 }
7336 
LowerBitreverse(SDValue Op,SelectionDAG & DAG) const7337 SDValue AArch64TargetLowering::LowerBitreverse(SDValue Op,
7338                                                SelectionDAG &DAG) const {
7339   EVT VT = Op.getValueType();
7340 
7341   if (VT.isScalableVector() ||
7342       useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
7343     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU,
7344                                true);
7345 
7346   SDLoc DL(Op);
7347   SDValue REVB;
7348   MVT VST;
7349 
7350   switch (VT.getSimpleVT().SimpleTy) {
7351   default:
7352     llvm_unreachable("Invalid type for bitreverse!");
7353 
7354   case MVT::v2i32: {
7355     VST = MVT::v8i8;
7356     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
7357 
7358     break;
7359   }
7360 
7361   case MVT::v4i32: {
7362     VST = MVT::v16i8;
7363     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
7364 
7365     break;
7366   }
7367 
7368   case MVT::v1i64: {
7369     VST = MVT::v8i8;
7370     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
7371 
7372     break;
7373   }
7374 
7375   case MVT::v2i64: {
7376     VST = MVT::v16i8;
7377     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
7378 
7379     break;
7380   }
7381   }
7382 
7383   return DAG.getNode(AArch64ISD::NVCAST, DL, VT,
7384                      DAG.getNode(ISD::BITREVERSE, DL, VST, REVB));
7385 }
7386 
LowerSETCC(SDValue Op,SelectionDAG & DAG) const7387 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7388 
7389   if (Op.getValueType().isVector())
7390     return LowerVSETCC(Op, DAG);
7391 
7392   bool IsStrict = Op->isStrictFPOpcode();
7393   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
7394   unsigned OpNo = IsStrict ? 1 : 0;
7395   SDValue Chain;
7396   if (IsStrict)
7397     Chain = Op.getOperand(0);
7398   SDValue LHS = Op.getOperand(OpNo + 0);
7399   SDValue RHS = Op.getOperand(OpNo + 1);
7400   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
7401   SDLoc dl(Op);
7402 
7403   // We chose ZeroOrOneBooleanContents, so use zero and one.
7404   EVT VT = Op.getValueType();
7405   SDValue TVal = DAG.getConstant(1, dl, VT);
7406   SDValue FVal = DAG.getConstant(0, dl, VT);
7407 
7408   // Handle f128 first, since one possible outcome is a normal integer
7409   // comparison which gets picked up by the next if statement.
7410   if (LHS.getValueType() == MVT::f128) {
7411     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
7412                         IsSignaling);
7413 
7414     // If softenSetCCOperands returned a scalar, use it.
7415     if (!RHS.getNode()) {
7416       assert(LHS.getValueType() == Op.getValueType() &&
7417              "Unexpected setcc expansion!");
7418       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
7419     }
7420   }
7421 
7422   if (LHS.getValueType().isInteger()) {
7423     SDValue CCVal;
7424     SDValue Cmp = getAArch64Cmp(
7425         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
7426 
7427     // Note that we inverted the condition above, so we reverse the order of
7428     // the true and false operands here.  This will allow the setcc to be
7429     // matched to a single CSINC instruction.
7430     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
7431     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
7432   }
7433 
7434   // Now we know we're dealing with FP values.
7435   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
7436          LHS.getValueType() == MVT::f64);
7437 
7438   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
7439   // and do the comparison.
7440   SDValue Cmp;
7441   if (IsStrict)
7442     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
7443   else
7444     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7445 
7446   AArch64CC::CondCode CC1, CC2;
7447   changeFPCCToAArch64CC(CC, CC1, CC2);
7448   SDValue Res;
7449   if (CC2 == AArch64CC::AL) {
7450     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
7451                           CC2);
7452     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7453 
7454     // Note that we inverted the condition above, so we reverse the order of
7455     // the true and false operands here.  This will allow the setcc to be
7456     // matched to a single CSINC instruction.
7457     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
7458   } else {
7459     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
7460     // totally clean.  Some of them require two CSELs to implement.  As is in
7461     // this case, we emit the first CSEL and then emit a second using the output
7462     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
7463 
7464     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
7465     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7466     SDValue CS1 =
7467         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
7468 
7469     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7470     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
7471   }
7472   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
7473 }
7474 
LowerSELECT_CC(ISD::CondCode CC,SDValue LHS,SDValue RHS,SDValue TVal,SDValue FVal,const SDLoc & dl,SelectionDAG & DAG) const7475 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
7476                                               SDValue RHS, SDValue TVal,
7477                                               SDValue FVal, const SDLoc &dl,
7478                                               SelectionDAG &DAG) const {
7479   // Handle f128 first, because it will result in a comparison of some RTLIB
7480   // call result against zero.
7481   if (LHS.getValueType() == MVT::f128) {
7482     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
7483 
7484     // If softenSetCCOperands returned a scalar, we need to compare the result
7485     // against zero to select between true and false values.
7486     if (!RHS.getNode()) {
7487       RHS = DAG.getConstant(0, dl, LHS.getValueType());
7488       CC = ISD::SETNE;
7489     }
7490   }
7491 
7492   // Also handle f16, for which we need to do a f32 comparison.
7493   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
7494     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
7495     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
7496   }
7497 
7498   // Next, handle integers.
7499   if (LHS.getValueType().isInteger()) {
7500     assert((LHS.getValueType() == RHS.getValueType()) &&
7501            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
7502 
7503     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
7504     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
7505     ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
7506     // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
7507     // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
7508     // supported types.
7509     if (CC == ISD::SETGT && RHSC && RHSC->isAllOnes() && CTVal && CFVal &&
7510         CTVal->isOne() && CFVal->isAllOnes() &&
7511         LHS.getValueType() == TVal.getValueType()) {
7512       EVT VT = LHS.getValueType();
7513       SDValue Shift =
7514           DAG.getNode(ISD::SRA, dl, VT, LHS,
7515                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
7516       return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
7517     }
7518 
7519     unsigned Opcode = AArch64ISD::CSEL;
7520 
7521     // If both the TVal and the FVal are constants, see if we can swap them in
7522     // order to for a CSINV or CSINC out of them.
7523     if (CTVal && CFVal && CTVal->isAllOnes() && CFVal->isZero()) {
7524       std::swap(TVal, FVal);
7525       std::swap(CTVal, CFVal);
7526       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7527     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isZero()) {
7528       std::swap(TVal, FVal);
7529       std::swap(CTVal, CFVal);
7530       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7531     } else if (TVal.getOpcode() == ISD::XOR) {
7532       // If TVal is a NOT we want to swap TVal and FVal so that we can match
7533       // with a CSINV rather than a CSEL.
7534       if (isAllOnesConstant(TVal.getOperand(1))) {
7535         std::swap(TVal, FVal);
7536         std::swap(CTVal, CFVal);
7537         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7538       }
7539     } else if (TVal.getOpcode() == ISD::SUB) {
7540       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
7541       // that we can match with a CSNEG rather than a CSEL.
7542       if (isNullConstant(TVal.getOperand(0))) {
7543         std::swap(TVal, FVal);
7544         std::swap(CTVal, CFVal);
7545         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7546       }
7547     } else if (CTVal && CFVal) {
7548       const int64_t TrueVal = CTVal->getSExtValue();
7549       const int64_t FalseVal = CFVal->getSExtValue();
7550       bool Swap = false;
7551 
7552       // If both TVal and FVal are constants, see if FVal is the
7553       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
7554       // instead of a CSEL in that case.
7555       if (TrueVal == ~FalseVal) {
7556         Opcode = AArch64ISD::CSINV;
7557       } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
7558                  TrueVal == -FalseVal) {
7559         Opcode = AArch64ISD::CSNEG;
7560       } else if (TVal.getValueType() == MVT::i32) {
7561         // If our operands are only 32-bit wide, make sure we use 32-bit
7562         // arithmetic for the check whether we can use CSINC. This ensures that
7563         // the addition in the check will wrap around properly in case there is
7564         // an overflow (which would not be the case if we do the check with
7565         // 64-bit arithmetic).
7566         const uint32_t TrueVal32 = CTVal->getZExtValue();
7567         const uint32_t FalseVal32 = CFVal->getZExtValue();
7568 
7569         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
7570           Opcode = AArch64ISD::CSINC;
7571 
7572           if (TrueVal32 > FalseVal32) {
7573             Swap = true;
7574           }
7575         }
7576         // 64-bit check whether we can use CSINC.
7577       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
7578         Opcode = AArch64ISD::CSINC;
7579 
7580         if (TrueVal > FalseVal) {
7581           Swap = true;
7582         }
7583       }
7584 
7585       // Swap TVal and FVal if necessary.
7586       if (Swap) {
7587         std::swap(TVal, FVal);
7588         std::swap(CTVal, CFVal);
7589         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7590       }
7591 
7592       if (Opcode != AArch64ISD::CSEL) {
7593         // Drop FVal since we can get its value by simply inverting/negating
7594         // TVal.
7595         FVal = TVal;
7596       }
7597     }
7598 
7599     // Avoid materializing a constant when possible by reusing a known value in
7600     // a register.  However, don't perform this optimization if the known value
7601     // is one, zero or negative one in the case of a CSEL.  We can always
7602     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
7603     // FVal, respectively.
7604     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
7605     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
7606         !RHSVal->isZero() && !RHSVal->isAllOnes()) {
7607       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7608       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
7609       // "a != C ? x : a" to avoid materializing C.
7610       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
7611         TVal = LHS;
7612       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
7613         FVal = LHS;
7614     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
7615       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
7616       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
7617       // avoid materializing C.
7618       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7619       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
7620         Opcode = AArch64ISD::CSINV;
7621         TVal = LHS;
7622         FVal = DAG.getConstant(0, dl, FVal.getValueType());
7623       }
7624     }
7625 
7626     SDValue CCVal;
7627     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
7628     EVT VT = TVal.getValueType();
7629     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
7630   }
7631 
7632   // Now we know we're dealing with FP values.
7633   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
7634          LHS.getValueType() == MVT::f64);
7635   assert(LHS.getValueType() == RHS.getValueType());
7636   EVT VT = TVal.getValueType();
7637   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7638 
7639   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7640   // clean.  Some of them require two CSELs to implement.
7641   AArch64CC::CondCode CC1, CC2;
7642   changeFPCCToAArch64CC(CC, CC1, CC2);
7643 
7644   if (DAG.getTarget().Options.UnsafeFPMath) {
7645     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
7646     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
7647     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
7648     if (RHSVal && RHSVal->isZero()) {
7649       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
7650       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
7651 
7652       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
7653           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
7654         TVal = LHS;
7655       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
7656                CFVal && CFVal->isZero() &&
7657                FVal.getValueType() == LHS.getValueType())
7658         FVal = LHS;
7659     }
7660   }
7661 
7662   // Emit first, and possibly only, CSEL.
7663   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7664   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
7665 
7666   // If we need a second CSEL, emit it, using the output of the first as the
7667   // RHS.  We're effectively OR'ing the two CC's together.
7668   if (CC2 != AArch64CC::AL) {
7669     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7670     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
7671   }
7672 
7673   // Otherwise, return the output of the first CSEL.
7674   return CS1;
7675 }
7676 
LowerVECTOR_SPLICE(SDValue Op,SelectionDAG & DAG) const7677 SDValue AArch64TargetLowering::LowerVECTOR_SPLICE(SDValue Op,
7678                                                   SelectionDAG &DAG) const {
7679   EVT Ty = Op.getValueType();
7680   auto Idx = Op.getConstantOperandAPInt(2);
7681 
7682   // This will select to an EXT instruction, which has a maximum immediate
7683   // value of 255, hence 2048-bits is the maximum value we can lower.
7684   if (Idx.sge(-1) && Idx.slt(2048 / Ty.getVectorElementType().getSizeInBits()))
7685     return Op;
7686 
7687   return SDValue();
7688 }
7689 
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const7690 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
7691                                               SelectionDAG &DAG) const {
7692   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7693   SDValue LHS = Op.getOperand(0);
7694   SDValue RHS = Op.getOperand(1);
7695   SDValue TVal = Op.getOperand(2);
7696   SDValue FVal = Op.getOperand(3);
7697   SDLoc DL(Op);
7698   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
7699 }
7700 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const7701 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
7702                                            SelectionDAG &DAG) const {
7703   SDValue CCVal = Op->getOperand(0);
7704   SDValue TVal = Op->getOperand(1);
7705   SDValue FVal = Op->getOperand(2);
7706   SDLoc DL(Op);
7707 
7708   EVT Ty = Op.getValueType();
7709   if (Ty.isScalableVector()) {
7710     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
7711     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
7712     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
7713     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
7714   }
7715 
7716   if (useSVEForFixedLengthVectorVT(Ty)) {
7717     // FIXME: Ideally this would be the same as above using i1 types, however
7718     // for the moment we can't deal with fixed i1 vector types properly, so
7719     // instead extend the predicate to a result type sized integer vector.
7720     MVT SplatValVT = MVT::getIntegerVT(Ty.getScalarSizeInBits());
7721     MVT PredVT = MVT::getVectorVT(SplatValVT, Ty.getVectorElementCount());
7722     SDValue SplatVal = DAG.getSExtOrTrunc(CCVal, DL, SplatValVT);
7723     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, SplatVal);
7724     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
7725   }
7726 
7727   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
7728   // instruction.
7729   if (ISD::isOverflowIntrOpRes(CCVal)) {
7730     // Only lower legal XALUO ops.
7731     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
7732       return SDValue();
7733 
7734     AArch64CC::CondCode OFCC;
7735     SDValue Value, Overflow;
7736     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
7737     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
7738 
7739     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
7740                        CCVal, Overflow);
7741   }
7742 
7743   // Lower it the same way as we would lower a SELECT_CC node.
7744   ISD::CondCode CC;
7745   SDValue LHS, RHS;
7746   if (CCVal.getOpcode() == ISD::SETCC) {
7747     LHS = CCVal.getOperand(0);
7748     RHS = CCVal.getOperand(1);
7749     CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get();
7750   } else {
7751     LHS = CCVal;
7752     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
7753     CC = ISD::SETNE;
7754   }
7755   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
7756 }
7757 
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const7758 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
7759                                               SelectionDAG &DAG) const {
7760   // Jump table entries as PC relative offsets. No additional tweaking
7761   // is necessary here. Just get the address of the jump table.
7762   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7763 
7764   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
7765       !Subtarget->isTargetMachO()) {
7766     return getAddrLarge(JT, DAG);
7767   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7768     return getAddrTiny(JT, DAG);
7769   }
7770   return getAddr(JT, DAG);
7771 }
7772 
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const7773 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
7774                                           SelectionDAG &DAG) const {
7775   // Jump table entries as PC relative offsets. No additional tweaking
7776   // is necessary here. Just get the address of the jump table.
7777   SDLoc DL(Op);
7778   SDValue JT = Op.getOperand(1);
7779   SDValue Entry = Op.getOperand(2);
7780   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
7781 
7782   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7783   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
7784 
7785   SDNode *Dest =
7786       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
7787                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
7788   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
7789                      SDValue(Dest, 0));
7790 }
7791 
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const7792 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
7793                                                  SelectionDAG &DAG) const {
7794   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7795 
7796   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
7797     // Use the GOT for the large code model on iOS.
7798     if (Subtarget->isTargetMachO()) {
7799       return getGOT(CP, DAG);
7800     }
7801     return getAddrLarge(CP, DAG);
7802   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7803     return getAddrTiny(CP, DAG);
7804   } else {
7805     return getAddr(CP, DAG);
7806   }
7807 }
7808 
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const7809 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
7810                                                SelectionDAG &DAG) const {
7811   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
7812   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
7813       !Subtarget->isTargetMachO()) {
7814     return getAddrLarge(BA, DAG);
7815   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7816     return getAddrTiny(BA, DAG);
7817   }
7818   return getAddr(BA, DAG);
7819 }
7820 
LowerDarwin_VASTART(SDValue Op,SelectionDAG & DAG) const7821 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
7822                                                  SelectionDAG &DAG) const {
7823   AArch64FunctionInfo *FuncInfo =
7824       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7825 
7826   SDLoc DL(Op);
7827   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
7828                                  getPointerTy(DAG.getDataLayout()));
7829   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
7830   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7831   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7832                       MachinePointerInfo(SV));
7833 }
7834 
LowerWin64_VASTART(SDValue Op,SelectionDAG & DAG) const7835 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
7836                                                   SelectionDAG &DAG) const {
7837   AArch64FunctionInfo *FuncInfo =
7838       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7839 
7840   SDLoc DL(Op);
7841   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
7842                                      ? FuncInfo->getVarArgsGPRIndex()
7843                                      : FuncInfo->getVarArgsStackIndex(),
7844                                  getPointerTy(DAG.getDataLayout()));
7845   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7846   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7847                       MachinePointerInfo(SV));
7848 }
7849 
LowerAAPCS_VASTART(SDValue Op,SelectionDAG & DAG) const7850 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
7851                                                   SelectionDAG &DAG) const {
7852   // The layout of the va_list struct is specified in the AArch64 Procedure Call
7853   // Standard, section B.3.
7854   MachineFunction &MF = DAG.getMachineFunction();
7855   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
7856   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
7857   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
7858   auto PtrVT = getPointerTy(DAG.getDataLayout());
7859   SDLoc DL(Op);
7860 
7861   SDValue Chain = Op.getOperand(0);
7862   SDValue VAList = Op.getOperand(1);
7863   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7864   SmallVector<SDValue, 4> MemOps;
7865 
7866   // void *__stack at offset 0
7867   unsigned Offset = 0;
7868   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
7869   Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
7870   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
7871                                 MachinePointerInfo(SV), Align(PtrSize)));
7872 
7873   // void *__gr_top at offset 8 (4 on ILP32)
7874   Offset += PtrSize;
7875   int GPRSize = FuncInfo->getVarArgsGPRSize();
7876   if (GPRSize > 0) {
7877     SDValue GRTop, GRTopAddr;
7878 
7879     GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7880                             DAG.getConstant(Offset, DL, PtrVT));
7881 
7882     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
7883     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
7884                         DAG.getConstant(GPRSize, DL, PtrVT));
7885     GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
7886 
7887     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
7888                                   MachinePointerInfo(SV, Offset),
7889                                   Align(PtrSize)));
7890   }
7891 
7892   // void *__vr_top at offset 16 (8 on ILP32)
7893   Offset += PtrSize;
7894   int FPRSize = FuncInfo->getVarArgsFPRSize();
7895   if (FPRSize > 0) {
7896     SDValue VRTop, VRTopAddr;
7897     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7898                             DAG.getConstant(Offset, DL, PtrVT));
7899 
7900     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
7901     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
7902                         DAG.getConstant(FPRSize, DL, PtrVT));
7903     VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
7904 
7905     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
7906                                   MachinePointerInfo(SV, Offset),
7907                                   Align(PtrSize)));
7908   }
7909 
7910   // int __gr_offs at offset 24 (12 on ILP32)
7911   Offset += PtrSize;
7912   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7913                                    DAG.getConstant(Offset, DL, PtrVT));
7914   MemOps.push_back(
7915       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
7916                    GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
7917 
7918   // int __vr_offs at offset 28 (16 on ILP32)
7919   Offset += 4;
7920   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7921                                    DAG.getConstant(Offset, DL, PtrVT));
7922   MemOps.push_back(
7923       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
7924                    VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
7925 
7926   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
7927 }
7928 
LowerVASTART(SDValue Op,SelectionDAG & DAG) const7929 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
7930                                             SelectionDAG &DAG) const {
7931   MachineFunction &MF = DAG.getMachineFunction();
7932 
7933   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
7934     return LowerWin64_VASTART(Op, DAG);
7935   else if (Subtarget->isTargetDarwin())
7936     return LowerDarwin_VASTART(Op, DAG);
7937   else
7938     return LowerAAPCS_VASTART(Op, DAG);
7939 }
7940 
LowerVACOPY(SDValue Op,SelectionDAG & DAG) const7941 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
7942                                            SelectionDAG &DAG) const {
7943   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
7944   // pointer.
7945   SDLoc DL(Op);
7946   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
7947   unsigned VaListSize =
7948       (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
7949           ? PtrSize
7950           : Subtarget->isTargetILP32() ? 20 : 32;
7951   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7952   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7953 
7954   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
7955                        DAG.getConstant(VaListSize, DL, MVT::i32),
7956                        Align(PtrSize), false, false, false,
7957                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
7958 }
7959 
LowerVAARG(SDValue Op,SelectionDAG & DAG) const7960 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7961   assert(Subtarget->isTargetDarwin() &&
7962          "automatic va_arg instruction only works on Darwin");
7963 
7964   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7965   EVT VT = Op.getValueType();
7966   SDLoc DL(Op);
7967   SDValue Chain = Op.getOperand(0);
7968   SDValue Addr = Op.getOperand(1);
7969   MaybeAlign Align(Op.getConstantOperandVal(3));
7970   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
7971   auto PtrVT = getPointerTy(DAG.getDataLayout());
7972   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
7973   SDValue VAList =
7974       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
7975   Chain = VAList.getValue(1);
7976   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
7977 
7978   if (VT.isScalableVector())
7979     report_fatal_error("Passing SVE types to variadic functions is "
7980                        "currently not supported");
7981 
7982   if (Align && *Align > MinSlotSize) {
7983     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7984                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
7985     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
7986                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
7987   }
7988 
7989   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7990   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
7991 
7992   // Scalar integer and FP values smaller than 64 bits are implicitly extended
7993   // up to 64 bits.  At the very least, we have to increase the striding of the
7994   // vaargs list to match this, and for FP values we need to introduce
7995   // FP_ROUND nodes as well.
7996   if (VT.isInteger() && !VT.isVector())
7997     ArgSize = std::max(ArgSize, MinSlotSize);
7998   bool NeedFPTrunc = false;
7999   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
8000     ArgSize = 8;
8001     NeedFPTrunc = true;
8002   }
8003 
8004   // Increment the pointer, VAList, to the next vaarg
8005   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8006                                DAG.getConstant(ArgSize, DL, PtrVT));
8007   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
8008 
8009   // Store the incremented VAList to the legalized pointer
8010   SDValue APStore =
8011       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
8012 
8013   // Load the actual argument out of the pointer VAList
8014   if (NeedFPTrunc) {
8015     // Load the value as an f64.
8016     SDValue WideFP =
8017         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
8018     // Round the value down to an f32.
8019     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
8020                                    DAG.getIntPtrConstant(1, DL));
8021     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
8022     // Merge the rounded value with the chain output of the load.
8023     return DAG.getMergeValues(Ops, DL);
8024   }
8025 
8026   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
8027 }
8028 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const8029 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
8030                                               SelectionDAG &DAG) const {
8031   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8032   MFI.setFrameAddressIsTaken(true);
8033 
8034   EVT VT = Op.getValueType();
8035   SDLoc DL(Op);
8036   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8037   SDValue FrameAddr =
8038       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
8039   while (Depth--)
8040     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
8041                             MachinePointerInfo());
8042 
8043   if (Subtarget->isTargetILP32())
8044     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
8045                             DAG.getValueType(VT));
8046 
8047   return FrameAddr;
8048 }
8049 
LowerSPONENTRY(SDValue Op,SelectionDAG & DAG) const8050 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
8051                                               SelectionDAG &DAG) const {
8052   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8053 
8054   EVT VT = getPointerTy(DAG.getDataLayout());
8055   SDLoc DL(Op);
8056   int FI = MFI.CreateFixedObject(4, 0, false);
8057   return DAG.getFrameIndex(FI, VT);
8058 }
8059 
8060 #define GET_REGISTER_MATCHER
8061 #include "AArch64GenAsmMatcher.inc"
8062 
8063 // FIXME? Maybe this could be a TableGen attribute on some registers and
8064 // this table could be generated automatically from RegInfo.
8065 Register AArch64TargetLowering::
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const8066 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
8067   Register Reg = MatchRegisterName(RegName);
8068   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
8069     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
8070     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
8071     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
8072       Reg = 0;
8073   }
8074   if (Reg)
8075     return Reg;
8076   report_fatal_error(Twine("Invalid register name \""
8077                               + StringRef(RegName)  + "\"."));
8078 }
8079 
LowerADDROFRETURNADDR(SDValue Op,SelectionDAG & DAG) const8080 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
8081                                                      SelectionDAG &DAG) const {
8082   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
8083 
8084   EVT VT = Op.getValueType();
8085   SDLoc DL(Op);
8086 
8087   SDValue FrameAddr =
8088       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
8089   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
8090 
8091   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
8092 }
8093 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const8094 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
8095                                                SelectionDAG &DAG) const {
8096   MachineFunction &MF = DAG.getMachineFunction();
8097   MachineFrameInfo &MFI = MF.getFrameInfo();
8098   MFI.setReturnAddressIsTaken(true);
8099 
8100   EVT VT = Op.getValueType();
8101   SDLoc DL(Op);
8102   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8103   SDValue ReturnAddress;
8104   if (Depth) {
8105     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8106     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
8107     ReturnAddress = DAG.getLoad(
8108         VT, DL, DAG.getEntryNode(),
8109         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
8110   } else {
8111     // Return LR, which contains the return address. Mark it an implicit
8112     // live-in.
8113     unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
8114     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
8115   }
8116 
8117   // The XPACLRI instruction assembles to a hint-space instruction before
8118   // Armv8.3-A therefore this instruction can be safely used for any pre
8119   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
8120   // that instead.
8121   SDNode *St;
8122   if (Subtarget->hasPAuth()) {
8123     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
8124   } else {
8125     // XPACLRI operates on LR therefore we must move the operand accordingly.
8126     SDValue Chain =
8127         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
8128     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
8129   }
8130   return SDValue(St, 0);
8131 }
8132 
8133 /// LowerShiftParts - Lower SHL_PARTS/SRA_PARTS/SRL_PARTS, which returns two
8134 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftParts(SDValue Op,SelectionDAG & DAG) const8135 SDValue AArch64TargetLowering::LowerShiftParts(SDValue Op,
8136                                                SelectionDAG &DAG) const {
8137   SDValue Lo, Hi;
8138   expandShiftParts(Op.getNode(), Lo, Hi, DAG);
8139   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
8140 }
8141 
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const8142 bool AArch64TargetLowering::isOffsetFoldingLegal(
8143     const GlobalAddressSDNode *GA) const {
8144   // Offsets are folded in the DAG combine rather than here so that we can
8145   // intelligently choose an offset based on the uses.
8146   return false;
8147 }
8148 
isFPImmLegal(const APFloat & Imm,EVT VT,bool OptForSize) const8149 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
8150                                          bool OptForSize) const {
8151   bool IsLegal = false;
8152   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
8153   // 16-bit case when target has full fp16 support.
8154   // FIXME: We should be able to handle f128 as well with a clever lowering.
8155   const APInt ImmInt = Imm.bitcastToAPInt();
8156   if (VT == MVT::f64)
8157     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
8158   else if (VT == MVT::f32)
8159     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
8160   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
8161     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
8162   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
8163   //       generate that fmov.
8164 
8165   // If we can not materialize in immediate field for fmov, check if the
8166   // value can be encoded as the immediate operand of a logical instruction.
8167   // The immediate value will be created with either MOVZ, MOVN, or ORR.
8168   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
8169     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
8170     // however the mov+fmov sequence is always better because of the reduced
8171     // cache pressure. The timings are still the same if you consider
8172     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
8173     // movw+movk is fused). So we limit up to 2 instrdduction at most.
8174     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
8175     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
8176 			      Insn);
8177     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
8178     IsLegal = Insn.size() <= Limit;
8179   }
8180 
8181   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
8182                     << " imm value: "; Imm.dump(););
8183   return IsLegal;
8184 }
8185 
8186 //===----------------------------------------------------------------------===//
8187 //                          AArch64 Optimization Hooks
8188 //===----------------------------------------------------------------------===//
8189 
getEstimate(const AArch64Subtarget * ST,unsigned Opcode,SDValue Operand,SelectionDAG & DAG,int & ExtraSteps)8190 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
8191                            SDValue Operand, SelectionDAG &DAG,
8192                            int &ExtraSteps) {
8193   EVT VT = Operand.getValueType();
8194   if (ST->hasNEON() &&
8195       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
8196        VT == MVT::f32 || VT == MVT::v1f32 ||
8197        VT == MVT::v2f32 || VT == MVT::v4f32)) {
8198     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
8199       // For the reciprocal estimates, convergence is quadratic, so the number
8200       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
8201       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
8202       // the result for float (23 mantissa bits) is 2 and for double (52
8203       // mantissa bits) is 3.
8204       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
8205 
8206     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
8207   }
8208 
8209   return SDValue();
8210 }
8211 
8212 SDValue
getSqrtInputTest(SDValue Op,SelectionDAG & DAG,const DenormalMode & Mode) const8213 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
8214                                         const DenormalMode &Mode) const {
8215   SDLoc DL(Op);
8216   EVT VT = Op.getValueType();
8217   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8218   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
8219   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
8220 }
8221 
8222 SDValue
getSqrtResultForDenormInput(SDValue Op,SelectionDAG & DAG) const8223 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
8224                                                    SelectionDAG &DAG) const {
8225   return Op;
8226 }
8227 
getSqrtEstimate(SDValue Operand,SelectionDAG & DAG,int Enabled,int & ExtraSteps,bool & UseOneConst,bool Reciprocal) const8228 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
8229                                                SelectionDAG &DAG, int Enabled,
8230                                                int &ExtraSteps,
8231                                                bool &UseOneConst,
8232                                                bool Reciprocal) const {
8233   if (Enabled == ReciprocalEstimate::Enabled ||
8234       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
8235     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
8236                                        DAG, ExtraSteps)) {
8237       SDLoc DL(Operand);
8238       EVT VT = Operand.getValueType();
8239 
8240       SDNodeFlags Flags;
8241       Flags.setAllowReassociation(true);
8242 
8243       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
8244       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
8245       for (int i = ExtraSteps; i > 0; --i) {
8246         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
8247                                    Flags);
8248         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
8249         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
8250       }
8251       if (!Reciprocal)
8252         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
8253 
8254       ExtraSteps = 0;
8255       return Estimate;
8256     }
8257 
8258   return SDValue();
8259 }
8260 
getRecipEstimate(SDValue Operand,SelectionDAG & DAG,int Enabled,int & ExtraSteps) const8261 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
8262                                                 SelectionDAG &DAG, int Enabled,
8263                                                 int &ExtraSteps) const {
8264   if (Enabled == ReciprocalEstimate::Enabled)
8265     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
8266                                        DAG, ExtraSteps)) {
8267       SDLoc DL(Operand);
8268       EVT VT = Operand.getValueType();
8269 
8270       SDNodeFlags Flags;
8271       Flags.setAllowReassociation(true);
8272 
8273       // Newton reciprocal iteration: E * (2 - X * E)
8274       // AArch64 reciprocal iteration instruction: (2 - M * N)
8275       for (int i = ExtraSteps; i > 0; --i) {
8276         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
8277                                    Estimate, Flags);
8278         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
8279       }
8280 
8281       ExtraSteps = 0;
8282       return Estimate;
8283     }
8284 
8285   return SDValue();
8286 }
8287 
8288 //===----------------------------------------------------------------------===//
8289 //                          AArch64 Inline Assembly Support
8290 //===----------------------------------------------------------------------===//
8291 
8292 // Table of Constraints
8293 // TODO: This is the current set of constraints supported by ARM for the
8294 // compiler, not all of them may make sense.
8295 //
8296 // r - A general register
8297 // w - An FP/SIMD register of some size in the range v0-v31
8298 // x - An FP/SIMD register of some size in the range v0-v15
8299 // I - Constant that can be used with an ADD instruction
8300 // J - Constant that can be used with a SUB instruction
8301 // K - Constant that can be used with a 32-bit logical instruction
8302 // L - Constant that can be used with a 64-bit logical instruction
8303 // M - Constant that can be used as a 32-bit MOV immediate
8304 // N - Constant that can be used as a 64-bit MOV immediate
8305 // Q - A memory reference with base register and no offset
8306 // S - A symbolic address
8307 // Y - Floating point constant zero
8308 // Z - Integer constant zero
8309 //
8310 //   Note that general register operands will be output using their 64-bit x
8311 // register name, whatever the size of the variable, unless the asm operand
8312 // is prefixed by the %w modifier. Floating-point and SIMD register operands
8313 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
8314 // %q modifier.
LowerXConstraint(EVT ConstraintVT) const8315 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
8316   // At this point, we have to lower this constraint to something else, so we
8317   // lower it to an "r" or "w". However, by doing this we will force the result
8318   // to be in register, while the X constraint is much more permissive.
8319   //
8320   // Although we are correct (we are free to emit anything, without
8321   // constraints), we might break use cases that would expect us to be more
8322   // efficient and emit something else.
8323   if (!Subtarget->hasFPARMv8())
8324     return "r";
8325 
8326   if (ConstraintVT.isFloatingPoint())
8327     return "w";
8328 
8329   if (ConstraintVT.isVector() &&
8330      (ConstraintVT.getSizeInBits() == 64 ||
8331       ConstraintVT.getSizeInBits() == 128))
8332     return "w";
8333 
8334   return "r";
8335 }
8336 
8337 enum PredicateConstraint {
8338   Upl,
8339   Upa,
8340   Invalid
8341 };
8342 
parsePredicateConstraint(StringRef Constraint)8343 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
8344   PredicateConstraint P = PredicateConstraint::Invalid;
8345   if (Constraint == "Upa")
8346     P = PredicateConstraint::Upa;
8347   if (Constraint == "Upl")
8348     P = PredicateConstraint::Upl;
8349   return P;
8350 }
8351 
8352 /// getConstraintType - Given a constraint letter, return the type of
8353 /// constraint it is for this target.
8354 AArch64TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const8355 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
8356   if (Constraint.size() == 1) {
8357     switch (Constraint[0]) {
8358     default:
8359       break;
8360     case 'x':
8361     case 'w':
8362     case 'y':
8363       return C_RegisterClass;
8364     // An address with a single base register. Due to the way we
8365     // currently handle addresses it is the same as 'r'.
8366     case 'Q':
8367       return C_Memory;
8368     case 'I':
8369     case 'J':
8370     case 'K':
8371     case 'L':
8372     case 'M':
8373     case 'N':
8374     case 'Y':
8375     case 'Z':
8376       return C_Immediate;
8377     case 'z':
8378     case 'S': // A symbolic address
8379       return C_Other;
8380     }
8381   } else if (parsePredicateConstraint(Constraint) !=
8382              PredicateConstraint::Invalid)
8383       return C_RegisterClass;
8384   return TargetLowering::getConstraintType(Constraint);
8385 }
8386 
8387 /// Examine constraint type and operand type and determine a weight value.
8388 /// This object must already have been set up with the operand type
8389 /// and the current alternative constraint selected.
8390 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const8391 AArch64TargetLowering::getSingleConstraintMatchWeight(
8392     AsmOperandInfo &info, const char *constraint) const {
8393   ConstraintWeight weight = CW_Invalid;
8394   Value *CallOperandVal = info.CallOperandVal;
8395   // If we don't have a value, we can't do a match,
8396   // but allow it at the lowest weight.
8397   if (!CallOperandVal)
8398     return CW_Default;
8399   Type *type = CallOperandVal->getType();
8400   // Look at the constraint type.
8401   switch (*constraint) {
8402   default:
8403     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8404     break;
8405   case 'x':
8406   case 'w':
8407   case 'y':
8408     if (type->isFloatingPointTy() || type->isVectorTy())
8409       weight = CW_Register;
8410     break;
8411   case 'z':
8412     weight = CW_Constant;
8413     break;
8414   case 'U':
8415     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
8416       weight = CW_Register;
8417     break;
8418   }
8419   return weight;
8420 }
8421 
8422 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const8423 AArch64TargetLowering::getRegForInlineAsmConstraint(
8424     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
8425   if (Constraint.size() == 1) {
8426     switch (Constraint[0]) {
8427     case 'r':
8428       if (VT.isScalableVector())
8429         return std::make_pair(0U, nullptr);
8430       if (Subtarget->hasLS64() && VT.getSizeInBits() == 512)
8431         return std::make_pair(0U, &AArch64::GPR64x8ClassRegClass);
8432       if (VT.getFixedSizeInBits() == 64)
8433         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
8434       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
8435     case 'w': {
8436       if (!Subtarget->hasFPARMv8())
8437         break;
8438       if (VT.isScalableVector()) {
8439         if (VT.getVectorElementType() != MVT::i1)
8440           return std::make_pair(0U, &AArch64::ZPRRegClass);
8441         return std::make_pair(0U, nullptr);
8442       }
8443       uint64_t VTSize = VT.getFixedSizeInBits();
8444       if (VTSize == 16)
8445         return std::make_pair(0U, &AArch64::FPR16RegClass);
8446       if (VTSize == 32)
8447         return std::make_pair(0U, &AArch64::FPR32RegClass);
8448       if (VTSize == 64)
8449         return std::make_pair(0U, &AArch64::FPR64RegClass);
8450       if (VTSize == 128)
8451         return std::make_pair(0U, &AArch64::FPR128RegClass);
8452       break;
8453     }
8454     // The instructions that this constraint is designed for can
8455     // only take 128-bit registers so just use that regclass.
8456     case 'x':
8457       if (!Subtarget->hasFPARMv8())
8458         break;
8459       if (VT.isScalableVector())
8460         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
8461       if (VT.getSizeInBits() == 128)
8462         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
8463       break;
8464     case 'y':
8465       if (!Subtarget->hasFPARMv8())
8466         break;
8467       if (VT.isScalableVector())
8468         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
8469       break;
8470     }
8471   } else {
8472     PredicateConstraint PC = parsePredicateConstraint(Constraint);
8473     if (PC != PredicateConstraint::Invalid) {
8474       if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
8475         return std::make_pair(0U, nullptr);
8476       bool restricted = (PC == PredicateConstraint::Upl);
8477       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
8478                         : std::make_pair(0U, &AArch64::PPRRegClass);
8479     }
8480   }
8481   if (StringRef("{cc}").equals_insensitive(Constraint))
8482     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
8483 
8484   // Use the default implementation in TargetLowering to convert the register
8485   // constraint into a member of a register class.
8486   std::pair<unsigned, const TargetRegisterClass *> Res;
8487   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8488 
8489   // Not found as a standard register?
8490   if (!Res.second) {
8491     unsigned Size = Constraint.size();
8492     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
8493         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
8494       int RegNo;
8495       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
8496       if (!Failed && RegNo >= 0 && RegNo <= 31) {
8497         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
8498         // By default we'll emit v0-v31 for this unless there's a modifier where
8499         // we'll emit the correct register as well.
8500         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
8501           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
8502           Res.second = &AArch64::FPR64RegClass;
8503         } else {
8504           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
8505           Res.second = &AArch64::FPR128RegClass;
8506         }
8507       }
8508     }
8509   }
8510 
8511   if (Res.second && !Subtarget->hasFPARMv8() &&
8512       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
8513       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
8514     return std::make_pair(0U, nullptr);
8515 
8516   return Res;
8517 }
8518 
getAsmOperandValueType(const DataLayout & DL,llvm::Type * Ty,bool AllowUnknown) const8519 EVT AArch64TargetLowering::getAsmOperandValueType(const DataLayout &DL,
8520                                                   llvm::Type *Ty,
8521                                                   bool AllowUnknown) const {
8522   if (Subtarget->hasLS64() && Ty->isIntegerTy(512))
8523     return EVT(MVT::i64x8);
8524 
8525   return TargetLowering::getAsmOperandValueType(DL, Ty, AllowUnknown);
8526 }
8527 
8528 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8529 /// vector.  If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const8530 void AArch64TargetLowering::LowerAsmOperandForConstraint(
8531     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
8532     SelectionDAG &DAG) const {
8533   SDValue Result;
8534 
8535   // Currently only support length 1 constraints.
8536   if (Constraint.length() != 1)
8537     return;
8538 
8539   char ConstraintLetter = Constraint[0];
8540   switch (ConstraintLetter) {
8541   default:
8542     break;
8543 
8544   // This set of constraints deal with valid constants for various instructions.
8545   // Validate and return a target constant for them if we can.
8546   case 'z': {
8547     // 'z' maps to xzr or wzr so it needs an input of 0.
8548     if (!isNullConstant(Op))
8549       return;
8550 
8551     if (Op.getValueType() == MVT::i64)
8552       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
8553     else
8554       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
8555     break;
8556   }
8557   case 'S': {
8558     // An absolute symbolic address or label reference.
8559     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8560       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
8561                                           GA->getValueType(0));
8562     } else if (const BlockAddressSDNode *BA =
8563                    dyn_cast<BlockAddressSDNode>(Op)) {
8564       Result =
8565           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
8566     } else
8567       return;
8568     break;
8569   }
8570 
8571   case 'I':
8572   case 'J':
8573   case 'K':
8574   case 'L':
8575   case 'M':
8576   case 'N':
8577     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8578     if (!C)
8579       return;
8580 
8581     // Grab the value and do some validation.
8582     uint64_t CVal = C->getZExtValue();
8583     switch (ConstraintLetter) {
8584     // The I constraint applies only to simple ADD or SUB immediate operands:
8585     // i.e. 0 to 4095 with optional shift by 12
8586     // The J constraint applies only to ADD or SUB immediates that would be
8587     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
8588     // instruction [or vice versa], in other words -1 to -4095 with optional
8589     // left shift by 12.
8590     case 'I':
8591       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
8592         break;
8593       return;
8594     case 'J': {
8595       uint64_t NVal = -C->getSExtValue();
8596       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
8597         CVal = C->getSExtValue();
8598         break;
8599       }
8600       return;
8601     }
8602     // The K and L constraints apply *only* to logical immediates, including
8603     // what used to be the MOVI alias for ORR (though the MOVI alias has now
8604     // been removed and MOV should be used). So these constraints have to
8605     // distinguish between bit patterns that are valid 32-bit or 64-bit
8606     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
8607     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
8608     // versa.
8609     case 'K':
8610       if (AArch64_AM::isLogicalImmediate(CVal, 32))
8611         break;
8612       return;
8613     case 'L':
8614       if (AArch64_AM::isLogicalImmediate(CVal, 64))
8615         break;
8616       return;
8617     // The M and N constraints are a superset of K and L respectively, for use
8618     // with the MOV (immediate) alias. As well as the logical immediates they
8619     // also match 32 or 64-bit immediates that can be loaded either using a
8620     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
8621     // (M) or 64-bit 0x1234000000000000 (N) etc.
8622     // As a note some of this code is liberally stolen from the asm parser.
8623     case 'M': {
8624       if (!isUInt<32>(CVal))
8625         return;
8626       if (AArch64_AM::isLogicalImmediate(CVal, 32))
8627         break;
8628       if ((CVal & 0xFFFF) == CVal)
8629         break;
8630       if ((CVal & 0xFFFF0000ULL) == CVal)
8631         break;
8632       uint64_t NCVal = ~(uint32_t)CVal;
8633       if ((NCVal & 0xFFFFULL) == NCVal)
8634         break;
8635       if ((NCVal & 0xFFFF0000ULL) == NCVal)
8636         break;
8637       return;
8638     }
8639     case 'N': {
8640       if (AArch64_AM::isLogicalImmediate(CVal, 64))
8641         break;
8642       if ((CVal & 0xFFFFULL) == CVal)
8643         break;
8644       if ((CVal & 0xFFFF0000ULL) == CVal)
8645         break;
8646       if ((CVal & 0xFFFF00000000ULL) == CVal)
8647         break;
8648       if ((CVal & 0xFFFF000000000000ULL) == CVal)
8649         break;
8650       uint64_t NCVal = ~CVal;
8651       if ((NCVal & 0xFFFFULL) == NCVal)
8652         break;
8653       if ((NCVal & 0xFFFF0000ULL) == NCVal)
8654         break;
8655       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
8656         break;
8657       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
8658         break;
8659       return;
8660     }
8661     default:
8662       return;
8663     }
8664 
8665     // All assembler immediates are 64-bit integers.
8666     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
8667     break;
8668   }
8669 
8670   if (Result.getNode()) {
8671     Ops.push_back(Result);
8672     return;
8673   }
8674 
8675   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8676 }
8677 
8678 //===----------------------------------------------------------------------===//
8679 //                     AArch64 Advanced SIMD Support
8680 //===----------------------------------------------------------------------===//
8681 
8682 /// WidenVector - Given a value in the V64 register class, produce the
8683 /// equivalent value in the V128 register class.
WidenVector(SDValue V64Reg,SelectionDAG & DAG)8684 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
8685   EVT VT = V64Reg.getValueType();
8686   unsigned NarrowSize = VT.getVectorNumElements();
8687   MVT EltTy = VT.getVectorElementType().getSimpleVT();
8688   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
8689   SDLoc DL(V64Reg);
8690 
8691   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
8692                      V64Reg, DAG.getConstant(0, DL, MVT::i64));
8693 }
8694 
8695 /// getExtFactor - Determine the adjustment factor for the position when
8696 /// generating an "extract from vector registers" instruction.
getExtFactor(SDValue & V)8697 static unsigned getExtFactor(SDValue &V) {
8698   EVT EltType = V.getValueType().getVectorElementType();
8699   return EltType.getSizeInBits() / 8;
8700 }
8701 
8702 /// NarrowVector - Given a value in the V128 register class, produce the
8703 /// equivalent value in the V64 register class.
NarrowVector(SDValue V128Reg,SelectionDAG & DAG)8704 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
8705   EVT VT = V128Reg.getValueType();
8706   unsigned WideSize = VT.getVectorNumElements();
8707   MVT EltTy = VT.getVectorElementType().getSimpleVT();
8708   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
8709   SDLoc DL(V128Reg);
8710 
8711   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
8712 }
8713 
8714 // Gather data to see if the operation can be modelled as a
8715 // shuffle in combination with VEXTs.
ReconstructShuffle(SDValue Op,SelectionDAG & DAG) const8716 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
8717                                                   SelectionDAG &DAG) const {
8718   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8719   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
8720   SDLoc dl(Op);
8721   EVT VT = Op.getValueType();
8722   assert(!VT.isScalableVector() &&
8723          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
8724   unsigned NumElts = VT.getVectorNumElements();
8725 
8726   struct ShuffleSourceInfo {
8727     SDValue Vec;
8728     unsigned MinElt;
8729     unsigned MaxElt;
8730 
8731     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8732     // be compatible with the shuffle we intend to construct. As a result
8733     // ShuffleVec will be some sliding window into the original Vec.
8734     SDValue ShuffleVec;
8735 
8736     // Code should guarantee that element i in Vec starts at element "WindowBase
8737     // + i * WindowScale in ShuffleVec".
8738     int WindowBase;
8739     int WindowScale;
8740 
8741     ShuffleSourceInfo(SDValue Vec)
8742       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
8743           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
8744 
8745     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8746   };
8747 
8748   // First gather all vectors used as an immediate source for this BUILD_VECTOR
8749   // node.
8750   SmallVector<ShuffleSourceInfo, 2> Sources;
8751   for (unsigned i = 0; i < NumElts; ++i) {
8752     SDValue V = Op.getOperand(i);
8753     if (V.isUndef())
8754       continue;
8755     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8756              !isa<ConstantSDNode>(V.getOperand(1))) {
8757       LLVM_DEBUG(
8758           dbgs() << "Reshuffle failed: "
8759                     "a shuffle can only come from building a vector from "
8760                     "various elements of other vectors, provided their "
8761                     "indices are constant\n");
8762       return SDValue();
8763     }
8764 
8765     // Add this element source to the list if it's not already there.
8766     SDValue SourceVec = V.getOperand(0);
8767     auto Source = find(Sources, SourceVec);
8768     if (Source == Sources.end())
8769       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8770 
8771     // Update the minimum and maximum lane number seen.
8772     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
8773     Source->MinElt = std::min(Source->MinElt, EltNo);
8774     Source->MaxElt = std::max(Source->MaxElt, EltNo);
8775   }
8776 
8777   if (Sources.size() > 2) {
8778     LLVM_DEBUG(
8779         dbgs() << "Reshuffle failed: currently only do something sane when at "
8780                   "most two source vectors are involved\n");
8781     return SDValue();
8782   }
8783 
8784   // Find out the smallest element size among result and two sources, and use
8785   // it as element size to build the shuffle_vector.
8786   EVT SmallestEltTy = VT.getVectorElementType();
8787   for (auto &Source : Sources) {
8788     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8789     if (SrcEltTy.bitsLT(SmallestEltTy)) {
8790       SmallestEltTy = SrcEltTy;
8791     }
8792   }
8793   unsigned ResMultiplier =
8794       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
8795   uint64_t VTSize = VT.getFixedSizeInBits();
8796   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
8797   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8798 
8799   // If the source vector is too wide or too narrow, we may nevertheless be able
8800   // to construct a compatible shuffle either by concatenating it with UNDEF or
8801   // extracting a suitable range of elements.
8802   for (auto &Src : Sources) {
8803     EVT SrcVT = Src.ShuffleVec.getValueType();
8804 
8805     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8806     if (SrcVTSize == VTSize)
8807       continue;
8808 
8809     // This stage of the search produces a source with the same element type as
8810     // the original, but with a total width matching the BUILD_VECTOR output.
8811     EVT EltVT = SrcVT.getVectorElementType();
8812     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8813     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8814 
8815     if (SrcVTSize < VTSize) {
8816       assert(2 * SrcVTSize == VTSize);
8817       // We can pad out the smaller vector for free, so if it's part of a
8818       // shuffle...
8819       Src.ShuffleVec =
8820           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8821                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8822       continue;
8823     }
8824 
8825     if (SrcVTSize != 2 * VTSize) {
8826       LLVM_DEBUG(
8827           dbgs() << "Reshuffle failed: result vector too small to extract\n");
8828       return SDValue();
8829     }
8830 
8831     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8832       LLVM_DEBUG(
8833           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
8834       return SDValue();
8835     }
8836 
8837     if (Src.MinElt >= NumSrcElts) {
8838       // The extraction can just take the second half
8839       Src.ShuffleVec =
8840           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8841                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
8842       Src.WindowBase = -NumSrcElts;
8843     } else if (Src.MaxElt < NumSrcElts) {
8844       // The extraction can just take the first half
8845       Src.ShuffleVec =
8846           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8847                       DAG.getConstant(0, dl, MVT::i64));
8848     } else {
8849       // An actual VEXT is needed
8850       SDValue VEXTSrc1 =
8851           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8852                       DAG.getConstant(0, dl, MVT::i64));
8853       SDValue VEXTSrc2 =
8854           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8855                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
8856       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
8857 
8858       if (!SrcVT.is64BitVector()) {
8859         LLVM_DEBUG(
8860           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
8861                     "for SVE vectors.");
8862         return SDValue();
8863       }
8864 
8865       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
8866                                    VEXTSrc2,
8867                                    DAG.getConstant(Imm, dl, MVT::i32));
8868       Src.WindowBase = -Src.MinElt;
8869     }
8870   }
8871 
8872   // Another possible incompatibility occurs from the vector element types. We
8873   // can fix this by bitcasting the source vectors to the same type we intend
8874   // for the shuffle.
8875   for (auto &Src : Sources) {
8876     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8877     if (SrcEltTy == SmallestEltTy)
8878       continue;
8879     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8880     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
8881     Src.WindowScale =
8882         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
8883     Src.WindowBase *= Src.WindowScale;
8884   }
8885 
8886   // Final sanity check before we try to actually produce a shuffle.
8887   LLVM_DEBUG(for (auto Src
8888                   : Sources)
8889                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
8890 
8891   // The stars all align, our next step is to produce the mask for the shuffle.
8892   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8893   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8894   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8895     SDValue Entry = Op.getOperand(i);
8896     if (Entry.isUndef())
8897       continue;
8898 
8899     auto Src = find(Sources, Entry.getOperand(0));
8900     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8901 
8902     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8903     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8904     // segment.
8905     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8906     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8907                                VT.getScalarSizeInBits());
8908     int LanesDefined = BitsDefined / BitsPerShuffleLane;
8909 
8910     // This source is expected to fill ResMultiplier lanes of the final shuffle,
8911     // starting at the appropriate offset.
8912     int *LaneMask = &Mask[i * ResMultiplier];
8913 
8914     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8915     ExtractBase += NumElts * (Src - Sources.begin());
8916     for (int j = 0; j < LanesDefined; ++j)
8917       LaneMask[j] = ExtractBase + j;
8918   }
8919 
8920   // Final check before we try to produce nonsense...
8921   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
8922     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
8923     return SDValue();
8924   }
8925 
8926   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8927   for (unsigned i = 0; i < Sources.size(); ++i)
8928     ShuffleOps[i] = Sources[i].ShuffleVec;
8929 
8930   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8931                                          ShuffleOps[1], Mask);
8932   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
8933 
8934   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
8935              dbgs() << "Reshuffle, creating node: "; V.dump(););
8936 
8937   return V;
8938 }
8939 
8940 // check if an EXT instruction can handle the shuffle mask when the
8941 // vector sources of the shuffle are the same.
isSingletonEXTMask(ArrayRef<int> M,EVT VT,unsigned & Imm)8942 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
8943   unsigned NumElts = VT.getVectorNumElements();
8944 
8945   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
8946   if (M[0] < 0)
8947     return false;
8948 
8949   Imm = M[0];
8950 
8951   // If this is a VEXT shuffle, the immediate value is the index of the first
8952   // element.  The other shuffle indices must be the successive elements after
8953   // the first one.
8954   unsigned ExpectedElt = Imm;
8955   for (unsigned i = 1; i < NumElts; ++i) {
8956     // Increment the expected index.  If it wraps around, just follow it
8957     // back to index zero and keep going.
8958     ++ExpectedElt;
8959     if (ExpectedElt == NumElts)
8960       ExpectedElt = 0;
8961 
8962     if (M[i] < 0)
8963       continue; // ignore UNDEF indices
8964     if (ExpectedElt != static_cast<unsigned>(M[i]))
8965       return false;
8966   }
8967 
8968   return true;
8969 }
8970 
8971 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
8972 /// element width than the vector lane type. If that is the case the function
8973 /// returns true and writes the value of the DUP instruction lane operand into
8974 /// DupLaneOp
isWideDUPMask(ArrayRef<int> M,EVT VT,unsigned BlockSize,unsigned & DupLaneOp)8975 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
8976                           unsigned &DupLaneOp) {
8977   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
8978          "Only possible block sizes for wide DUP are: 16, 32, 64");
8979 
8980   if (BlockSize <= VT.getScalarSizeInBits())
8981     return false;
8982   if (BlockSize % VT.getScalarSizeInBits() != 0)
8983     return false;
8984   if (VT.getSizeInBits() % BlockSize != 0)
8985     return false;
8986 
8987   size_t SingleVecNumElements = VT.getVectorNumElements();
8988   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
8989   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
8990 
8991   // We are looking for masks like
8992   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
8993   // might be replaced by 'undefined'. BlockIndices will eventually contain
8994   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
8995   // for the above examples)
8996   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
8997   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
8998     for (size_t I = 0; I < NumEltsPerBlock; I++) {
8999       int Elt = M[BlockIndex * NumEltsPerBlock + I];
9000       if (Elt < 0)
9001         continue;
9002       // For now we don't support shuffles that use the second operand
9003       if ((unsigned)Elt >= SingleVecNumElements)
9004         return false;
9005       if (BlockElts[I] < 0)
9006         BlockElts[I] = Elt;
9007       else if (BlockElts[I] != Elt)
9008         return false;
9009     }
9010 
9011   // We found a candidate block (possibly with some undefs). It must be a
9012   // sequence of consecutive integers starting with a value divisible by
9013   // NumEltsPerBlock with some values possibly replaced by undef-s.
9014 
9015   // Find first non-undef element
9016   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
9017   assert(FirstRealEltIter != BlockElts.end() &&
9018          "Shuffle with all-undefs must have been caught by previous cases, "
9019          "e.g. isSplat()");
9020   if (FirstRealEltIter == BlockElts.end()) {
9021     DupLaneOp = 0;
9022     return true;
9023   }
9024 
9025   // Index of FirstRealElt in BlockElts
9026   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
9027 
9028   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
9029     return false;
9030   // BlockElts[0] must have the following value if it isn't undef:
9031   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
9032 
9033   // Check the first element
9034   if (Elt0 % NumEltsPerBlock != 0)
9035     return false;
9036   // Check that the sequence indeed consists of consecutive integers (modulo
9037   // undefs)
9038   for (size_t I = 0; I < NumEltsPerBlock; I++)
9039     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
9040       return false;
9041 
9042   DupLaneOp = Elt0 / NumEltsPerBlock;
9043   return true;
9044 }
9045 
9046 // check if an EXT instruction can handle the shuffle mask when the
9047 // vector sources of the shuffle are different.
isEXTMask(ArrayRef<int> M,EVT VT,bool & ReverseEXT,unsigned & Imm)9048 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
9049                       unsigned &Imm) {
9050   // Look for the first non-undef element.
9051   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
9052 
9053   // Benefit form APInt to handle overflow when calculating expected element.
9054   unsigned NumElts = VT.getVectorNumElements();
9055   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
9056   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
9057   // The following shuffle indices must be the successive elements after the
9058   // first real element.
9059   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
9060       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
9061   if (FirstWrongElt != M.end())
9062     return false;
9063 
9064   // The index of an EXT is the first element if it is not UNDEF.
9065   // Watch out for the beginning UNDEFs. The EXT index should be the expected
9066   // value of the first element.  E.g.
9067   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
9068   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
9069   // ExpectedElt is the last mask index plus 1.
9070   Imm = ExpectedElt.getZExtValue();
9071 
9072   // There are two difference cases requiring to reverse input vectors.
9073   // For example, for vector <4 x i32> we have the following cases,
9074   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
9075   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
9076   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
9077   // to reverse two input vectors.
9078   if (Imm < NumElts)
9079     ReverseEXT = true;
9080   else
9081     Imm -= NumElts;
9082 
9083   return true;
9084 }
9085 
9086 /// isREVMask - Check if a vector shuffle corresponds to a REV
9087 /// instruction with the specified blocksize.  (The order of the elements
9088 /// within each block of the vector is reversed.)
isREVMask(ArrayRef<int> M,EVT VT,unsigned BlockSize)9089 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
9090   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
9091          "Only possible block sizes for REV are: 16, 32, 64");
9092 
9093   unsigned EltSz = VT.getScalarSizeInBits();
9094   if (EltSz == 64)
9095     return false;
9096 
9097   unsigned NumElts = VT.getVectorNumElements();
9098   unsigned BlockElts = M[0] + 1;
9099   // If the first shuffle index is UNDEF, be optimistic.
9100   if (M[0] < 0)
9101     BlockElts = BlockSize / EltSz;
9102 
9103   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
9104     return false;
9105 
9106   for (unsigned i = 0; i < NumElts; ++i) {
9107     if (M[i] < 0)
9108       continue; // ignore UNDEF indices
9109     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
9110       return false;
9111   }
9112 
9113   return true;
9114 }
9115 
isZIPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)9116 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9117   unsigned NumElts = VT.getVectorNumElements();
9118   if (NumElts % 2 != 0)
9119     return false;
9120   WhichResult = (M[0] == 0 ? 0 : 1);
9121   unsigned Idx = WhichResult * NumElts / 2;
9122   for (unsigned i = 0; i != NumElts; i += 2) {
9123     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
9124         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
9125       return false;
9126     Idx += 1;
9127   }
9128 
9129   return true;
9130 }
9131 
isUZPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)9132 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9133   unsigned NumElts = VT.getVectorNumElements();
9134   WhichResult = (M[0] == 0 ? 0 : 1);
9135   for (unsigned i = 0; i != NumElts; ++i) {
9136     if (M[i] < 0)
9137       continue; // ignore UNDEF indices
9138     if ((unsigned)M[i] != 2 * i + WhichResult)
9139       return false;
9140   }
9141 
9142   return true;
9143 }
9144 
isTRNMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)9145 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9146   unsigned NumElts = VT.getVectorNumElements();
9147   if (NumElts % 2 != 0)
9148     return false;
9149   WhichResult = (M[0] == 0 ? 0 : 1);
9150   for (unsigned i = 0; i < NumElts; i += 2) {
9151     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
9152         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
9153       return false;
9154   }
9155   return true;
9156 }
9157 
9158 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
9159 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9160 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
isZIP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)9161 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9162   unsigned NumElts = VT.getVectorNumElements();
9163   if (NumElts % 2 != 0)
9164     return false;
9165   WhichResult = (M[0] == 0 ? 0 : 1);
9166   unsigned Idx = WhichResult * NumElts / 2;
9167   for (unsigned i = 0; i != NumElts; i += 2) {
9168     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
9169         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
9170       return false;
9171     Idx += 1;
9172   }
9173 
9174   return true;
9175 }
9176 
9177 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
9178 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9179 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
isUZP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)9180 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9181   unsigned Half = VT.getVectorNumElements() / 2;
9182   WhichResult = (M[0] == 0 ? 0 : 1);
9183   for (unsigned j = 0; j != 2; ++j) {
9184     unsigned Idx = WhichResult;
9185     for (unsigned i = 0; i != Half; ++i) {
9186       int MIdx = M[i + j * Half];
9187       if (MIdx >= 0 && (unsigned)MIdx != Idx)
9188         return false;
9189       Idx += 2;
9190     }
9191   }
9192 
9193   return true;
9194 }
9195 
9196 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
9197 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9198 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
isTRN_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)9199 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9200   unsigned NumElts = VT.getVectorNumElements();
9201   if (NumElts % 2 != 0)
9202     return false;
9203   WhichResult = (M[0] == 0 ? 0 : 1);
9204   for (unsigned i = 0; i < NumElts; i += 2) {
9205     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
9206         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
9207       return false;
9208   }
9209   return true;
9210 }
9211 
isINSMask(ArrayRef<int> M,int NumInputElements,bool & DstIsLeft,int & Anomaly)9212 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
9213                       bool &DstIsLeft, int &Anomaly) {
9214   if (M.size() != static_cast<size_t>(NumInputElements))
9215     return false;
9216 
9217   int NumLHSMatch = 0, NumRHSMatch = 0;
9218   int LastLHSMismatch = -1, LastRHSMismatch = -1;
9219 
9220   for (int i = 0; i < NumInputElements; ++i) {
9221     if (M[i] == -1) {
9222       ++NumLHSMatch;
9223       ++NumRHSMatch;
9224       continue;
9225     }
9226 
9227     if (M[i] == i)
9228       ++NumLHSMatch;
9229     else
9230       LastLHSMismatch = i;
9231 
9232     if (M[i] == i + NumInputElements)
9233       ++NumRHSMatch;
9234     else
9235       LastRHSMismatch = i;
9236   }
9237 
9238   if (NumLHSMatch == NumInputElements - 1) {
9239     DstIsLeft = true;
9240     Anomaly = LastLHSMismatch;
9241     return true;
9242   } else if (NumRHSMatch == NumInputElements - 1) {
9243     DstIsLeft = false;
9244     Anomaly = LastRHSMismatch;
9245     return true;
9246   }
9247 
9248   return false;
9249 }
9250 
isConcatMask(ArrayRef<int> Mask,EVT VT,bool SplitLHS)9251 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
9252   if (VT.getSizeInBits() != 128)
9253     return false;
9254 
9255   unsigned NumElts = VT.getVectorNumElements();
9256 
9257   for (int I = 0, E = NumElts / 2; I != E; I++) {
9258     if (Mask[I] != I)
9259       return false;
9260   }
9261 
9262   int Offset = NumElts / 2;
9263   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
9264     if (Mask[I] != I + SplitLHS * Offset)
9265       return false;
9266   }
9267 
9268   return true;
9269 }
9270 
tryFormConcatFromShuffle(SDValue Op,SelectionDAG & DAG)9271 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
9272   SDLoc DL(Op);
9273   EVT VT = Op.getValueType();
9274   SDValue V0 = Op.getOperand(0);
9275   SDValue V1 = Op.getOperand(1);
9276   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
9277 
9278   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
9279       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
9280     return SDValue();
9281 
9282   bool SplitV0 = V0.getValueSizeInBits() == 128;
9283 
9284   if (!isConcatMask(Mask, VT, SplitV0))
9285     return SDValue();
9286 
9287   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
9288   if (SplitV0) {
9289     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
9290                      DAG.getConstant(0, DL, MVT::i64));
9291   }
9292   if (V1.getValueSizeInBits() == 128) {
9293     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
9294                      DAG.getConstant(0, DL, MVT::i64));
9295   }
9296   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
9297 }
9298 
9299 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9300 /// the specified operations to build the shuffle.
GeneratePerfectShuffle(unsigned PFEntry,SDValue LHS,SDValue RHS,SelectionDAG & DAG,const SDLoc & dl)9301 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9302                                       SDValue RHS, SelectionDAG &DAG,
9303                                       const SDLoc &dl) {
9304   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9305   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
9306   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
9307 
9308   enum {
9309     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9310     OP_VREV,
9311     OP_VDUP0,
9312     OP_VDUP1,
9313     OP_VDUP2,
9314     OP_VDUP3,
9315     OP_VEXT1,
9316     OP_VEXT2,
9317     OP_VEXT3,
9318     OP_VUZPL, // VUZP, left result
9319     OP_VUZPR, // VUZP, right result
9320     OP_VZIPL, // VZIP, left result
9321     OP_VZIPR, // VZIP, right result
9322     OP_VTRNL, // VTRN, left result
9323     OP_VTRNR  // VTRN, right result
9324   };
9325 
9326   if (OpNum == OP_COPY) {
9327     if (LHSID == (1 * 9 + 2) * 9 + 3)
9328       return LHS;
9329     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
9330     return RHS;
9331   }
9332 
9333   SDValue OpLHS, OpRHS;
9334   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9335   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9336   EVT VT = OpLHS.getValueType();
9337 
9338   switch (OpNum) {
9339   default:
9340     llvm_unreachable("Unknown shuffle opcode!");
9341   case OP_VREV:
9342     // VREV divides the vector in half and swaps within the half.
9343     if (VT.getVectorElementType() == MVT::i32 ||
9344         VT.getVectorElementType() == MVT::f32)
9345       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
9346     // vrev <4 x i16> -> REV32
9347     if (VT.getVectorElementType() == MVT::i16 ||
9348         VT.getVectorElementType() == MVT::f16 ||
9349         VT.getVectorElementType() == MVT::bf16)
9350       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
9351     // vrev <4 x i8> -> REV16
9352     assert(VT.getVectorElementType() == MVT::i8);
9353     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
9354   case OP_VDUP0:
9355   case OP_VDUP1:
9356   case OP_VDUP2:
9357   case OP_VDUP3: {
9358     EVT EltTy = VT.getVectorElementType();
9359     unsigned Opcode;
9360     if (EltTy == MVT::i8)
9361       Opcode = AArch64ISD::DUPLANE8;
9362     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
9363       Opcode = AArch64ISD::DUPLANE16;
9364     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
9365       Opcode = AArch64ISD::DUPLANE32;
9366     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
9367       Opcode = AArch64ISD::DUPLANE64;
9368     else
9369       llvm_unreachable("Invalid vector element type?");
9370 
9371     if (VT.getSizeInBits() == 64)
9372       OpLHS = WidenVector(OpLHS, DAG);
9373     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
9374     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
9375   }
9376   case OP_VEXT1:
9377   case OP_VEXT2:
9378   case OP_VEXT3: {
9379     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
9380     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
9381                        DAG.getConstant(Imm, dl, MVT::i32));
9382   }
9383   case OP_VUZPL:
9384     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
9385                        OpRHS);
9386   case OP_VUZPR:
9387     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
9388                        OpRHS);
9389   case OP_VZIPL:
9390     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
9391                        OpRHS);
9392   case OP_VZIPR:
9393     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
9394                        OpRHS);
9395   case OP_VTRNL:
9396     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
9397                        OpRHS);
9398   case OP_VTRNR:
9399     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
9400                        OpRHS);
9401   }
9402 }
9403 
GenerateTBL(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)9404 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
9405                            SelectionDAG &DAG) {
9406   // Check to see if we can use the TBL instruction.
9407   SDValue V1 = Op.getOperand(0);
9408   SDValue V2 = Op.getOperand(1);
9409   SDLoc DL(Op);
9410 
9411   EVT EltVT = Op.getValueType().getVectorElementType();
9412   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
9413 
9414   SmallVector<SDValue, 8> TBLMask;
9415   for (int Val : ShuffleMask) {
9416     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
9417       unsigned Offset = Byte + Val * BytesPerElt;
9418       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
9419     }
9420   }
9421 
9422   MVT IndexVT = MVT::v8i8;
9423   unsigned IndexLen = 8;
9424   if (Op.getValueSizeInBits() == 128) {
9425     IndexVT = MVT::v16i8;
9426     IndexLen = 16;
9427   }
9428 
9429   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
9430   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
9431 
9432   SDValue Shuffle;
9433   if (V2.getNode()->isUndef()) {
9434     if (IndexLen == 8)
9435       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
9436     Shuffle = DAG.getNode(
9437         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9438         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
9439         DAG.getBuildVector(IndexVT, DL,
9440                            makeArrayRef(TBLMask.data(), IndexLen)));
9441   } else {
9442     if (IndexLen == 8) {
9443       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
9444       Shuffle = DAG.getNode(
9445           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9446           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
9447           DAG.getBuildVector(IndexVT, DL,
9448                              makeArrayRef(TBLMask.data(), IndexLen)));
9449     } else {
9450       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
9451       // cannot currently represent the register constraints on the input
9452       // table registers.
9453       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
9454       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
9455       //                   IndexLen));
9456       Shuffle = DAG.getNode(
9457           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9458           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
9459           V2Cst, DAG.getBuildVector(IndexVT, DL,
9460                                     makeArrayRef(TBLMask.data(), IndexLen)));
9461     }
9462   }
9463   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
9464 }
9465 
getDUPLANEOp(EVT EltType)9466 static unsigned getDUPLANEOp(EVT EltType) {
9467   if (EltType == MVT::i8)
9468     return AArch64ISD::DUPLANE8;
9469   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
9470     return AArch64ISD::DUPLANE16;
9471   if (EltType == MVT::i32 || EltType == MVT::f32)
9472     return AArch64ISD::DUPLANE32;
9473   if (EltType == MVT::i64 || EltType == MVT::f64)
9474     return AArch64ISD::DUPLANE64;
9475 
9476   llvm_unreachable("Invalid vector element type?");
9477 }
9478 
constructDup(SDValue V,int Lane,SDLoc dl,EVT VT,unsigned Opcode,SelectionDAG & DAG)9479 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
9480                             unsigned Opcode, SelectionDAG &DAG) {
9481   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
9482   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
9483     // Match: dup (bitcast (extract_subv X, C)), LaneC
9484     if (BitCast.getOpcode() != ISD::BITCAST ||
9485         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
9486       return false;
9487 
9488     // The extract index must align in the destination type. That may not
9489     // happen if the bitcast is from narrow to wide type.
9490     SDValue Extract = BitCast.getOperand(0);
9491     unsigned ExtIdx = Extract.getConstantOperandVal(1);
9492     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
9493     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
9494     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
9495     if (ExtIdxInBits % CastedEltBitWidth != 0)
9496       return false;
9497 
9498     // Update the lane value by offsetting with the scaled extract index.
9499     LaneC += ExtIdxInBits / CastedEltBitWidth;
9500 
9501     // Determine the casted vector type of the wide vector input.
9502     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
9503     // Examples:
9504     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
9505     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
9506     unsigned SrcVecNumElts =
9507         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
9508     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
9509                               SrcVecNumElts);
9510     return true;
9511   };
9512   MVT CastVT;
9513   if (getScaledOffsetDup(V, Lane, CastVT)) {
9514     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
9515   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9516     // The lane is incremented by the index of the extract.
9517     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
9518     Lane += V.getConstantOperandVal(1);
9519     V = V.getOperand(0);
9520   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
9521     // The lane is decremented if we are splatting from the 2nd operand.
9522     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
9523     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
9524     Lane -= Idx * VT.getVectorNumElements() / 2;
9525     V = WidenVector(V.getOperand(Idx), DAG);
9526   } else if (VT.getSizeInBits() == 64) {
9527     // Widen the operand to 128-bit register with undef.
9528     V = WidenVector(V, DAG);
9529   }
9530   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
9531 }
9532 
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG) const9533 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9534                                                    SelectionDAG &DAG) const {
9535   SDLoc dl(Op);
9536   EVT VT = Op.getValueType();
9537 
9538   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
9539 
9540   if (useSVEForFixedLengthVectorVT(VT))
9541     return LowerFixedLengthVECTOR_SHUFFLEToSVE(Op, DAG);
9542 
9543   // Convert shuffles that are directly supported on NEON to target-specific
9544   // DAG nodes, instead of keeping them as shuffles and matching them again
9545   // during code selection.  This is more efficient and avoids the possibility
9546   // of inconsistencies between legalization and selection.
9547   ArrayRef<int> ShuffleMask = SVN->getMask();
9548 
9549   SDValue V1 = Op.getOperand(0);
9550   SDValue V2 = Op.getOperand(1);
9551 
9552   assert(V1.getValueType() == VT && "Unexpected VECTOR_SHUFFLE type!");
9553   assert(ShuffleMask.size() == VT.getVectorNumElements() &&
9554          "Unexpected VECTOR_SHUFFLE mask size!");
9555 
9556   if (SVN->isSplat()) {
9557     int Lane = SVN->getSplatIndex();
9558     // If this is undef splat, generate it via "just" vdup, if possible.
9559     if (Lane == -1)
9560       Lane = 0;
9561 
9562     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
9563       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
9564                          V1.getOperand(0));
9565     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
9566     // constant. If so, we can just reference the lane's definition directly.
9567     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
9568         !isa<ConstantSDNode>(V1.getOperand(Lane)))
9569       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
9570 
9571     // Otherwise, duplicate from the lane of the input vector.
9572     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
9573     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
9574   }
9575 
9576   // Check if the mask matches a DUP for a wider element
9577   for (unsigned LaneSize : {64U, 32U, 16U}) {
9578     unsigned Lane = 0;
9579     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
9580       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
9581                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
9582                                                         : AArch64ISD::DUPLANE16;
9583       // Cast V1 to an integer vector with required lane size
9584       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
9585       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
9586       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
9587       V1 = DAG.getBitcast(NewVecTy, V1);
9588       // Constuct the DUP instruction
9589       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
9590       // Cast back to the original type
9591       return DAG.getBitcast(VT, V1);
9592     }
9593   }
9594 
9595   if (isREVMask(ShuffleMask, VT, 64))
9596     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
9597   if (isREVMask(ShuffleMask, VT, 32))
9598     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
9599   if (isREVMask(ShuffleMask, VT, 16))
9600     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
9601 
9602   if (((VT.getVectorNumElements() == 8 && VT.getScalarSizeInBits() == 16) ||
9603        (VT.getVectorNumElements() == 16 && VT.getScalarSizeInBits() == 8)) &&
9604       ShuffleVectorInst::isReverseMask(ShuffleMask)) {
9605     SDValue Rev = DAG.getNode(AArch64ISD::REV64, dl, VT, V1);
9606     return DAG.getNode(AArch64ISD::EXT, dl, VT, Rev, Rev,
9607                        DAG.getConstant(8, dl, MVT::i32));
9608   }
9609 
9610   bool ReverseEXT = false;
9611   unsigned Imm;
9612   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
9613     if (ReverseEXT)
9614       std::swap(V1, V2);
9615     Imm *= getExtFactor(V1);
9616     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
9617                        DAG.getConstant(Imm, dl, MVT::i32));
9618   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
9619     Imm *= getExtFactor(V1);
9620     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
9621                        DAG.getConstant(Imm, dl, MVT::i32));
9622   }
9623 
9624   unsigned WhichResult;
9625   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
9626     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
9627     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9628   }
9629   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
9630     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
9631     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9632   }
9633   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
9634     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
9635     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9636   }
9637 
9638   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9639     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
9640     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9641   }
9642   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9643     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
9644     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9645   }
9646   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9647     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
9648     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9649   }
9650 
9651   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
9652     return Concat;
9653 
9654   bool DstIsLeft;
9655   int Anomaly;
9656   int NumInputElements = V1.getValueType().getVectorNumElements();
9657   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
9658     SDValue DstVec = DstIsLeft ? V1 : V2;
9659     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
9660 
9661     SDValue SrcVec = V1;
9662     int SrcLane = ShuffleMask[Anomaly];
9663     if (SrcLane >= NumInputElements) {
9664       SrcVec = V2;
9665       SrcLane -= VT.getVectorNumElements();
9666     }
9667     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
9668 
9669     EVT ScalarVT = VT.getVectorElementType();
9670 
9671     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
9672       ScalarVT = MVT::i32;
9673 
9674     return DAG.getNode(
9675         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9676         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
9677         DstLaneV);
9678   }
9679 
9680   // If the shuffle is not directly supported and it has 4 elements, use
9681   // the PerfectShuffle-generated table to synthesize it from other shuffles.
9682   unsigned NumElts = VT.getVectorNumElements();
9683   if (NumElts == 4) {
9684     unsigned PFIndexes[4];
9685     for (unsigned i = 0; i != 4; ++i) {
9686       if (ShuffleMask[i] < 0)
9687         PFIndexes[i] = 8;
9688       else
9689         PFIndexes[i] = ShuffleMask[i];
9690     }
9691 
9692     // Compute the index in the perfect shuffle table.
9693     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
9694                             PFIndexes[2] * 9 + PFIndexes[3];
9695     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9696     unsigned Cost = (PFEntry >> 30);
9697 
9698     if (Cost <= 4)
9699       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9700   }
9701 
9702   return GenerateTBL(Op, ShuffleMask, DAG);
9703 }
9704 
LowerSPLAT_VECTOR(SDValue Op,SelectionDAG & DAG) const9705 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
9706                                                  SelectionDAG &DAG) const {
9707   SDLoc dl(Op);
9708   EVT VT = Op.getValueType();
9709   EVT ElemVT = VT.getScalarType();
9710   SDValue SplatVal = Op.getOperand(0);
9711 
9712   if (useSVEForFixedLengthVectorVT(VT))
9713     return LowerToScalableOp(Op, DAG);
9714 
9715   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
9716   // FPRs don't have this restriction.
9717   switch (ElemVT.getSimpleVT().SimpleTy) {
9718   case MVT::i1: {
9719     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
9720     // lowering code.
9721     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
9722       if (ConstVal->isZero())
9723         return SDValue(DAG.getMachineNode(AArch64::PFALSE, dl, VT), 0);
9724       if (ConstVal->isOne())
9725         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
9726     }
9727     // The general case of i1.  There isn't any natural way to do this,
9728     // so we use some trickery with whilelo.
9729     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
9730     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
9731                            DAG.getValueType(MVT::i1));
9732     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
9733                                        MVT::i64);
9734     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
9735                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
9736   }
9737   case MVT::i8:
9738   case MVT::i16:
9739   case MVT::i32:
9740     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
9741     break;
9742   case MVT::i64:
9743     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
9744     break;
9745   case MVT::f16:
9746   case MVT::bf16:
9747   case MVT::f32:
9748   case MVT::f64:
9749     // Fine as is
9750     break;
9751   default:
9752     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
9753   }
9754 
9755   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
9756 }
9757 
LowerDUPQLane(SDValue Op,SelectionDAG & DAG) const9758 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
9759                                              SelectionDAG &DAG) const {
9760   SDLoc DL(Op);
9761 
9762   EVT VT = Op.getValueType();
9763   if (!isTypeLegal(VT) || !VT.isScalableVector())
9764     return SDValue();
9765 
9766   // Current lowering only supports the SVE-ACLE types.
9767   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
9768     return SDValue();
9769 
9770   // The DUPQ operation is indepedent of element type so normalise to i64s.
9771   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
9772   SDValue Idx128 = Op.getOperand(2);
9773 
9774   // DUPQ can be used when idx is in range.
9775   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
9776   if (CIdx && (CIdx->getZExtValue() <= 3)) {
9777     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
9778     SDNode *DUPQ =
9779         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
9780     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
9781   }
9782 
9783   // The ACLE says this must produce the same result as:
9784   //   svtbl(data, svadd_x(svptrue_b64(),
9785   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
9786   //                       index * 2))
9787   SDValue One = DAG.getConstant(1, DL, MVT::i64);
9788   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
9789 
9790   // create the vector 0,1,0,1,...
9791   SDValue SV = DAG.getStepVector(DL, MVT::nxv2i64);
9792   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
9793 
9794   // create the vector idx64,idx64+1,idx64,idx64+1,...
9795   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
9796   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
9797   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
9798 
9799   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
9800   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
9801   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
9802 }
9803 
9804 
resolveBuildVector(BuildVectorSDNode * BVN,APInt & CnstBits,APInt & UndefBits)9805 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
9806                                APInt &UndefBits) {
9807   EVT VT = BVN->getValueType(0);
9808   APInt SplatBits, SplatUndef;
9809   unsigned SplatBitSize;
9810   bool HasAnyUndefs;
9811   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9812     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
9813 
9814     for (unsigned i = 0; i < NumSplats; ++i) {
9815       CnstBits <<= SplatBitSize;
9816       UndefBits <<= SplatBitSize;
9817       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
9818       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
9819     }
9820 
9821     return true;
9822   }
9823 
9824   return false;
9825 }
9826 
9827 // Try 64-bit splatted SIMD immediate.
tryAdvSIMDModImm64(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)9828 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9829                                  const APInt &Bits) {
9830   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9831     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9832     EVT VT = Op.getValueType();
9833     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
9834 
9835     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
9836       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
9837 
9838       SDLoc dl(Op);
9839       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9840                                 DAG.getConstant(Value, dl, MVT::i32));
9841       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9842     }
9843   }
9844 
9845   return SDValue();
9846 }
9847 
9848 // Try 32-bit splatted SIMD immediate.
tryAdvSIMDModImm32(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits,const SDValue * LHS=nullptr)9849 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9850                                   const APInt &Bits,
9851                                   const SDValue *LHS = nullptr) {
9852   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9853     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9854     EVT VT = Op.getValueType();
9855     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
9856     bool isAdvSIMDModImm = false;
9857     uint64_t Shift;
9858 
9859     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
9860       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
9861       Shift = 0;
9862     }
9863     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
9864       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
9865       Shift = 8;
9866     }
9867     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
9868       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
9869       Shift = 16;
9870     }
9871     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
9872       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
9873       Shift = 24;
9874     }
9875 
9876     if (isAdvSIMDModImm) {
9877       SDLoc dl(Op);
9878       SDValue Mov;
9879 
9880       if (LHS)
9881         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
9882                           DAG.getConstant(Value, dl, MVT::i32),
9883                           DAG.getConstant(Shift, dl, MVT::i32));
9884       else
9885         Mov = DAG.getNode(NewOp, dl, MovTy,
9886                           DAG.getConstant(Value, dl, MVT::i32),
9887                           DAG.getConstant(Shift, dl, MVT::i32));
9888 
9889       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9890     }
9891   }
9892 
9893   return SDValue();
9894 }
9895 
9896 // Try 16-bit splatted SIMD immediate.
tryAdvSIMDModImm16(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits,const SDValue * LHS=nullptr)9897 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9898                                   const APInt &Bits,
9899                                   const SDValue *LHS = nullptr) {
9900   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9901     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9902     EVT VT = Op.getValueType();
9903     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
9904     bool isAdvSIMDModImm = false;
9905     uint64_t Shift;
9906 
9907     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
9908       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
9909       Shift = 0;
9910     }
9911     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
9912       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
9913       Shift = 8;
9914     }
9915 
9916     if (isAdvSIMDModImm) {
9917       SDLoc dl(Op);
9918       SDValue Mov;
9919 
9920       if (LHS)
9921         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
9922                           DAG.getConstant(Value, dl, MVT::i32),
9923                           DAG.getConstant(Shift, dl, MVT::i32));
9924       else
9925         Mov = DAG.getNode(NewOp, dl, MovTy,
9926                           DAG.getConstant(Value, dl, MVT::i32),
9927                           DAG.getConstant(Shift, dl, MVT::i32));
9928 
9929       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9930     }
9931   }
9932 
9933   return SDValue();
9934 }
9935 
9936 // Try 32-bit splatted SIMD immediate with shifted ones.
tryAdvSIMDModImm321s(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)9937 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
9938                                     SelectionDAG &DAG, const APInt &Bits) {
9939   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9940     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9941     EVT VT = Op.getValueType();
9942     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
9943     bool isAdvSIMDModImm = false;
9944     uint64_t Shift;
9945 
9946     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
9947       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
9948       Shift = 264;
9949     }
9950     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
9951       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
9952       Shift = 272;
9953     }
9954 
9955     if (isAdvSIMDModImm) {
9956       SDLoc dl(Op);
9957       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9958                                 DAG.getConstant(Value, dl, MVT::i32),
9959                                 DAG.getConstant(Shift, dl, MVT::i32));
9960       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9961     }
9962   }
9963 
9964   return SDValue();
9965 }
9966 
9967 // Try 8-bit splatted SIMD immediate.
tryAdvSIMDModImm8(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)9968 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9969                                  const APInt &Bits) {
9970   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9971     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9972     EVT VT = Op.getValueType();
9973     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
9974 
9975     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
9976       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
9977 
9978       SDLoc dl(Op);
9979       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9980                                 DAG.getConstant(Value, dl, MVT::i32));
9981       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9982     }
9983   }
9984 
9985   return SDValue();
9986 }
9987 
9988 // Try FP splatted SIMD immediate.
tryAdvSIMDModImmFP(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)9989 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9990                                   const APInt &Bits) {
9991   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9992     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9993     EVT VT = Op.getValueType();
9994     bool isWide = (VT.getSizeInBits() == 128);
9995     MVT MovTy;
9996     bool isAdvSIMDModImm = false;
9997 
9998     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
9999       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
10000       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
10001     }
10002     else if (isWide &&
10003              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
10004       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
10005       MovTy = MVT::v2f64;
10006     }
10007 
10008     if (isAdvSIMDModImm) {
10009       SDLoc dl(Op);
10010       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10011                                 DAG.getConstant(Value, dl, MVT::i32));
10012       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10013     }
10014   }
10015 
10016   return SDValue();
10017 }
10018 
10019 // Specialized code to quickly find if PotentialBVec is a BuildVector that
10020 // consists of only the same constant int value, returned in reference arg
10021 // ConstVal
isAllConstantBuildVector(const SDValue & PotentialBVec,uint64_t & ConstVal)10022 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
10023                                      uint64_t &ConstVal) {
10024   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
10025   if (!Bvec)
10026     return false;
10027   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
10028   if (!FirstElt)
10029     return false;
10030   EVT VT = Bvec->getValueType(0);
10031   unsigned NumElts = VT.getVectorNumElements();
10032   for (unsigned i = 1; i < NumElts; ++i)
10033     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
10034       return false;
10035   ConstVal = FirstElt->getZExtValue();
10036   return true;
10037 }
10038 
getIntrinsicID(const SDNode * N)10039 static unsigned getIntrinsicID(const SDNode *N) {
10040   unsigned Opcode = N->getOpcode();
10041   switch (Opcode) {
10042   default:
10043     return Intrinsic::not_intrinsic;
10044   case ISD::INTRINSIC_WO_CHAIN: {
10045     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10046     if (IID < Intrinsic::num_intrinsics)
10047       return IID;
10048     return Intrinsic::not_intrinsic;
10049   }
10050   }
10051 }
10052 
10053 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
10054 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
10055 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
10056 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
10057 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
10058 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
tryLowerToSLI(SDNode * N,SelectionDAG & DAG)10059 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
10060   EVT VT = N->getValueType(0);
10061 
10062   if (!VT.isVector())
10063     return SDValue();
10064 
10065   SDLoc DL(N);
10066 
10067   SDValue And;
10068   SDValue Shift;
10069 
10070   SDValue FirstOp = N->getOperand(0);
10071   unsigned FirstOpc = FirstOp.getOpcode();
10072   SDValue SecondOp = N->getOperand(1);
10073   unsigned SecondOpc = SecondOp.getOpcode();
10074 
10075   // Is one of the operands an AND or a BICi? The AND may have been optimised to
10076   // a BICi in order to use an immediate instead of a register.
10077   // Is the other operand an shl or lshr? This will have been turned into:
10078   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
10079   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
10080       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
10081     And = FirstOp;
10082     Shift = SecondOp;
10083 
10084   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
10085              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
10086     And = SecondOp;
10087     Shift = FirstOp;
10088   } else
10089     return SDValue();
10090 
10091   bool IsAnd = And.getOpcode() == ISD::AND;
10092   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
10093 
10094   // Is the shift amount constant?
10095   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10096   if (!C2node)
10097     return SDValue();
10098 
10099   uint64_t C1;
10100   if (IsAnd) {
10101     // Is the and mask vector all constant?
10102     if (!isAllConstantBuildVector(And.getOperand(1), C1))
10103       return SDValue();
10104   } else {
10105     // Reconstruct the corresponding AND immediate from the two BICi immediates.
10106     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
10107     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
10108     assert(C1nodeImm && C1nodeShift);
10109     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
10110   }
10111 
10112   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
10113   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
10114   // how much one can shift elements of a particular size?
10115   uint64_t C2 = C2node->getZExtValue();
10116   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
10117   if (C2 > ElemSizeInBits)
10118     return SDValue();
10119 
10120   APInt C1AsAPInt(ElemSizeInBits, C1);
10121   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
10122                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
10123   if (C1AsAPInt != RequiredC1)
10124     return SDValue();
10125 
10126   SDValue X = And.getOperand(0);
10127   SDValue Y = Shift.getOperand(0);
10128 
10129   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
10130   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
10131 
10132   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
10133   LLVM_DEBUG(N->dump(&DAG));
10134   LLVM_DEBUG(dbgs() << "into: \n");
10135   LLVM_DEBUG(ResultSLI->dump(&DAG));
10136 
10137   ++NumShiftInserts;
10138   return ResultSLI;
10139 }
10140 
LowerVectorOR(SDValue Op,SelectionDAG & DAG) const10141 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
10142                                              SelectionDAG &DAG) const {
10143   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10144     return LowerToScalableOp(Op, DAG);
10145 
10146   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
10147   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
10148     return Res;
10149 
10150   EVT VT = Op.getValueType();
10151 
10152   SDValue LHS = Op.getOperand(0);
10153   BuildVectorSDNode *BVN =
10154       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
10155   if (!BVN) {
10156     // OR commutes, so try swapping the operands.
10157     LHS = Op.getOperand(1);
10158     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
10159   }
10160   if (!BVN)
10161     return Op;
10162 
10163   APInt DefBits(VT.getSizeInBits(), 0);
10164   APInt UndefBits(VT.getSizeInBits(), 0);
10165   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10166     SDValue NewOp;
10167 
10168     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
10169                                     DefBits, &LHS)) ||
10170         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
10171                                     DefBits, &LHS)))
10172       return NewOp;
10173 
10174     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
10175                                     UndefBits, &LHS)) ||
10176         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
10177                                     UndefBits, &LHS)))
10178       return NewOp;
10179   }
10180 
10181   // We can always fall back to a non-immediate OR.
10182   return Op;
10183 }
10184 
10185 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
10186 // be truncated to fit element width.
NormalizeBuildVector(SDValue Op,SelectionDAG & DAG)10187 static SDValue NormalizeBuildVector(SDValue Op,
10188                                     SelectionDAG &DAG) {
10189   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
10190   SDLoc dl(Op);
10191   EVT VT = Op.getValueType();
10192   EVT EltTy= VT.getVectorElementType();
10193 
10194   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
10195     return Op;
10196 
10197   SmallVector<SDValue, 16> Ops;
10198   for (SDValue Lane : Op->ops()) {
10199     // For integer vectors, type legalization would have promoted the
10200     // operands already. Otherwise, if Op is a floating-point splat
10201     // (with operands cast to integers), then the only possibilities
10202     // are constants and UNDEFs.
10203     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
10204       APInt LowBits(EltTy.getSizeInBits(),
10205                     CstLane->getZExtValue());
10206       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
10207     } else if (Lane.getNode()->isUndef()) {
10208       Lane = DAG.getUNDEF(MVT::i32);
10209     } else {
10210       assert(Lane.getValueType() == MVT::i32 &&
10211              "Unexpected BUILD_VECTOR operand type");
10212     }
10213     Ops.push_back(Lane);
10214   }
10215   return DAG.getBuildVector(VT, dl, Ops);
10216 }
10217 
ConstantBuildVector(SDValue Op,SelectionDAG & DAG)10218 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
10219   EVT VT = Op.getValueType();
10220 
10221   APInt DefBits(VT.getSizeInBits(), 0);
10222   APInt UndefBits(VT.getSizeInBits(), 0);
10223   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
10224   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10225     SDValue NewOp;
10226     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
10227         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10228         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
10229         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10230         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
10231         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
10232       return NewOp;
10233 
10234     DefBits = ~DefBits;
10235     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
10236         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
10237         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
10238       return NewOp;
10239 
10240     DefBits = UndefBits;
10241     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
10242         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10243         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
10244         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10245         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
10246         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
10247       return NewOp;
10248 
10249     DefBits = ~UndefBits;
10250     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
10251         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
10252         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
10253       return NewOp;
10254   }
10255 
10256   return SDValue();
10257 }
10258 
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const10259 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
10260                                                  SelectionDAG &DAG) const {
10261   EVT VT = Op.getValueType();
10262 
10263   // Try to build a simple constant vector.
10264   Op = NormalizeBuildVector(Op, DAG);
10265   if (VT.isInteger()) {
10266     // Certain vector constants, used to express things like logical NOT and
10267     // arithmetic NEG, are passed through unmodified.  This allows special
10268     // patterns for these operations to match, which will lower these constants
10269     // to whatever is proven necessary.
10270     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
10271     if (BVN->isConstant())
10272       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
10273         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
10274         APInt Val(BitSize,
10275                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
10276         if (Val.isZero() || Val.isAllOnes())
10277           return Op;
10278       }
10279   }
10280 
10281   if (SDValue V = ConstantBuildVector(Op, DAG))
10282     return V;
10283 
10284   // Scan through the operands to find some interesting properties we can
10285   // exploit:
10286   //   1) If only one value is used, we can use a DUP, or
10287   //   2) if only the low element is not undef, we can just insert that, or
10288   //   3) if only one constant value is used (w/ some non-constant lanes),
10289   //      we can splat the constant value into the whole vector then fill
10290   //      in the non-constant lanes.
10291   //   4) FIXME: If different constant values are used, but we can intelligently
10292   //             select the values we'll be overwriting for the non-constant
10293   //             lanes such that we can directly materialize the vector
10294   //             some other way (MOVI, e.g.), we can be sneaky.
10295   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
10296   SDLoc dl(Op);
10297   unsigned NumElts = VT.getVectorNumElements();
10298   bool isOnlyLowElement = true;
10299   bool usesOnlyOneValue = true;
10300   bool usesOnlyOneConstantValue = true;
10301   bool isConstant = true;
10302   bool AllLanesExtractElt = true;
10303   unsigned NumConstantLanes = 0;
10304   unsigned NumDifferentLanes = 0;
10305   unsigned NumUndefLanes = 0;
10306   SDValue Value;
10307   SDValue ConstantValue;
10308   for (unsigned i = 0; i < NumElts; ++i) {
10309     SDValue V = Op.getOperand(i);
10310     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10311       AllLanesExtractElt = false;
10312     if (V.isUndef()) {
10313       ++NumUndefLanes;
10314       continue;
10315     }
10316     if (i > 0)
10317       isOnlyLowElement = false;
10318     if (!isIntOrFPConstant(V))
10319       isConstant = false;
10320 
10321     if (isIntOrFPConstant(V)) {
10322       ++NumConstantLanes;
10323       if (!ConstantValue.getNode())
10324         ConstantValue = V;
10325       else if (ConstantValue != V)
10326         usesOnlyOneConstantValue = false;
10327     }
10328 
10329     if (!Value.getNode())
10330       Value = V;
10331     else if (V != Value) {
10332       usesOnlyOneValue = false;
10333       ++NumDifferentLanes;
10334     }
10335   }
10336 
10337   if (!Value.getNode()) {
10338     LLVM_DEBUG(
10339         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
10340     return DAG.getUNDEF(VT);
10341   }
10342 
10343   // Convert BUILD_VECTOR where all elements but the lowest are undef into
10344   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
10345   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
10346   if (isOnlyLowElement && !(NumElts == 1 && isIntOrFPConstant(Value))) {
10347     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
10348                          "SCALAR_TO_VECTOR node\n");
10349     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
10350   }
10351 
10352   if (AllLanesExtractElt) {
10353     SDNode *Vector = nullptr;
10354     bool Even = false;
10355     bool Odd = false;
10356     // Check whether the extract elements match the Even pattern <0,2,4,...> or
10357     // the Odd pattern <1,3,5,...>.
10358     for (unsigned i = 0; i < NumElts; ++i) {
10359       SDValue V = Op.getOperand(i);
10360       const SDNode *N = V.getNode();
10361       if (!isa<ConstantSDNode>(N->getOperand(1)))
10362         break;
10363       SDValue N0 = N->getOperand(0);
10364 
10365       // All elements are extracted from the same vector.
10366       if (!Vector) {
10367         Vector = N0.getNode();
10368         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
10369         // BUILD_VECTOR.
10370         if (VT.getVectorElementType() !=
10371             N0.getValueType().getVectorElementType())
10372           break;
10373       } else if (Vector != N0.getNode()) {
10374         Odd = false;
10375         Even = false;
10376         break;
10377       }
10378 
10379       // Extracted values are either at Even indices <0,2,4,...> or at Odd
10380       // indices <1,3,5,...>.
10381       uint64_t Val = N->getConstantOperandVal(1);
10382       if (Val == 2 * i) {
10383         Even = true;
10384         continue;
10385       }
10386       if (Val - 1 == 2 * i) {
10387         Odd = true;
10388         continue;
10389       }
10390 
10391       // Something does not match: abort.
10392       Odd = false;
10393       Even = false;
10394       break;
10395     }
10396     if (Even || Odd) {
10397       SDValue LHS =
10398           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
10399                       DAG.getConstant(0, dl, MVT::i64));
10400       SDValue RHS =
10401           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
10402                       DAG.getConstant(NumElts, dl, MVT::i64));
10403 
10404       if (Even && !Odd)
10405         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
10406                            RHS);
10407       if (Odd && !Even)
10408         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
10409                            RHS);
10410     }
10411   }
10412 
10413   // Use DUP for non-constant splats. For f32 constant splats, reduce to
10414   // i32 and try again.
10415   if (usesOnlyOneValue) {
10416     if (!isConstant) {
10417       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10418           Value.getValueType() != VT) {
10419         LLVM_DEBUG(
10420             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
10421         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
10422       }
10423 
10424       // This is actually a DUPLANExx operation, which keeps everything vectory.
10425 
10426       SDValue Lane = Value.getOperand(1);
10427       Value = Value.getOperand(0);
10428       if (Value.getValueSizeInBits() == 64) {
10429         LLVM_DEBUG(
10430             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
10431                       "widening it\n");
10432         Value = WidenVector(Value, DAG);
10433       }
10434 
10435       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
10436       return DAG.getNode(Opcode, dl, VT, Value, Lane);
10437     }
10438 
10439     if (VT.getVectorElementType().isFloatingPoint()) {
10440       SmallVector<SDValue, 8> Ops;
10441       EVT EltTy = VT.getVectorElementType();
10442       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
10443                EltTy == MVT::f64) && "Unsupported floating-point vector type");
10444       LLVM_DEBUG(
10445           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
10446                     "BITCASTS, and try again\n");
10447       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
10448       for (unsigned i = 0; i < NumElts; ++i)
10449         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
10450       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
10451       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
10452       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
10453                  Val.dump(););
10454       Val = LowerBUILD_VECTOR(Val, DAG);
10455       if (Val.getNode())
10456         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
10457     }
10458   }
10459 
10460   // If we need to insert a small number of different non-constant elements and
10461   // the vector width is sufficiently large, prefer using DUP with the common
10462   // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
10463   // skip the constant lane handling below.
10464   bool PreferDUPAndInsert =
10465       !isConstant && NumDifferentLanes >= 1 &&
10466       NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
10467       NumDifferentLanes >= NumConstantLanes;
10468 
10469   // If there was only one constant value used and for more than one lane,
10470   // start by splatting that value, then replace the non-constant lanes. This
10471   // is better than the default, which will perform a separate initialization
10472   // for each lane.
10473   if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
10474     // Firstly, try to materialize the splat constant.
10475     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
10476             Val = ConstantBuildVector(Vec, DAG);
10477     if (!Val) {
10478       // Otherwise, materialize the constant and splat it.
10479       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
10480       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
10481     }
10482 
10483     // Now insert the non-constant lanes.
10484     for (unsigned i = 0; i < NumElts; ++i) {
10485       SDValue V = Op.getOperand(i);
10486       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
10487       if (!isIntOrFPConstant(V))
10488         // Note that type legalization likely mucked about with the VT of the
10489         // source operand, so we may have to convert it here before inserting.
10490         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
10491     }
10492     return Val;
10493   }
10494 
10495   // This will generate a load from the constant pool.
10496   if (isConstant) {
10497     LLVM_DEBUG(
10498         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
10499                   "expansion\n");
10500     return SDValue();
10501   }
10502 
10503   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
10504   if (NumElts >= 4) {
10505     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
10506       return shuffle;
10507   }
10508 
10509   if (PreferDUPAndInsert) {
10510     // First, build a constant vector with the common element.
10511     SmallVector<SDValue, 8> Ops(NumElts, Value);
10512     SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
10513     // Next, insert the elements that do not match the common value.
10514     for (unsigned I = 0; I < NumElts; ++I)
10515       if (Op.getOperand(I) != Value)
10516         NewVector =
10517             DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
10518                         Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
10519 
10520     return NewVector;
10521   }
10522 
10523   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
10524   // know the default expansion would otherwise fall back on something even
10525   // worse. For a vector with one or two non-undef values, that's
10526   // scalar_to_vector for the elements followed by a shuffle (provided the
10527   // shuffle is valid for the target) and materialization element by element
10528   // on the stack followed by a load for everything else.
10529   if (!isConstant && !usesOnlyOneValue) {
10530     LLVM_DEBUG(
10531         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
10532                   "of INSERT_VECTOR_ELT\n");
10533 
10534     SDValue Vec = DAG.getUNDEF(VT);
10535     SDValue Op0 = Op.getOperand(0);
10536     unsigned i = 0;
10537 
10538     // Use SCALAR_TO_VECTOR for lane zero to
10539     // a) Avoid a RMW dependency on the full vector register, and
10540     // b) Allow the register coalescer to fold away the copy if the
10541     //    value is already in an S or D register, and we're forced to emit an
10542     //    INSERT_SUBREG that we can't fold anywhere.
10543     //
10544     // We also allow types like i8 and i16 which are illegal scalar but legal
10545     // vector element types. After type-legalization the inserted value is
10546     // extended (i32) and it is safe to cast them to the vector type by ignoring
10547     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
10548     if (!Op0.isUndef()) {
10549       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
10550       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
10551       ++i;
10552     }
10553     LLVM_DEBUG(if (i < NumElts) dbgs()
10554                    << "Creating nodes for the other vector elements:\n";);
10555     for (; i < NumElts; ++i) {
10556       SDValue V = Op.getOperand(i);
10557       if (V.isUndef())
10558         continue;
10559       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
10560       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
10561     }
10562     return Vec;
10563   }
10564 
10565   LLVM_DEBUG(
10566       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
10567                 "better alternative\n");
10568   return SDValue();
10569 }
10570 
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG) const10571 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
10572                                                    SelectionDAG &DAG) const {
10573   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10574     return LowerFixedLengthConcatVectorsToSVE(Op, DAG);
10575 
10576   assert(Op.getValueType().isScalableVector() &&
10577          isTypeLegal(Op.getValueType()) &&
10578          "Expected legal scalable vector type!");
10579 
10580   if (isTypeLegal(Op.getOperand(0).getValueType())) {
10581     unsigned NumOperands = Op->getNumOperands();
10582     assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
10583            "Unexpected number of operands in CONCAT_VECTORS");
10584 
10585     if (NumOperands == 2)
10586       return Op;
10587 
10588     // Concat each pair of subvectors and pack into the lower half of the array.
10589     SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
10590     while (ConcatOps.size() > 1) {
10591       for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
10592         SDValue V1 = ConcatOps[I];
10593         SDValue V2 = ConcatOps[I + 1];
10594         EVT SubVT = V1.getValueType();
10595         EVT PairVT = SubVT.getDoubleNumVectorElementsVT(*DAG.getContext());
10596         ConcatOps[I / 2] =
10597             DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), PairVT, V1, V2);
10598       }
10599       ConcatOps.resize(ConcatOps.size() / 2);
10600     }
10601     return ConcatOps[0];
10602   }
10603 
10604   return SDValue();
10605 }
10606 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const10607 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10608                                                       SelectionDAG &DAG) const {
10609   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
10610 
10611   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10612     return LowerFixedLengthInsertVectorElt(Op, DAG);
10613 
10614   // Check for non-constant or out of range lane.
10615   EVT VT = Op.getOperand(0).getValueType();
10616 
10617   if (VT.getScalarType() == MVT::i1) {
10618     EVT VectorVT = getPromotedVTForPredicate(VT);
10619     SDLoc DL(Op);
10620     SDValue ExtendedVector =
10621         DAG.getAnyExtOrTrunc(Op.getOperand(0), DL, VectorVT);
10622     SDValue ExtendedValue =
10623         DAG.getAnyExtOrTrunc(Op.getOperand(1), DL,
10624                              VectorVT.getScalarType().getSizeInBits() < 32
10625                                  ? MVT::i32
10626                                  : VectorVT.getScalarType());
10627     ExtendedVector =
10628         DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VectorVT, ExtendedVector,
10629                     ExtendedValue, Op.getOperand(2));
10630     return DAG.getAnyExtOrTrunc(ExtendedVector, DL, VT);
10631   }
10632 
10633   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10634   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
10635     return SDValue();
10636 
10637   // Insertion/extraction are legal for V128 types.
10638   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10639       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
10640       VT == MVT::v8f16 || VT == MVT::v8bf16)
10641     return Op;
10642 
10643   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
10644       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
10645       VT != MVT::v4bf16)
10646     return SDValue();
10647 
10648   // For V64 types, we perform insertion by expanding the value
10649   // to a V128 type and perform the insertion on that.
10650   SDLoc DL(Op);
10651   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
10652   EVT WideTy = WideVec.getValueType();
10653 
10654   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
10655                              Op.getOperand(1), Op.getOperand(2));
10656   // Re-narrow the resultant vector.
10657   return NarrowVector(Node, DAG);
10658 }
10659 
10660 SDValue
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const10661 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10662                                                SelectionDAG &DAG) const {
10663   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
10664   EVT VT = Op.getOperand(0).getValueType();
10665 
10666   if (VT.getScalarType() == MVT::i1) {
10667     // We can't directly extract from an SVE predicate; extend it first.
10668     // (This isn't the only possible lowering, but it's straightforward.)
10669     EVT VectorVT = getPromotedVTForPredicate(VT);
10670     SDLoc DL(Op);
10671     SDValue Extend =
10672         DAG.getNode(ISD::ANY_EXTEND, DL, VectorVT, Op.getOperand(0));
10673     MVT ExtractTy = VectorVT == MVT::nxv2i64 ? MVT::i64 : MVT::i32;
10674     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractTy,
10675                                   Extend, Op.getOperand(1));
10676     return DAG.getAnyExtOrTrunc(Extract, DL, Op.getValueType());
10677   }
10678 
10679   if (useSVEForFixedLengthVectorVT(VT))
10680     return LowerFixedLengthExtractVectorElt(Op, DAG);
10681 
10682   // Check for non-constant or out of range lane.
10683   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10684   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
10685     return SDValue();
10686 
10687   // Insertion/extraction are legal for V128 types.
10688   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10689       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
10690       VT == MVT::v8f16 || VT == MVT::v8bf16)
10691     return Op;
10692 
10693   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
10694       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
10695       VT != MVT::v4bf16)
10696     return SDValue();
10697 
10698   // For V64 types, we perform extraction by expanding the value
10699   // to a V128 type and perform the extraction on that.
10700   SDLoc DL(Op);
10701   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
10702   EVT WideTy = WideVec.getValueType();
10703 
10704   EVT ExtrTy = WideTy.getVectorElementType();
10705   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
10706     ExtrTy = MVT::i32;
10707 
10708   // For extractions, we just return the result directly.
10709   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
10710                      Op.getOperand(1));
10711 }
10712 
LowerEXTRACT_SUBVECTOR(SDValue Op,SelectionDAG & DAG) const10713 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
10714                                                       SelectionDAG &DAG) const {
10715   assert(Op.getValueType().isFixedLengthVector() &&
10716          "Only cases that extract a fixed length vector are supported!");
10717 
10718   EVT InVT = Op.getOperand(0).getValueType();
10719   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10720   unsigned Size = Op.getValueSizeInBits();
10721 
10722   // If we don't have legal types yet, do nothing
10723   if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
10724     return SDValue();
10725 
10726   if (InVT.isScalableVector()) {
10727     // This will be matched by custom code during ISelDAGToDAG.
10728     if (Idx == 0 && isPackedVectorType(InVT, DAG))
10729       return Op;
10730 
10731     return SDValue();
10732   }
10733 
10734   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
10735   if (Idx == 0 && InVT.getSizeInBits() <= 128)
10736     return Op;
10737 
10738   // If this is extracting the upper 64-bits of a 128-bit vector, we match
10739   // that directly.
10740   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
10741       InVT.getSizeInBits() == 128)
10742     return Op;
10743 
10744   if (useSVEForFixedLengthVectorVT(InVT)) {
10745     SDLoc DL(Op);
10746 
10747     EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
10748     SDValue NewInVec =
10749         convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
10750 
10751     SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ContainerVT, NewInVec,
10752                                  NewInVec, DAG.getConstant(Idx, DL, MVT::i64));
10753     return convertFromScalableVector(DAG, Op.getValueType(), Splice);
10754   }
10755 
10756   return SDValue();
10757 }
10758 
LowerINSERT_SUBVECTOR(SDValue Op,SelectionDAG & DAG) const10759 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
10760                                                      SelectionDAG &DAG) const {
10761   assert(Op.getValueType().isScalableVector() &&
10762          "Only expect to lower inserts into scalable vectors!");
10763 
10764   EVT InVT = Op.getOperand(1).getValueType();
10765   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10766 
10767   if (InVT.isScalableVector()) {
10768     SDLoc DL(Op);
10769     EVT VT = Op.getValueType();
10770 
10771     if (!isTypeLegal(VT) || !VT.isInteger())
10772       return SDValue();
10773 
10774     SDValue Vec0 = Op.getOperand(0);
10775     SDValue Vec1 = Op.getOperand(1);
10776 
10777     // Ensure the subvector is half the size of the main vector.
10778     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
10779       return SDValue();
10780 
10781     // Extend elements of smaller vector...
10782     EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
10783     SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
10784 
10785     if (Idx == 0) {
10786       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
10787       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
10788     } else if (Idx == InVT.getVectorMinNumElements()) {
10789       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
10790       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
10791     }
10792 
10793     return SDValue();
10794   }
10795 
10796   // This will be matched by custom code during ISelDAGToDAG.
10797   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
10798     return Op;
10799 
10800   return SDValue();
10801 }
10802 
LowerDIV(SDValue Op,SelectionDAG & DAG) const10803 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
10804   EVT VT = Op.getValueType();
10805 
10806   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
10807     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
10808 
10809   assert(VT.isScalableVector() && "Expected a scalable vector.");
10810 
10811   bool Signed = Op.getOpcode() == ISD::SDIV;
10812   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
10813 
10814   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
10815     return LowerToPredicatedOp(Op, DAG, PredOpcode);
10816 
10817   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
10818   // operations, and truncate the result.
10819   EVT WidenedVT;
10820   if (VT == MVT::nxv16i8)
10821     WidenedVT = MVT::nxv8i16;
10822   else if (VT == MVT::nxv8i16)
10823     WidenedVT = MVT::nxv4i32;
10824   else
10825     llvm_unreachable("Unexpected Custom DIV operation");
10826 
10827   SDLoc dl(Op);
10828   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
10829   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
10830   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
10831   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
10832   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
10833   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
10834   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
10835   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
10836   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
10837 }
10838 
isShuffleMaskLegal(ArrayRef<int> M,EVT VT) const10839 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
10840   // Currently no fixed length shuffles that require SVE are legal.
10841   if (useSVEForFixedLengthVectorVT(VT))
10842     return false;
10843 
10844   if (VT.getVectorNumElements() == 4 &&
10845       (VT.is128BitVector() || VT.is64BitVector())) {
10846     unsigned PFIndexes[4];
10847     for (unsigned i = 0; i != 4; ++i) {
10848       if (M[i] < 0)
10849         PFIndexes[i] = 8;
10850       else
10851         PFIndexes[i] = M[i];
10852     }
10853 
10854     // Compute the index in the perfect shuffle table.
10855     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10856                             PFIndexes[2] * 9 + PFIndexes[3];
10857     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10858     unsigned Cost = (PFEntry >> 30);
10859 
10860     if (Cost <= 4)
10861       return true;
10862   }
10863 
10864   bool DummyBool;
10865   int DummyInt;
10866   unsigned DummyUnsigned;
10867 
10868   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
10869           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
10870           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
10871           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
10872           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
10873           isZIPMask(M, VT, DummyUnsigned) ||
10874           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
10875           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
10876           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
10877           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
10878           isConcatMask(M, VT, VT.getSizeInBits() == 128));
10879 }
10880 
10881 /// getVShiftImm - Check if this is a valid build_vector for the immediate
10882 /// operand of a vector shift operation, where all the elements of the
10883 /// build_vector must have the same constant integer value.
getVShiftImm(SDValue Op,unsigned ElementBits,int64_t & Cnt)10884 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10885   // Ignore bit_converts.
10886   while (Op.getOpcode() == ISD::BITCAST)
10887     Op = Op.getOperand(0);
10888   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10889   APInt SplatBits, SplatUndef;
10890   unsigned SplatBitSize;
10891   bool HasAnyUndefs;
10892   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10893                                     HasAnyUndefs, ElementBits) ||
10894       SplatBitSize > ElementBits)
10895     return false;
10896   Cnt = SplatBits.getSExtValue();
10897   return true;
10898 }
10899 
10900 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10901 /// operand of a vector shift left operation.  That value must be in the range:
10902 ///   0 <= Value < ElementBits for a left shift; or
10903 ///   0 <= Value <= ElementBits for a long left shift.
isVShiftLImm(SDValue Op,EVT VT,bool isLong,int64_t & Cnt)10904 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10905   assert(VT.isVector() && "vector shift count is not a vector type");
10906   int64_t ElementBits = VT.getScalarSizeInBits();
10907   if (!getVShiftImm(Op, ElementBits, Cnt))
10908     return false;
10909   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
10910 }
10911 
10912 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10913 /// operand of a vector shift right operation. The value must be in the range:
10914 ///   1 <= Value <= ElementBits for a right shift; or
isVShiftRImm(SDValue Op,EVT VT,bool isNarrow,int64_t & Cnt)10915 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
10916   assert(VT.isVector() && "vector shift count is not a vector type");
10917   int64_t ElementBits = VT.getScalarSizeInBits();
10918   if (!getVShiftImm(Op, ElementBits, Cnt))
10919     return false;
10920   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
10921 }
10922 
LowerTRUNCATE(SDValue Op,SelectionDAG & DAG) const10923 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
10924                                              SelectionDAG &DAG) const {
10925   EVT VT = Op.getValueType();
10926 
10927   if (VT.getScalarType() == MVT::i1) {
10928     // Lower i1 truncate to `(x & 1) != 0`.
10929     SDLoc dl(Op);
10930     EVT OpVT = Op.getOperand(0).getValueType();
10931     SDValue Zero = DAG.getConstant(0, dl, OpVT);
10932     SDValue One = DAG.getConstant(1, dl, OpVT);
10933     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
10934     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
10935   }
10936 
10937   if (!VT.isVector() || VT.isScalableVector())
10938     return SDValue();
10939 
10940   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
10941     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
10942 
10943   return SDValue();
10944 }
10945 
LowerVectorSRA_SRL_SHL(SDValue Op,SelectionDAG & DAG) const10946 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
10947                                                       SelectionDAG &DAG) const {
10948   EVT VT = Op.getValueType();
10949   SDLoc DL(Op);
10950   int64_t Cnt;
10951 
10952   if (!Op.getOperand(1).getValueType().isVector())
10953     return Op;
10954   unsigned EltSize = VT.getScalarSizeInBits();
10955 
10956   switch (Op.getOpcode()) {
10957   default:
10958     llvm_unreachable("unexpected shift opcode");
10959 
10960   case ISD::SHL:
10961     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
10962       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
10963 
10964     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
10965       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
10966                          DAG.getConstant(Cnt, DL, MVT::i32));
10967     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10968                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
10969                                        MVT::i32),
10970                        Op.getOperand(0), Op.getOperand(1));
10971   case ISD::SRA:
10972   case ISD::SRL:
10973     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
10974       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
10975                                                 : AArch64ISD::SRL_PRED;
10976       return LowerToPredicatedOp(Op, DAG, Opc);
10977     }
10978 
10979     // Right shift immediate
10980     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
10981       unsigned Opc =
10982           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
10983       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
10984                          DAG.getConstant(Cnt, DL, MVT::i32));
10985     }
10986 
10987     // Right shift register.  Note, there is not a shift right register
10988     // instruction, but the shift left register instruction takes a signed
10989     // value, where negative numbers specify a right shift.
10990     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
10991                                                 : Intrinsic::aarch64_neon_ushl;
10992     // negate the shift amount
10993     SDValue NegShift = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
10994                                    Op.getOperand(1));
10995     SDValue NegShiftLeft =
10996         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10997                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
10998                     NegShift);
10999     return NegShiftLeft;
11000   }
11001 
11002   return SDValue();
11003 }
11004 
EmitVectorComparison(SDValue LHS,SDValue RHS,AArch64CC::CondCode CC,bool NoNans,EVT VT,const SDLoc & dl,SelectionDAG & DAG)11005 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
11006                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
11007                                     const SDLoc &dl, SelectionDAG &DAG) {
11008   EVT SrcVT = LHS.getValueType();
11009   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
11010          "function only supposed to emit natural comparisons");
11011 
11012   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
11013   APInt CnstBits(VT.getSizeInBits(), 0);
11014   APInt UndefBits(VT.getSizeInBits(), 0);
11015   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
11016   bool IsZero = IsCnst && (CnstBits == 0);
11017 
11018   if (SrcVT.getVectorElementType().isFloatingPoint()) {
11019     switch (CC) {
11020     default:
11021       return SDValue();
11022     case AArch64CC::NE: {
11023       SDValue Fcmeq;
11024       if (IsZero)
11025         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
11026       else
11027         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
11028       return DAG.getNOT(dl, Fcmeq, VT);
11029     }
11030     case AArch64CC::EQ:
11031       if (IsZero)
11032         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
11033       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
11034     case AArch64CC::GE:
11035       if (IsZero)
11036         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
11037       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
11038     case AArch64CC::GT:
11039       if (IsZero)
11040         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
11041       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
11042     case AArch64CC::LS:
11043       if (IsZero)
11044         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
11045       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
11046     case AArch64CC::LT:
11047       if (!NoNans)
11048         return SDValue();
11049       // If we ignore NaNs then we can use to the MI implementation.
11050       LLVM_FALLTHROUGH;
11051     case AArch64CC::MI:
11052       if (IsZero)
11053         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
11054       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
11055     }
11056   }
11057 
11058   switch (CC) {
11059   default:
11060     return SDValue();
11061   case AArch64CC::NE: {
11062     SDValue Cmeq;
11063     if (IsZero)
11064       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
11065     else
11066       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
11067     return DAG.getNOT(dl, Cmeq, VT);
11068   }
11069   case AArch64CC::EQ:
11070     if (IsZero)
11071       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
11072     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
11073   case AArch64CC::GE:
11074     if (IsZero)
11075       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
11076     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
11077   case AArch64CC::GT:
11078     if (IsZero)
11079       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
11080     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
11081   case AArch64CC::LE:
11082     if (IsZero)
11083       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
11084     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
11085   case AArch64CC::LS:
11086     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
11087   case AArch64CC::LO:
11088     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
11089   case AArch64CC::LT:
11090     if (IsZero)
11091       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
11092     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
11093   case AArch64CC::HI:
11094     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
11095   case AArch64CC::HS:
11096     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
11097   }
11098 }
11099 
LowerVSETCC(SDValue Op,SelectionDAG & DAG) const11100 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
11101                                            SelectionDAG &DAG) const {
11102   if (Op.getValueType().isScalableVector())
11103     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
11104 
11105   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
11106     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
11107 
11108   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11109   SDValue LHS = Op.getOperand(0);
11110   SDValue RHS = Op.getOperand(1);
11111   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
11112   SDLoc dl(Op);
11113 
11114   if (LHS.getValueType().getVectorElementType().isInteger()) {
11115     assert(LHS.getValueType() == RHS.getValueType());
11116     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
11117     SDValue Cmp =
11118         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
11119     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
11120   }
11121 
11122   const bool FullFP16 =
11123     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
11124 
11125   // Make v4f16 (only) fcmp operations utilise vector instructions
11126   // v8f16 support will be a litle more complicated
11127   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
11128     if (LHS.getValueType().getVectorNumElements() == 4) {
11129       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
11130       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
11131       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
11132       DAG.ReplaceAllUsesWith(Op, NewSetcc);
11133       CmpVT = MVT::v4i32;
11134     } else
11135       return SDValue();
11136   }
11137 
11138   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
11139           LHS.getValueType().getVectorElementType() != MVT::f128);
11140 
11141   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
11142   // clean.  Some of them require two branches to implement.
11143   AArch64CC::CondCode CC1, CC2;
11144   bool ShouldInvert;
11145   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
11146 
11147   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
11148   SDValue Cmp =
11149       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
11150   if (!Cmp.getNode())
11151     return SDValue();
11152 
11153   if (CC2 != AArch64CC::AL) {
11154     SDValue Cmp2 =
11155         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
11156     if (!Cmp2.getNode())
11157       return SDValue();
11158 
11159     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
11160   }
11161 
11162   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
11163 
11164   if (ShouldInvert)
11165     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
11166 
11167   return Cmp;
11168 }
11169 
getReductionSDNode(unsigned Op,SDLoc DL,SDValue ScalarOp,SelectionDAG & DAG)11170 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
11171                                   SelectionDAG &DAG) {
11172   SDValue VecOp = ScalarOp.getOperand(0);
11173   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
11174   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
11175                      DAG.getConstant(0, DL, MVT::i64));
11176 }
11177 
LowerVECREDUCE(SDValue Op,SelectionDAG & DAG) const11178 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
11179                                               SelectionDAG &DAG) const {
11180   SDValue Src = Op.getOperand(0);
11181 
11182   // Try to lower fixed length reductions to SVE.
11183   EVT SrcVT = Src.getValueType();
11184   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
11185                       Op.getOpcode() == ISD::VECREDUCE_OR ||
11186                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
11187                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
11188                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
11189                        SrcVT.getVectorElementType() == MVT::i64);
11190   if (SrcVT.isScalableVector() ||
11191       useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
11192 
11193     if (SrcVT.getVectorElementType() == MVT::i1)
11194       return LowerPredReductionToSVE(Op, DAG);
11195 
11196     switch (Op.getOpcode()) {
11197     case ISD::VECREDUCE_ADD:
11198       return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
11199     case ISD::VECREDUCE_AND:
11200       return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
11201     case ISD::VECREDUCE_OR:
11202       return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
11203     case ISD::VECREDUCE_SMAX:
11204       return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
11205     case ISD::VECREDUCE_SMIN:
11206       return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
11207     case ISD::VECREDUCE_UMAX:
11208       return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
11209     case ISD::VECREDUCE_UMIN:
11210       return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
11211     case ISD::VECREDUCE_XOR:
11212       return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
11213     case ISD::VECREDUCE_FADD:
11214       return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
11215     case ISD::VECREDUCE_FMAX:
11216       return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
11217     case ISD::VECREDUCE_FMIN:
11218       return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
11219     default:
11220       llvm_unreachable("Unhandled fixed length reduction");
11221     }
11222   }
11223 
11224   // Lower NEON reductions.
11225   SDLoc dl(Op);
11226   switch (Op.getOpcode()) {
11227   case ISD::VECREDUCE_ADD:
11228     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
11229   case ISD::VECREDUCE_SMAX:
11230     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
11231   case ISD::VECREDUCE_SMIN:
11232     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
11233   case ISD::VECREDUCE_UMAX:
11234     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
11235   case ISD::VECREDUCE_UMIN:
11236     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
11237   case ISD::VECREDUCE_FMAX: {
11238     return DAG.getNode(
11239         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
11240         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
11241         Src);
11242   }
11243   case ISD::VECREDUCE_FMIN: {
11244     return DAG.getNode(
11245         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
11246         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
11247         Src);
11248   }
11249   default:
11250     llvm_unreachable("Unhandled reduction");
11251   }
11252 }
11253 
LowerATOMIC_LOAD_SUB(SDValue Op,SelectionDAG & DAG) const11254 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
11255                                                     SelectionDAG &DAG) const {
11256   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
11257   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
11258     return SDValue();
11259 
11260   // LSE has an atomic load-add instruction, but not a load-sub.
11261   SDLoc dl(Op);
11262   MVT VT = Op.getSimpleValueType();
11263   SDValue RHS = Op.getOperand(2);
11264   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
11265   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
11266   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
11267                        Op.getOperand(0), Op.getOperand(1), RHS,
11268                        AN->getMemOperand());
11269 }
11270 
LowerATOMIC_LOAD_AND(SDValue Op,SelectionDAG & DAG) const11271 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
11272                                                     SelectionDAG &DAG) const {
11273   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
11274   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
11275     return SDValue();
11276 
11277   // LSE has an atomic load-clear instruction, but not a load-and.
11278   SDLoc dl(Op);
11279   MVT VT = Op.getSimpleValueType();
11280   SDValue RHS = Op.getOperand(2);
11281   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
11282   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
11283   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
11284                        Op.getOperand(0), Op.getOperand(1), RHS,
11285                        AN->getMemOperand());
11286 }
11287 
LowerWindowsDYNAMIC_STACKALLOC(SDValue Op,SDValue Chain,SDValue & Size,SelectionDAG & DAG) const11288 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
11289     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
11290   SDLoc dl(Op);
11291   EVT PtrVT = getPointerTy(DAG.getDataLayout());
11292   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
11293 
11294   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11295   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
11296   if (Subtarget->hasCustomCallingConv())
11297     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
11298 
11299   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
11300                      DAG.getConstant(4, dl, MVT::i64));
11301   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
11302   Chain =
11303       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
11304                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
11305                   DAG.getRegisterMask(Mask), Chain.getValue(1));
11306   // To match the actual intent better, we should read the output from X15 here
11307   // again (instead of potentially spilling it to the stack), but rereading Size
11308   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
11309   // here.
11310 
11311   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
11312                      DAG.getConstant(4, dl, MVT::i64));
11313   return Chain;
11314 }
11315 
11316 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const11317 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11318                                                SelectionDAG &DAG) const {
11319   assert(Subtarget->isTargetWindows() &&
11320          "Only Windows alloca probing supported");
11321   SDLoc dl(Op);
11322   // Get the inputs.
11323   SDNode *Node = Op.getNode();
11324   SDValue Chain = Op.getOperand(0);
11325   SDValue Size = Op.getOperand(1);
11326   MaybeAlign Align =
11327       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
11328   EVT VT = Node->getValueType(0);
11329 
11330   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
11331           "no-stack-arg-probe")) {
11332     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
11333     Chain = SP.getValue(1);
11334     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
11335     if (Align)
11336       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11337                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
11338     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
11339     SDValue Ops[2] = {SP, Chain};
11340     return DAG.getMergeValues(Ops, dl);
11341   }
11342 
11343   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
11344 
11345   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
11346 
11347   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
11348   Chain = SP.getValue(1);
11349   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
11350   if (Align)
11351     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11352                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
11353   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
11354 
11355   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
11356                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
11357 
11358   SDValue Ops[2] = {SP, Chain};
11359   return DAG.getMergeValues(Ops, dl);
11360 }
11361 
LowerVSCALE(SDValue Op,SelectionDAG & DAG) const11362 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
11363                                            SelectionDAG &DAG) const {
11364   EVT VT = Op.getValueType();
11365   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
11366 
11367   SDLoc DL(Op);
11368   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
11369   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
11370                             DL, VT);
11371 }
11372 
11373 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
11374 template <unsigned NumVecs>
11375 static bool
setInfoSVEStN(const AArch64TargetLowering & TLI,const DataLayout & DL,AArch64TargetLowering::IntrinsicInfo & Info,const CallInst & CI)11376 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
11377               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
11378   Info.opc = ISD::INTRINSIC_VOID;
11379   // Retrieve EC from first vector argument.
11380   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
11381   ElementCount EC = VT.getVectorElementCount();
11382 #ifndef NDEBUG
11383   // Check the assumption that all input vectors are the same type.
11384   for (unsigned I = 0; I < NumVecs; ++I)
11385     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
11386            "Invalid type.");
11387 #endif
11388   // memVT is `NumVecs * VT`.
11389   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
11390                                 EC * NumVecs);
11391   Info.ptrVal = CI.getArgOperand(CI.arg_size() - 1);
11392   Info.offset = 0;
11393   Info.align.reset();
11394   Info.flags = MachineMemOperand::MOStore;
11395   return true;
11396 }
11397 
11398 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11399 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11400 /// specified in the intrinsic calls.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const11401 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11402                                                const CallInst &I,
11403                                                MachineFunction &MF,
11404                                                unsigned Intrinsic) const {
11405   auto &DL = I.getModule()->getDataLayout();
11406   switch (Intrinsic) {
11407   case Intrinsic::aarch64_sve_st2:
11408     return setInfoSVEStN<2>(*this, DL, Info, I);
11409   case Intrinsic::aarch64_sve_st3:
11410     return setInfoSVEStN<3>(*this, DL, Info, I);
11411   case Intrinsic::aarch64_sve_st4:
11412     return setInfoSVEStN<4>(*this, DL, Info, I);
11413   case Intrinsic::aarch64_neon_ld2:
11414   case Intrinsic::aarch64_neon_ld3:
11415   case Intrinsic::aarch64_neon_ld4:
11416   case Intrinsic::aarch64_neon_ld1x2:
11417   case Intrinsic::aarch64_neon_ld1x3:
11418   case Intrinsic::aarch64_neon_ld1x4:
11419   case Intrinsic::aarch64_neon_ld2lane:
11420   case Intrinsic::aarch64_neon_ld3lane:
11421   case Intrinsic::aarch64_neon_ld4lane:
11422   case Intrinsic::aarch64_neon_ld2r:
11423   case Intrinsic::aarch64_neon_ld3r:
11424   case Intrinsic::aarch64_neon_ld4r: {
11425     Info.opc = ISD::INTRINSIC_W_CHAIN;
11426     // Conservatively set memVT to the entire set of vectors loaded.
11427     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11428     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11429     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
11430     Info.offset = 0;
11431     Info.align.reset();
11432     // volatile loads with NEON intrinsics not supported
11433     Info.flags = MachineMemOperand::MOLoad;
11434     return true;
11435   }
11436   case Intrinsic::aarch64_neon_st2:
11437   case Intrinsic::aarch64_neon_st3:
11438   case Intrinsic::aarch64_neon_st4:
11439   case Intrinsic::aarch64_neon_st1x2:
11440   case Intrinsic::aarch64_neon_st1x3:
11441   case Intrinsic::aarch64_neon_st1x4:
11442   case Intrinsic::aarch64_neon_st2lane:
11443   case Intrinsic::aarch64_neon_st3lane:
11444   case Intrinsic::aarch64_neon_st4lane: {
11445     Info.opc = ISD::INTRINSIC_VOID;
11446     // Conservatively set memVT to the entire set of vectors stored.
11447     unsigned NumElts = 0;
11448     for (const Value *Arg : I.args()) {
11449       Type *ArgTy = Arg->getType();
11450       if (!ArgTy->isVectorTy())
11451         break;
11452       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11453     }
11454     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11455     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
11456     Info.offset = 0;
11457     Info.align.reset();
11458     // volatile stores with NEON intrinsics not supported
11459     Info.flags = MachineMemOperand::MOStore;
11460     return true;
11461   }
11462   case Intrinsic::aarch64_ldaxr:
11463   case Intrinsic::aarch64_ldxr: {
11464     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11465     Info.opc = ISD::INTRINSIC_W_CHAIN;
11466     Info.memVT = MVT::getVT(PtrTy->getElementType());
11467     Info.ptrVal = I.getArgOperand(0);
11468     Info.offset = 0;
11469     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11470     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
11471     return true;
11472   }
11473   case Intrinsic::aarch64_stlxr:
11474   case Intrinsic::aarch64_stxr: {
11475     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11476     Info.opc = ISD::INTRINSIC_W_CHAIN;
11477     Info.memVT = MVT::getVT(PtrTy->getElementType());
11478     Info.ptrVal = I.getArgOperand(1);
11479     Info.offset = 0;
11480     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11481     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
11482     return true;
11483   }
11484   case Intrinsic::aarch64_ldaxp:
11485   case Intrinsic::aarch64_ldxp:
11486     Info.opc = ISD::INTRINSIC_W_CHAIN;
11487     Info.memVT = MVT::i128;
11488     Info.ptrVal = I.getArgOperand(0);
11489     Info.offset = 0;
11490     Info.align = Align(16);
11491     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
11492     return true;
11493   case Intrinsic::aarch64_stlxp:
11494   case Intrinsic::aarch64_stxp:
11495     Info.opc = ISD::INTRINSIC_W_CHAIN;
11496     Info.memVT = MVT::i128;
11497     Info.ptrVal = I.getArgOperand(2);
11498     Info.offset = 0;
11499     Info.align = Align(16);
11500     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
11501     return true;
11502   case Intrinsic::aarch64_sve_ldnt1: {
11503     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11504     Info.opc = ISD::INTRINSIC_W_CHAIN;
11505     Info.memVT = MVT::getVT(I.getType());
11506     Info.ptrVal = I.getArgOperand(1);
11507     Info.offset = 0;
11508     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11509     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
11510     return true;
11511   }
11512   case Intrinsic::aarch64_sve_stnt1: {
11513     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
11514     Info.opc = ISD::INTRINSIC_W_CHAIN;
11515     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
11516     Info.ptrVal = I.getArgOperand(2);
11517     Info.offset = 0;
11518     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11519     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
11520     return true;
11521   }
11522   default:
11523     break;
11524   }
11525 
11526   return false;
11527 }
11528 
shouldReduceLoadWidth(SDNode * Load,ISD::LoadExtType ExtTy,EVT NewVT) const11529 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
11530                                                   ISD::LoadExtType ExtTy,
11531                                                   EVT NewVT) const {
11532   // TODO: This may be worth removing. Check regression tests for diffs.
11533   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
11534     return false;
11535 
11536   // If we're reducing the load width in order to avoid having to use an extra
11537   // instruction to do extension then it's probably a good idea.
11538   if (ExtTy != ISD::NON_EXTLOAD)
11539     return true;
11540   // Don't reduce load width if it would prevent us from combining a shift into
11541   // the offset.
11542   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
11543   assert(Mem);
11544   const SDValue &Base = Mem->getBasePtr();
11545   if (Base.getOpcode() == ISD::ADD &&
11546       Base.getOperand(1).getOpcode() == ISD::SHL &&
11547       Base.getOperand(1).hasOneUse() &&
11548       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
11549     // The shift can be combined if it matches the size of the value being
11550     // loaded (and so reducing the width would make it not match).
11551     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
11552     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
11553     if (ShiftAmount == Log2_32(LoadBytes))
11554       return false;
11555   }
11556   // We have no reason to disallow reducing the load width, so allow it.
11557   return true;
11558 }
11559 
11560 // Truncations from 64-bit GPR to 32-bit GPR is free.
isTruncateFree(Type * Ty1,Type * Ty2) const11561 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11562   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11563     return false;
11564   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
11565   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
11566   return NumBits1 > NumBits2;
11567 }
isTruncateFree(EVT VT1,EVT VT2) const11568 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11569   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
11570     return false;
11571   uint64_t NumBits1 = VT1.getFixedSizeInBits();
11572   uint64_t NumBits2 = VT2.getFixedSizeInBits();
11573   return NumBits1 > NumBits2;
11574 }
11575 
11576 /// Check if it is profitable to hoist instruction in then/else to if.
11577 /// Not profitable if I and it's user can form a FMA instruction
11578 /// because we prefer FMSUB/FMADD.
isProfitableToHoist(Instruction * I) const11579 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
11580   if (I->getOpcode() != Instruction::FMul)
11581     return true;
11582 
11583   if (!I->hasOneUse())
11584     return true;
11585 
11586   Instruction *User = I->user_back();
11587 
11588   if (User &&
11589       !(User->getOpcode() == Instruction::FSub ||
11590         User->getOpcode() == Instruction::FAdd))
11591     return true;
11592 
11593   const TargetOptions &Options = getTargetMachine().Options;
11594   const Function *F = I->getFunction();
11595   const DataLayout &DL = F->getParent()->getDataLayout();
11596   Type *Ty = User->getOperand(0)->getType();
11597 
11598   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
11599            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
11600            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
11601             Options.UnsafeFPMath));
11602 }
11603 
11604 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
11605 // 64-bit GPR.
isZExtFree(Type * Ty1,Type * Ty2) const11606 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11607   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11608     return false;
11609   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11610   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11611   return NumBits1 == 32 && NumBits2 == 64;
11612 }
isZExtFree(EVT VT1,EVT VT2) const11613 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11614   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
11615     return false;
11616   unsigned NumBits1 = VT1.getSizeInBits();
11617   unsigned NumBits2 = VT2.getSizeInBits();
11618   return NumBits1 == 32 && NumBits2 == 64;
11619 }
11620 
isZExtFree(SDValue Val,EVT VT2) const11621 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11622   EVT VT1 = Val.getValueType();
11623   if (isZExtFree(VT1, VT2)) {
11624     return true;
11625   }
11626 
11627   if (Val.getOpcode() != ISD::LOAD)
11628     return false;
11629 
11630   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
11631   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
11632           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
11633           VT1.getSizeInBits() <= 32);
11634 }
11635 
isExtFreeImpl(const Instruction * Ext) const11636 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
11637   if (isa<FPExtInst>(Ext))
11638     return false;
11639 
11640   // Vector types are not free.
11641   if (Ext->getType()->isVectorTy())
11642     return false;
11643 
11644   for (const Use &U : Ext->uses()) {
11645     // The extension is free if we can fold it with a left shift in an
11646     // addressing mode or an arithmetic operation: add, sub, and cmp.
11647 
11648     // Is there a shift?
11649     const Instruction *Instr = cast<Instruction>(U.getUser());
11650 
11651     // Is this a constant shift?
11652     switch (Instr->getOpcode()) {
11653     case Instruction::Shl:
11654       if (!isa<ConstantInt>(Instr->getOperand(1)))
11655         return false;
11656       break;
11657     case Instruction::GetElementPtr: {
11658       gep_type_iterator GTI = gep_type_begin(Instr);
11659       auto &DL = Ext->getModule()->getDataLayout();
11660       std::advance(GTI, U.getOperandNo()-1);
11661       Type *IdxTy = GTI.getIndexedType();
11662       // This extension will end up with a shift because of the scaling factor.
11663       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
11664       // Get the shift amount based on the scaling factor:
11665       // log2(sizeof(IdxTy)) - log2(8).
11666       uint64_t ShiftAmt =
11667         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
11668       // Is the constant foldable in the shift of the addressing mode?
11669       // I.e., shift amount is between 1 and 4 inclusive.
11670       if (ShiftAmt == 0 || ShiftAmt > 4)
11671         return false;
11672       break;
11673     }
11674     case Instruction::Trunc:
11675       // Check if this is a noop.
11676       // trunc(sext ty1 to ty2) to ty1.
11677       if (Instr->getType() == Ext->getOperand(0)->getType())
11678         continue;
11679       LLVM_FALLTHROUGH;
11680     default:
11681       return false;
11682     }
11683 
11684     // At this point we can use the bfm family, so this extension is free
11685     // for that use.
11686   }
11687   return true;
11688 }
11689 
11690 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
11691 /// or upper half of the vector elements.
areExtractShuffleVectors(Value * Op1,Value * Op2)11692 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
11693   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
11694     auto *FullTy = FullV->getType();
11695     auto *HalfTy = HalfV->getType();
11696     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
11697            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
11698   };
11699 
11700   auto extractHalf = [](Value *FullV, Value *HalfV) {
11701     auto *FullVT = cast<FixedVectorType>(FullV->getType());
11702     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
11703     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
11704   };
11705 
11706   ArrayRef<int> M1, M2;
11707   Value *S1Op1, *S2Op1;
11708   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
11709       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
11710     return false;
11711 
11712   // Check that the operands are half as wide as the result and we extract
11713   // half of the elements of the input vectors.
11714   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
11715       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
11716     return false;
11717 
11718   // Check the mask extracts either the lower or upper half of vector
11719   // elements.
11720   int M1Start = -1;
11721   int M2Start = -1;
11722   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
11723   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
11724       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
11725       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
11726     return false;
11727 
11728   return true;
11729 }
11730 
11731 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
11732 /// of the vector elements.
areExtractExts(Value * Ext1,Value * Ext2)11733 static bool areExtractExts(Value *Ext1, Value *Ext2) {
11734   auto areExtDoubled = [](Instruction *Ext) {
11735     return Ext->getType()->getScalarSizeInBits() ==
11736            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
11737   };
11738 
11739   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
11740       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
11741       !areExtDoubled(cast<Instruction>(Ext1)) ||
11742       !areExtDoubled(cast<Instruction>(Ext2)))
11743     return false;
11744 
11745   return true;
11746 }
11747 
11748 /// Check if Op could be used with vmull_high_p64 intrinsic.
isOperandOfVmullHighP64(Value * Op)11749 static bool isOperandOfVmullHighP64(Value *Op) {
11750   Value *VectorOperand = nullptr;
11751   ConstantInt *ElementIndex = nullptr;
11752   return match(Op, m_ExtractElt(m_Value(VectorOperand),
11753                                 m_ConstantInt(ElementIndex))) &&
11754          ElementIndex->getValue() == 1 &&
11755          isa<FixedVectorType>(VectorOperand->getType()) &&
11756          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
11757 }
11758 
11759 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
areOperandsOfVmullHighP64(Value * Op1,Value * Op2)11760 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
11761   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
11762 }
11763 
11764 /// Check if sinking \p I's operands to I's basic block is profitable, because
11765 /// the operands can be folded into a target instruction, e.g.
11766 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
shouldSinkOperands(Instruction * I,SmallVectorImpl<Use * > & Ops) const11767 bool AArch64TargetLowering::shouldSinkOperands(
11768     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
11769   if (!I->getType()->isVectorTy())
11770     return false;
11771 
11772   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
11773     switch (II->getIntrinsicID()) {
11774     case Intrinsic::aarch64_neon_umull:
11775       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
11776         return false;
11777       Ops.push_back(&II->getOperandUse(0));
11778       Ops.push_back(&II->getOperandUse(1));
11779       return true;
11780 
11781     case Intrinsic::aarch64_neon_pmull64:
11782       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
11783                                      II->getArgOperand(1)))
11784         return false;
11785       Ops.push_back(&II->getArgOperandUse(0));
11786       Ops.push_back(&II->getArgOperandUse(1));
11787       return true;
11788 
11789     default:
11790       return false;
11791     }
11792   }
11793 
11794   switch (I->getOpcode()) {
11795   case Instruction::Sub:
11796   case Instruction::Add: {
11797     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
11798       return false;
11799 
11800     // If the exts' operands extract either the lower or upper elements, we
11801     // can sink them too.
11802     auto Ext1 = cast<Instruction>(I->getOperand(0));
11803     auto Ext2 = cast<Instruction>(I->getOperand(1));
11804     if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
11805       Ops.push_back(&Ext1->getOperandUse(0));
11806       Ops.push_back(&Ext2->getOperandUse(0));
11807     }
11808 
11809     Ops.push_back(&I->getOperandUse(0));
11810     Ops.push_back(&I->getOperandUse(1));
11811 
11812     return true;
11813   }
11814   case Instruction::Mul: {
11815     bool IsProfitable = false;
11816     for (auto &Op : I->operands()) {
11817       // Make sure we are not already sinking this operand
11818       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
11819         continue;
11820 
11821       ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
11822       if (!Shuffle || !Shuffle->isZeroEltSplat())
11823         continue;
11824 
11825       Value *ShuffleOperand = Shuffle->getOperand(0);
11826       InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
11827       if (!Insert)
11828         continue;
11829 
11830       Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
11831       if (!OperandInstr)
11832         continue;
11833 
11834       ConstantInt *ElementConstant =
11835           dyn_cast<ConstantInt>(Insert->getOperand(2));
11836       // Check that the insertelement is inserting into element 0
11837       if (!ElementConstant || ElementConstant->getZExtValue() != 0)
11838         continue;
11839 
11840       unsigned Opcode = OperandInstr->getOpcode();
11841       if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
11842         continue;
11843 
11844       Ops.push_back(&Shuffle->getOperandUse(0));
11845       Ops.push_back(&Op);
11846       IsProfitable = true;
11847     }
11848 
11849     return IsProfitable;
11850   }
11851   default:
11852     return false;
11853   }
11854   return false;
11855 }
11856 
hasPairedLoad(EVT LoadedType,Align & RequiredAligment) const11857 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
11858                                           Align &RequiredAligment) const {
11859   if (!LoadedType.isSimple() ||
11860       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
11861     return false;
11862   // Cyclone supports unaligned accesses.
11863   RequiredAligment = Align(1);
11864   unsigned NumBits = LoadedType.getSizeInBits();
11865   return NumBits == 32 || NumBits == 64;
11866 }
11867 
11868 /// A helper function for determining the number of interleaved accesses we
11869 /// will generate when lowering accesses of the given type.
11870 unsigned
getNumInterleavedAccesses(VectorType * VecTy,const DataLayout & DL) const11871 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
11872                                                  const DataLayout &DL) const {
11873   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
11874 }
11875 
11876 MachineMemOperand::Flags
getTargetMMOFlags(const Instruction & I) const11877 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
11878   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
11879       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
11880     return MOStridedAccess;
11881   return MachineMemOperand::MONone;
11882 }
11883 
isLegalInterleavedAccessType(VectorType * VecTy,const DataLayout & DL) const11884 bool AArch64TargetLowering::isLegalInterleavedAccessType(
11885     VectorType *VecTy, const DataLayout &DL) const {
11886 
11887   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
11888   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
11889 
11890   // Ensure the number of vector elements is greater than 1.
11891   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
11892     return false;
11893 
11894   // Ensure the element type is legal.
11895   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
11896     return false;
11897 
11898   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
11899   // 128 will be split into multiple interleaved accesses.
11900   return VecSize == 64 || VecSize % 128 == 0;
11901 }
11902 
11903 /// Lower an interleaved load into a ldN intrinsic.
11904 ///
11905 /// E.g. Lower an interleaved load (Factor = 2):
11906 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
11907 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11908 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11909 ///
11910 ///      Into:
11911 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
11912 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
11913 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
lowerInterleavedLoad(LoadInst * LI,ArrayRef<ShuffleVectorInst * > Shuffles,ArrayRef<unsigned> Indices,unsigned Factor) const11914 bool AArch64TargetLowering::lowerInterleavedLoad(
11915     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11916     ArrayRef<unsigned> Indices, unsigned Factor) const {
11917   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11918          "Invalid interleave factor");
11919   assert(!Shuffles.empty() && "Empty shufflevector input");
11920   assert(Shuffles.size() == Indices.size() &&
11921          "Unmatched number of shufflevectors and indices");
11922 
11923   const DataLayout &DL = LI->getModule()->getDataLayout();
11924 
11925   VectorType *VTy = Shuffles[0]->getType();
11926 
11927   // Skip if we do not have NEON and skip illegal vector types. We can
11928   // "legalize" wide vector types into multiple interleaved accesses as long as
11929   // the vector types are divisible by 128.
11930   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
11931     return false;
11932 
11933   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
11934 
11935   auto *FVTy = cast<FixedVectorType>(VTy);
11936 
11937   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11938   // load integer vectors first and then convert to pointer vectors.
11939   Type *EltTy = FVTy->getElementType();
11940   if (EltTy->isPointerTy())
11941     FVTy =
11942         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
11943 
11944   IRBuilder<> Builder(LI);
11945 
11946   // The base address of the load.
11947   Value *BaseAddr = LI->getPointerOperand();
11948 
11949   if (NumLoads > 1) {
11950     // If we're going to generate more than one load, reset the sub-vector type
11951     // to something legal.
11952     FVTy = FixedVectorType::get(FVTy->getElementType(),
11953                                 FVTy->getNumElements() / NumLoads);
11954 
11955     // We will compute the pointer operand of each load from the original base
11956     // address using GEPs. Cast the base address to a pointer to the scalar
11957     // element type.
11958     BaseAddr = Builder.CreateBitCast(
11959         BaseAddr,
11960         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
11961   }
11962 
11963   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
11964   Type *Tys[2] = {FVTy, PtrTy};
11965   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
11966                                             Intrinsic::aarch64_neon_ld3,
11967                                             Intrinsic::aarch64_neon_ld4};
11968   Function *LdNFunc =
11969       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11970 
11971   // Holds sub-vectors extracted from the load intrinsic return values. The
11972   // sub-vectors are associated with the shufflevector instructions they will
11973   // replace.
11974   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
11975 
11976   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
11977 
11978     // If we're generating more than one load, compute the base address of
11979     // subsequent loads as an offset from the previous.
11980     if (LoadCount > 0)
11981       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
11982                                             FVTy->getNumElements() * Factor);
11983 
11984     CallInst *LdN = Builder.CreateCall(
11985         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
11986 
11987     // Extract and store the sub-vectors returned by the load intrinsic.
11988     for (unsigned i = 0; i < Shuffles.size(); i++) {
11989       ShuffleVectorInst *SVI = Shuffles[i];
11990       unsigned Index = Indices[i];
11991 
11992       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
11993 
11994       // Convert the integer vector to pointer vector if the element is pointer.
11995       if (EltTy->isPointerTy())
11996         SubVec = Builder.CreateIntToPtr(
11997             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
11998                                          FVTy->getNumElements()));
11999       SubVecs[SVI].push_back(SubVec);
12000     }
12001   }
12002 
12003   // Replace uses of the shufflevector instructions with the sub-vectors
12004   // returned by the load intrinsic. If a shufflevector instruction is
12005   // associated with more than one sub-vector, those sub-vectors will be
12006   // concatenated into a single wide vector.
12007   for (ShuffleVectorInst *SVI : Shuffles) {
12008     auto &SubVec = SubVecs[SVI];
12009     auto *WideVec =
12010         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
12011     SVI->replaceAllUsesWith(WideVec);
12012   }
12013 
12014   return true;
12015 }
12016 
12017 /// Lower an interleaved store into a stN intrinsic.
12018 ///
12019 /// E.g. Lower an interleaved store (Factor = 3):
12020 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12021 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12022 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
12023 ///
12024 ///      Into:
12025 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12026 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12027 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12028 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
12029 ///
12030 /// Note that the new shufflevectors will be removed and we'll only generate one
12031 /// st3 instruction in CodeGen.
12032 ///
12033 /// Example for a more general valid mask (Factor 3). Lower:
12034 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
12035 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
12036 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
12037 ///
12038 ///      Into:
12039 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
12040 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
12041 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
12042 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
lowerInterleavedStore(StoreInst * SI,ShuffleVectorInst * SVI,unsigned Factor) const12043 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
12044                                                   ShuffleVectorInst *SVI,
12045                                                   unsigned Factor) const {
12046   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12047          "Invalid interleave factor");
12048 
12049   auto *VecTy = cast<FixedVectorType>(SVI->getType());
12050   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
12051 
12052   unsigned LaneLen = VecTy->getNumElements() / Factor;
12053   Type *EltTy = VecTy->getElementType();
12054   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
12055 
12056   const DataLayout &DL = SI->getModule()->getDataLayout();
12057 
12058   // Skip if we do not have NEON and skip illegal vector types. We can
12059   // "legalize" wide vector types into multiple interleaved accesses as long as
12060   // the vector types are divisible by 128.
12061   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
12062     return false;
12063 
12064   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
12065 
12066   Value *Op0 = SVI->getOperand(0);
12067   Value *Op1 = SVI->getOperand(1);
12068   IRBuilder<> Builder(SI);
12069 
12070   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12071   // vectors to integer vectors.
12072   if (EltTy->isPointerTy()) {
12073     Type *IntTy = DL.getIntPtrType(EltTy);
12074     unsigned NumOpElts =
12075         cast<FixedVectorType>(Op0->getType())->getNumElements();
12076 
12077     // Convert to the corresponding integer vector.
12078     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
12079     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12080     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12081 
12082     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
12083   }
12084 
12085   // The base address of the store.
12086   Value *BaseAddr = SI->getPointerOperand();
12087 
12088   if (NumStores > 1) {
12089     // If we're going to generate more than one store, reset the lane length
12090     // and sub-vector type to something legal.
12091     LaneLen /= NumStores;
12092     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
12093 
12094     // We will compute the pointer operand of each store from the original base
12095     // address using GEPs. Cast the base address to a pointer to the scalar
12096     // element type.
12097     BaseAddr = Builder.CreateBitCast(
12098         BaseAddr,
12099         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
12100   }
12101 
12102   auto Mask = SVI->getShuffleMask();
12103 
12104   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
12105   Type *Tys[2] = {SubVecTy, PtrTy};
12106   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
12107                                              Intrinsic::aarch64_neon_st3,
12108                                              Intrinsic::aarch64_neon_st4};
12109   Function *StNFunc =
12110       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
12111 
12112   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
12113 
12114     SmallVector<Value *, 5> Ops;
12115 
12116     // Split the shufflevector operands into sub vectors for the new stN call.
12117     for (unsigned i = 0; i < Factor; i++) {
12118       unsigned IdxI = StoreCount * LaneLen * Factor + i;
12119       if (Mask[IdxI] >= 0) {
12120         Ops.push_back(Builder.CreateShuffleVector(
12121             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
12122       } else {
12123         unsigned StartMask = 0;
12124         for (unsigned j = 1; j < LaneLen; j++) {
12125           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
12126           if (Mask[IdxJ * Factor + IdxI] >= 0) {
12127             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
12128             break;
12129           }
12130         }
12131         // Note: Filling undef gaps with random elements is ok, since
12132         // those elements were being written anyway (with undefs).
12133         // In the case of all undefs we're defaulting to using elems from 0
12134         // Note: StartMask cannot be negative, it's checked in
12135         // isReInterleaveMask
12136         Ops.push_back(Builder.CreateShuffleVector(
12137             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
12138       }
12139     }
12140 
12141     // If we generating more than one store, we compute the base address of
12142     // subsequent stores as an offset from the previous.
12143     if (StoreCount > 0)
12144       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
12145                                             BaseAddr, LaneLen * Factor);
12146 
12147     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
12148     Builder.CreateCall(StNFunc, Ops);
12149   }
12150   return true;
12151 }
12152 
12153 // Lower an SVE structured load intrinsic returning a tuple type to target
12154 // specific intrinsic taking the same input but returning a multi-result value
12155 // of the split tuple type.
12156 //
12157 // E.g. Lowering an LD3:
12158 //
12159 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
12160 //                                                    <vscale x 4 x i1> %pred,
12161 //                                                    <vscale x 4 x i32>* %addr)
12162 //
12163 //  Output DAG:
12164 //
12165 //    t0: ch = EntryToken
12166 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
12167 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
12168 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
12169 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
12170 //
12171 // This is called pre-legalization to avoid widening/splitting issues with
12172 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
LowerSVEStructLoad(unsigned Intrinsic,ArrayRef<SDValue> LoadOps,EVT VT,SelectionDAG & DAG,const SDLoc & DL) const12173 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
12174                                                   ArrayRef<SDValue> LoadOps,
12175                                                   EVT VT, SelectionDAG &DAG,
12176                                                   const SDLoc &DL) const {
12177   assert(VT.isScalableVector() && "Can only lower scalable vectors");
12178 
12179   unsigned N, Opcode;
12180   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
12181       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
12182       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
12183       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
12184 
12185   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
12186   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
12187          "invalid tuple vector type!");
12188 
12189   EVT SplitVT =
12190       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
12191                        VT.getVectorElementCount().divideCoefficientBy(N));
12192   assert(isTypeLegal(SplitVT));
12193 
12194   SmallVector<EVT, 5> VTs(N, SplitVT);
12195   VTs.push_back(MVT::Other); // Chain
12196   SDVTList NodeTys = DAG.getVTList(VTs);
12197 
12198   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
12199   SmallVector<SDValue, 4> PseudoLoadOps;
12200   for (unsigned I = 0; I < N; ++I)
12201     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
12202   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
12203 }
12204 
getOptimalMemOpType(const MemOp & Op,const AttributeList & FuncAttributes) const12205 EVT AArch64TargetLowering::getOptimalMemOpType(
12206     const MemOp &Op, const AttributeList &FuncAttributes) const {
12207   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
12208   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
12209   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
12210   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
12211   // taken one instruction to materialize the v2i64 zero and one store (with
12212   // restrictive addressing mode). Just do i64 stores.
12213   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
12214   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
12215     if (Op.isAligned(AlignCheck))
12216       return true;
12217     bool Fast;
12218     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
12219                                           MachineMemOperand::MONone, &Fast) &&
12220            Fast;
12221   };
12222 
12223   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
12224       AlignmentIsAcceptable(MVT::v16i8, Align(16)))
12225     return MVT::v16i8;
12226   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
12227     return MVT::f128;
12228   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
12229     return MVT::i64;
12230   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
12231     return MVT::i32;
12232   return MVT::Other;
12233 }
12234 
getOptimalMemOpLLT(const MemOp & Op,const AttributeList & FuncAttributes) const12235 LLT AArch64TargetLowering::getOptimalMemOpLLT(
12236     const MemOp &Op, const AttributeList &FuncAttributes) const {
12237   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
12238   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
12239   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
12240   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
12241   // taken one instruction to materialize the v2i64 zero and one store (with
12242   // restrictive addressing mode). Just do i64 stores.
12243   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
12244   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
12245     if (Op.isAligned(AlignCheck))
12246       return true;
12247     bool Fast;
12248     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
12249                                           MachineMemOperand::MONone, &Fast) &&
12250            Fast;
12251   };
12252 
12253   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
12254       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
12255     return LLT::fixed_vector(2, 64);
12256   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
12257     return LLT::scalar(128);
12258   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
12259     return LLT::scalar(64);
12260   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
12261     return LLT::scalar(32);
12262   return LLT();
12263 }
12264 
12265 // 12-bit optionally shifted immediates are legal for adds.
isLegalAddImmediate(int64_t Immed) const12266 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
12267   if (Immed == std::numeric_limits<int64_t>::min()) {
12268     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
12269                       << ": avoid UB for INT64_MIN\n");
12270     return false;
12271   }
12272   // Same encoding for add/sub, just flip the sign.
12273   Immed = std::abs(Immed);
12274   bool IsLegal = ((Immed >> 12) == 0 ||
12275                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
12276   LLVM_DEBUG(dbgs() << "Is " << Immed
12277                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
12278   return IsLegal;
12279 }
12280 
12281 // Return false to prevent folding
12282 // (mul (add x, c1), c2) -> (add (mul x, c2), c2*c1) in DAGCombine,
12283 // if the folding leads to worse code.
isMulAddWithConstProfitable(const SDValue & AddNode,const SDValue & ConstNode) const12284 bool AArch64TargetLowering::isMulAddWithConstProfitable(
12285     const SDValue &AddNode, const SDValue &ConstNode) const {
12286   // Let the DAGCombiner decide for vector types and large types.
12287   const EVT VT = AddNode.getValueType();
12288   if (VT.isVector() || VT.getScalarSizeInBits() > 64)
12289     return true;
12290 
12291   // It is worse if c1 is legal add immediate, while c1*c2 is not
12292   // and has to be composed by at least two instructions.
12293   const ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12294   const ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12295   const int64_t C1 = C1Node->getSExtValue();
12296   const APInt C1C2 = C1Node->getAPIntValue() * C2Node->getAPIntValue();
12297   if (!isLegalAddImmediate(C1) || isLegalAddImmediate(C1C2.getSExtValue()))
12298     return true;
12299   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
12300   AArch64_IMM::expandMOVImm(C1C2.getZExtValue(), VT.getSizeInBits(), Insn);
12301   if (Insn.size() > 1)
12302     return false;
12303 
12304   // Default to true and let the DAGCombiner decide.
12305   return true;
12306 }
12307 
12308 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
12309 // immediates is the same as for an add or a sub.
isLegalICmpImmediate(int64_t Immed) const12310 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
12311   return isLegalAddImmediate(Immed);
12312 }
12313 
12314 /// isLegalAddressingMode - Return true if the addressing mode represented
12315 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const12316 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
12317                                                   const AddrMode &AM, Type *Ty,
12318                                                   unsigned AS, Instruction *I) const {
12319   // AArch64 has five basic addressing modes:
12320   //  reg
12321   //  reg + 9-bit signed offset
12322   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
12323   //  reg1 + reg2
12324   //  reg + SIZE_IN_BYTES * reg
12325 
12326   // No global is ever allowed as a base.
12327   if (AM.BaseGV)
12328     return false;
12329 
12330   // No reg+reg+imm addressing.
12331   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
12332     return false;
12333 
12334   // FIXME: Update this method to support scalable addressing modes.
12335   if (isa<ScalableVectorType>(Ty)) {
12336     uint64_t VecElemNumBytes =
12337         DL.getTypeSizeInBits(cast<VectorType>(Ty)->getElementType()) / 8;
12338     return AM.HasBaseReg && !AM.BaseOffs &&
12339            (AM.Scale == 0 || (uint64_t)AM.Scale == VecElemNumBytes);
12340   }
12341 
12342   // check reg + imm case:
12343   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
12344   uint64_t NumBytes = 0;
12345   if (Ty->isSized()) {
12346     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
12347     NumBytes = NumBits / 8;
12348     if (!isPowerOf2_64(NumBits))
12349       NumBytes = 0;
12350   }
12351 
12352   if (!AM.Scale) {
12353     int64_t Offset = AM.BaseOffs;
12354 
12355     // 9-bit signed offset
12356     if (isInt<9>(Offset))
12357       return true;
12358 
12359     // 12-bit unsigned offset
12360     unsigned shift = Log2_64(NumBytes);
12361     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
12362         // Must be a multiple of NumBytes (NumBytes is a power of 2)
12363         (Offset >> shift) << shift == Offset)
12364       return true;
12365     return false;
12366   }
12367 
12368   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
12369 
12370   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
12371 }
12372 
shouldConsiderGEPOffsetSplit() const12373 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
12374   // Consider splitting large offset of struct or array.
12375   return true;
12376 }
12377 
getScalingFactorCost(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const12378 InstructionCost AArch64TargetLowering::getScalingFactorCost(
12379     const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const {
12380   // Scaling factors are not free at all.
12381   // Operands                     | Rt Latency
12382   // -------------------------------------------
12383   // Rt, [Xn, Xm]                 | 4
12384   // -------------------------------------------
12385   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
12386   // Rt, [Xn, Wm, <extend> #imm]  |
12387   if (isLegalAddressingMode(DL, AM, Ty, AS))
12388     // Scale represents reg2 * scale, thus account for 1 if
12389     // it is not equal to 0 or 1.
12390     return AM.Scale != 0 && AM.Scale != 1;
12391   return -1;
12392 }
12393 
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const12394 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
12395     const MachineFunction &MF, EVT VT) const {
12396   VT = VT.getScalarType();
12397 
12398   if (!VT.isSimple())
12399     return false;
12400 
12401   switch (VT.getSimpleVT().SimpleTy) {
12402   case MVT::f16:
12403     return Subtarget->hasFullFP16();
12404   case MVT::f32:
12405   case MVT::f64:
12406     return true;
12407   default:
12408     break;
12409   }
12410 
12411   return false;
12412 }
12413 
isFMAFasterThanFMulAndFAdd(const Function & F,Type * Ty) const12414 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
12415                                                        Type *Ty) const {
12416   switch (Ty->getScalarType()->getTypeID()) {
12417   case Type::FloatTyID:
12418   case Type::DoubleTyID:
12419     return true;
12420   default:
12421     return false;
12422   }
12423 }
12424 
generateFMAsInMachineCombiner(EVT VT,CodeGenOpt::Level OptLevel) const12425 bool AArch64TargetLowering::generateFMAsInMachineCombiner(
12426     EVT VT, CodeGenOpt::Level OptLevel) const {
12427   return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector();
12428 }
12429 
12430 const MCPhysReg *
getScratchRegisters(CallingConv::ID) const12431 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
12432   // LR is a callee-save register, but we must treat it as clobbered by any call
12433   // site. Hence we include LR in the scratch registers, which are in turn added
12434   // as implicit-defs for stackmaps and patchpoints.
12435   static const MCPhysReg ScratchRegs[] = {
12436     AArch64::X16, AArch64::X17, AArch64::LR, 0
12437   };
12438   return ScratchRegs;
12439 }
12440 
12441 bool
isDesirableToCommuteWithShift(const SDNode * N,CombineLevel Level) const12442 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
12443                                                      CombineLevel Level) const {
12444   N = N->getOperand(0).getNode();
12445   EVT VT = N->getValueType(0);
12446     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
12447     // it with shift to let it be lowered to UBFX.
12448   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
12449       isa<ConstantSDNode>(N->getOperand(1))) {
12450     uint64_t TruncMask = N->getConstantOperandVal(1);
12451     if (isMask_64(TruncMask) &&
12452       N->getOperand(0).getOpcode() == ISD::SRL &&
12453       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
12454       return false;
12455   }
12456   return true;
12457 }
12458 
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const12459 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12460                                                               Type *Ty) const {
12461   assert(Ty->isIntegerTy());
12462 
12463   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12464   if (BitSize == 0)
12465     return false;
12466 
12467   int64_t Val = Imm.getSExtValue();
12468   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
12469     return true;
12470 
12471   if ((int64_t)Val < 0)
12472     Val = ~Val;
12473   if (BitSize == 32)
12474     Val &= (1LL << 32) - 1;
12475 
12476   unsigned LZ = countLeadingZeros((uint64_t)Val);
12477   unsigned Shift = (63 - LZ) / 16;
12478   // MOVZ is free so return true for one or fewer MOVK.
12479   return Shift < 3;
12480 }
12481 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const12482 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
12483                                                     unsigned Index) const {
12484   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
12485     return false;
12486 
12487   return (Index == 0 || Index == ResVT.getVectorNumElements());
12488 }
12489 
12490 /// Turn vector tests of the signbit in the form of:
12491 ///   xor (sra X, elt_size(X)-1), -1
12492 /// into:
12493 ///   cmge X, X, #0
foldVectorXorShiftIntoCmp(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)12494 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
12495                                          const AArch64Subtarget *Subtarget) {
12496   EVT VT = N->getValueType(0);
12497   if (!Subtarget->hasNEON() || !VT.isVector())
12498     return SDValue();
12499 
12500   // There must be a shift right algebraic before the xor, and the xor must be a
12501   // 'not' operation.
12502   SDValue Shift = N->getOperand(0);
12503   SDValue Ones = N->getOperand(1);
12504   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
12505       !ISD::isBuildVectorAllOnes(Ones.getNode()))
12506     return SDValue();
12507 
12508   // The shift should be smearing the sign bit across each vector element.
12509   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
12510   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
12511   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
12512     return SDValue();
12513 
12514   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
12515 }
12516 
12517 // Given a vecreduce_add node, detect the below pattern and convert it to the
12518 // node sequence with UABDL, [S|U]ADB and UADDLP.
12519 //
12520 // i32 vecreduce_add(
12521 //  v16i32 abs(
12522 //    v16i32 sub(
12523 //     v16i32 [sign|zero]_extend(v16i8 a), v16i32 [sign|zero]_extend(v16i8 b))))
12524 // =================>
12525 // i32 vecreduce_add(
12526 //   v4i32 UADDLP(
12527 //     v8i16 add(
12528 //       v8i16 zext(
12529 //         v8i8 [S|U]ABD low8:v16i8 a, low8:v16i8 b
12530 //       v8i16 zext(
12531 //         v8i8 [S|U]ABD high8:v16i8 a, high8:v16i8 b
performVecReduceAddCombineWithUADDLP(SDNode * N,SelectionDAG & DAG)12532 static SDValue performVecReduceAddCombineWithUADDLP(SDNode *N,
12533                                                     SelectionDAG &DAG) {
12534   // Assumed i32 vecreduce_add
12535   if (N->getValueType(0) != MVT::i32)
12536     return SDValue();
12537 
12538   SDValue VecReduceOp0 = N->getOperand(0);
12539   unsigned Opcode = VecReduceOp0.getOpcode();
12540   // Assumed v16i32 abs
12541   if (Opcode != ISD::ABS || VecReduceOp0->getValueType(0) != MVT::v16i32)
12542     return SDValue();
12543 
12544   SDValue ABS = VecReduceOp0;
12545   // Assumed v16i32 sub
12546   if (ABS->getOperand(0)->getOpcode() != ISD::SUB ||
12547       ABS->getOperand(0)->getValueType(0) != MVT::v16i32)
12548     return SDValue();
12549 
12550   SDValue SUB = ABS->getOperand(0);
12551   unsigned Opcode0 = SUB->getOperand(0).getOpcode();
12552   unsigned Opcode1 = SUB->getOperand(1).getOpcode();
12553   // Assumed v16i32 type
12554   if (SUB->getOperand(0)->getValueType(0) != MVT::v16i32 ||
12555       SUB->getOperand(1)->getValueType(0) != MVT::v16i32)
12556     return SDValue();
12557 
12558   // Assumed zext or sext
12559   bool IsZExt = false;
12560   if (Opcode0 == ISD::ZERO_EXTEND && Opcode1 == ISD::ZERO_EXTEND) {
12561     IsZExt = true;
12562   } else if (Opcode0 == ISD::SIGN_EXTEND && Opcode1 == ISD::SIGN_EXTEND) {
12563     IsZExt = false;
12564   } else
12565     return SDValue();
12566 
12567   SDValue EXT0 = SUB->getOperand(0);
12568   SDValue EXT1 = SUB->getOperand(1);
12569   // Assumed zext's operand has v16i8 type
12570   if (EXT0->getOperand(0)->getValueType(0) != MVT::v16i8 ||
12571       EXT1->getOperand(0)->getValueType(0) != MVT::v16i8)
12572     return SDValue();
12573 
12574   // Pattern is dectected. Let's convert it to sequence of nodes.
12575   SDLoc DL(N);
12576 
12577   // First, create the node pattern of UABD/SABD.
12578   SDValue UABDHigh8Op0 =
12579       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
12580                   DAG.getConstant(8, DL, MVT::i64));
12581   SDValue UABDHigh8Op1 =
12582       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
12583                   DAG.getConstant(8, DL, MVT::i64));
12584   SDValue UABDHigh8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
12585                                   UABDHigh8Op0, UABDHigh8Op1);
12586   SDValue UABDL = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDHigh8);
12587 
12588   // Second, create the node pattern of UABAL.
12589   SDValue UABDLo8Op0 =
12590       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
12591                   DAG.getConstant(0, DL, MVT::i64));
12592   SDValue UABDLo8Op1 =
12593       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
12594                   DAG.getConstant(0, DL, MVT::i64));
12595   SDValue UABDLo8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
12596                                 UABDLo8Op0, UABDLo8Op1);
12597   SDValue ZExtUABD = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDLo8);
12598   SDValue UABAL = DAG.getNode(ISD::ADD, DL, MVT::v8i16, UABDL, ZExtUABD);
12599 
12600   // Third, create the node of UADDLP.
12601   SDValue UADDLP = DAG.getNode(AArch64ISD::UADDLP, DL, MVT::v4i32, UABAL);
12602 
12603   // Fourth, create the node of VECREDUCE_ADD.
12604   return DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, UADDLP);
12605 }
12606 
12607 // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce
12608 //   vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one))
12609 //   vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B))
performVecReduceAddCombine(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * ST)12610 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
12611                                           const AArch64Subtarget *ST) {
12612   if (!ST->hasDotProd())
12613     return performVecReduceAddCombineWithUADDLP(N, DAG);
12614 
12615   SDValue Op0 = N->getOperand(0);
12616   if (N->getValueType(0) != MVT::i32 ||
12617       Op0.getValueType().getVectorElementType() != MVT::i32)
12618     return SDValue();
12619 
12620   unsigned ExtOpcode = Op0.getOpcode();
12621   SDValue A = Op0;
12622   SDValue B;
12623   if (ExtOpcode == ISD::MUL) {
12624     A = Op0.getOperand(0);
12625     B = Op0.getOperand(1);
12626     if (A.getOpcode() != B.getOpcode() ||
12627         A.getOperand(0).getValueType() != B.getOperand(0).getValueType())
12628       return SDValue();
12629     ExtOpcode = A.getOpcode();
12630   }
12631   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
12632     return SDValue();
12633 
12634   EVT Op0VT = A.getOperand(0).getValueType();
12635   if (Op0VT != MVT::v8i8 && Op0VT != MVT::v16i8)
12636     return SDValue();
12637 
12638   SDLoc DL(Op0);
12639   // For non-mla reductions B can be set to 1. For MLA we take the operand of
12640   // the extend B.
12641   if (!B)
12642     B = DAG.getConstant(1, DL, Op0VT);
12643   else
12644     B = B.getOperand(0);
12645 
12646   SDValue Zeros =
12647       DAG.getConstant(0, DL, Op0VT == MVT::v8i8 ? MVT::v2i32 : MVT::v4i32);
12648   auto DotOpcode =
12649       (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT;
12650   SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros,
12651                             A.getOperand(0), B);
12652   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
12653 }
12654 
performXorCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)12655 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
12656                                  TargetLowering::DAGCombinerInfo &DCI,
12657                                  const AArch64Subtarget *Subtarget) {
12658   if (DCI.isBeforeLegalizeOps())
12659     return SDValue();
12660 
12661   return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
12662 }
12663 
12664 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const12665 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12666                                      SelectionDAG &DAG,
12667                                      SmallVectorImpl<SDNode *> &Created) const {
12668   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12669   if (isIntDivCheap(N->getValueType(0), Attr))
12670     return SDValue(N,0); // Lower SDIV as SDIV
12671 
12672   // fold (sdiv X, pow2)
12673   EVT VT = N->getValueType(0);
12674   if ((VT != MVT::i32 && VT != MVT::i64) ||
12675       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12676     return SDValue();
12677 
12678   SDLoc DL(N);
12679   SDValue N0 = N->getOperand(0);
12680   unsigned Lg2 = Divisor.countTrailingZeros();
12681   SDValue Zero = DAG.getConstant(0, DL, VT);
12682   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12683 
12684   // Add (N0 < 0) ? Pow2 - 1 : 0;
12685   SDValue CCVal;
12686   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
12687   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12688   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
12689 
12690   Created.push_back(Cmp.getNode());
12691   Created.push_back(Add.getNode());
12692   Created.push_back(CSel.getNode());
12693 
12694   // Divide by pow2.
12695   SDValue SRA =
12696       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
12697 
12698   // If we're dividing by a positive value, we're done.  Otherwise, we must
12699   // negate the result.
12700   if (Divisor.isNonNegative())
12701     return SRA;
12702 
12703   Created.push_back(SRA.getNode());
12704   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12705 }
12706 
IsSVECntIntrinsic(SDValue S)12707 static bool IsSVECntIntrinsic(SDValue S) {
12708   switch(getIntrinsicID(S.getNode())) {
12709   default:
12710     break;
12711   case Intrinsic::aarch64_sve_cntb:
12712   case Intrinsic::aarch64_sve_cnth:
12713   case Intrinsic::aarch64_sve_cntw:
12714   case Intrinsic::aarch64_sve_cntd:
12715     return true;
12716   }
12717   return false;
12718 }
12719 
12720 /// Calculates what the pre-extend type is, based on the extension
12721 /// operation node provided by \p Extend.
12722 ///
12723 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
12724 /// pre-extend type is pulled directly from the operand, while other extend
12725 /// operations need a bit more inspection to get this information.
12726 ///
12727 /// \param Extend The SDNode from the DAG that represents the extend operation
12728 /// \param DAG The SelectionDAG hosting the \p Extend node
12729 ///
12730 /// \returns The type representing the \p Extend source type, or \p MVT::Other
12731 /// if no valid type can be determined
calculatePreExtendType(SDValue Extend,SelectionDAG & DAG)12732 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) {
12733   switch (Extend.getOpcode()) {
12734   case ISD::SIGN_EXTEND:
12735   case ISD::ZERO_EXTEND:
12736     return Extend.getOperand(0).getValueType();
12737   case ISD::AssertSext:
12738   case ISD::AssertZext:
12739   case ISD::SIGN_EXTEND_INREG: {
12740     VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
12741     if (!TypeNode)
12742       return MVT::Other;
12743     return TypeNode->getVT();
12744   }
12745   case ISD::AND: {
12746     ConstantSDNode *Constant =
12747         dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
12748     if (!Constant)
12749       return MVT::Other;
12750 
12751     uint32_t Mask = Constant->getZExtValue();
12752 
12753     if (Mask == UCHAR_MAX)
12754       return MVT::i8;
12755     else if (Mask == USHRT_MAX)
12756       return MVT::i16;
12757     else if (Mask == UINT_MAX)
12758       return MVT::i32;
12759 
12760     return MVT::Other;
12761   }
12762   default:
12763     return MVT::Other;
12764   }
12765 
12766   llvm_unreachable("Code path unhandled in calculatePreExtendType!");
12767 }
12768 
12769 /// Combines a dup(sext/zext) node pattern into sext/zext(dup)
12770 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
performCommonVectorExtendCombine(SDValue VectorShuffle,SelectionDAG & DAG)12771 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle,
12772                                                 SelectionDAG &DAG) {
12773 
12774   ShuffleVectorSDNode *ShuffleNode =
12775       dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode());
12776   if (!ShuffleNode)
12777     return SDValue();
12778 
12779   // Ensuring the mask is zero before continuing
12780   if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0)
12781     return SDValue();
12782 
12783   SDValue InsertVectorElt = VectorShuffle.getOperand(0);
12784 
12785   if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
12786     return SDValue();
12787 
12788   SDValue InsertLane = InsertVectorElt.getOperand(2);
12789   ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode());
12790   // Ensures the insert is inserting into lane 0
12791   if (!Constant || Constant->getZExtValue() != 0)
12792     return SDValue();
12793 
12794   SDValue Extend = InsertVectorElt.getOperand(1);
12795   unsigned ExtendOpcode = Extend.getOpcode();
12796 
12797   bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
12798                 ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
12799                 ExtendOpcode == ISD::AssertSext;
12800   if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
12801       ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
12802     return SDValue();
12803 
12804   EVT TargetType = VectorShuffle.getValueType();
12805   EVT PreExtendType = calculatePreExtendType(Extend, DAG);
12806 
12807   if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 &&
12808        TargetType != MVT::v2i64) ||
12809       (PreExtendType == MVT::Other))
12810     return SDValue();
12811 
12812   // Restrict valid pre-extend data type
12813   if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 &&
12814       PreExtendType != MVT::i32)
12815     return SDValue();
12816 
12817   EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType);
12818 
12819   if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount())
12820     return SDValue();
12821 
12822   if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2)
12823     return SDValue();
12824 
12825   SDLoc DL(VectorShuffle);
12826 
12827   SDValue InsertVectorNode = DAG.getNode(
12828       InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT),
12829       DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType),
12830       DAG.getConstant(0, DL, MVT::i64));
12831 
12832   std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue());
12833 
12834   SDValue VectorShuffleNode =
12835       DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode,
12836                            DAG.getUNDEF(PreExtendVT), ShuffleMask);
12837 
12838   SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12839                                    DL, TargetType, VectorShuffleNode);
12840 
12841   return ExtendNode;
12842 }
12843 
12844 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
12845 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
performMulVectorExtendCombine(SDNode * Mul,SelectionDAG & DAG)12846 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
12847   // If the value type isn't a vector, none of the operands are going to be dups
12848   if (!Mul->getValueType(0).isVector())
12849     return SDValue();
12850 
12851   SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG);
12852   SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG);
12853 
12854   // Neither operands have been changed, don't make any further changes
12855   if (!Op0 && !Op1)
12856     return SDValue();
12857 
12858   SDLoc DL(Mul);
12859   return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0),
12860                      Op0 ? Op0 : Mul->getOperand(0),
12861                      Op1 ? Op1 : Mul->getOperand(1));
12862 }
12863 
performMulCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)12864 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
12865                                  TargetLowering::DAGCombinerInfo &DCI,
12866                                  const AArch64Subtarget *Subtarget) {
12867 
12868   if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
12869     return Ext;
12870 
12871   if (DCI.isBeforeLegalizeOps())
12872     return SDValue();
12873 
12874   // The below optimizations require a constant RHS.
12875   if (!isa<ConstantSDNode>(N->getOperand(1)))
12876     return SDValue();
12877 
12878   SDValue N0 = N->getOperand(0);
12879   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
12880   const APInt &ConstValue = C->getAPIntValue();
12881 
12882   // Allow the scaling to be folded into the `cnt` instruction by preventing
12883   // the scaling to be obscured here. This makes it easier to pattern match.
12884   if (IsSVECntIntrinsic(N0) ||
12885      (N0->getOpcode() == ISD::TRUNCATE &&
12886       (IsSVECntIntrinsic(N0->getOperand(0)))))
12887        if (ConstValue.sge(1) && ConstValue.sle(16))
12888          return SDValue();
12889 
12890   // Multiplication of a power of two plus/minus one can be done more
12891   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
12892   // future CPUs have a cheaper MADD instruction, this may need to be
12893   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
12894   // 64-bit is 5 cycles, so this is always a win.
12895   // More aggressively, some multiplications N0 * C can be lowered to
12896   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
12897   // e.g. 6=3*2=(2+1)*2.
12898   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
12899   // which equals to (1+2)*16-(1+2).
12900 
12901   // TrailingZeroes is used to test if the mul can be lowered to
12902   // shift+add+shift.
12903   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
12904   if (TrailingZeroes) {
12905     // Conservatively do not lower to shift+add+shift if the mul might be
12906     // folded into smul or umul.
12907     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
12908                             isZeroExtended(N0.getNode(), DAG)))
12909       return SDValue();
12910     // Conservatively do not lower to shift+add+shift if the mul might be
12911     // folded into madd or msub.
12912     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
12913                            N->use_begin()->getOpcode() == ISD::SUB))
12914       return SDValue();
12915   }
12916   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
12917   // and shift+add+shift.
12918   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
12919 
12920   unsigned ShiftAmt, AddSubOpc;
12921   // Is the shifted value the LHS operand of the add/sub?
12922   bool ShiftValUseIsN0 = true;
12923   // Do we need to negate the result?
12924   bool NegateResult = false;
12925 
12926   if (ConstValue.isNonNegative()) {
12927     // (mul x, 2^N + 1) => (add (shl x, N), x)
12928     // (mul x, 2^N - 1) => (sub (shl x, N), x)
12929     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
12930     APInt SCVMinus1 = ShiftedConstValue - 1;
12931     APInt CVPlus1 = ConstValue + 1;
12932     if (SCVMinus1.isPowerOf2()) {
12933       ShiftAmt = SCVMinus1.logBase2();
12934       AddSubOpc = ISD::ADD;
12935     } else if (CVPlus1.isPowerOf2()) {
12936       ShiftAmt = CVPlus1.logBase2();
12937       AddSubOpc = ISD::SUB;
12938     } else
12939       return SDValue();
12940   } else {
12941     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12942     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12943     APInt CVNegPlus1 = -ConstValue + 1;
12944     APInt CVNegMinus1 = -ConstValue - 1;
12945     if (CVNegPlus1.isPowerOf2()) {
12946       ShiftAmt = CVNegPlus1.logBase2();
12947       AddSubOpc = ISD::SUB;
12948       ShiftValUseIsN0 = false;
12949     } else if (CVNegMinus1.isPowerOf2()) {
12950       ShiftAmt = CVNegMinus1.logBase2();
12951       AddSubOpc = ISD::ADD;
12952       NegateResult = true;
12953     } else
12954       return SDValue();
12955   }
12956 
12957   SDLoc DL(N);
12958   EVT VT = N->getValueType(0);
12959   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
12960                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
12961 
12962   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
12963   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
12964   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
12965   assert(!(NegateResult && TrailingZeroes) &&
12966          "NegateResult and TrailingZeroes cannot both be true for now.");
12967   // Negate the result.
12968   if (NegateResult)
12969     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
12970   // Shift the result.
12971   if (TrailingZeroes)
12972     return DAG.getNode(ISD::SHL, DL, VT, Res,
12973                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
12974   return Res;
12975 }
12976 
performVectorCompareAndMaskUnaryOpCombine(SDNode * N,SelectionDAG & DAG)12977 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
12978                                                          SelectionDAG &DAG) {
12979   // Take advantage of vector comparisons producing 0 or -1 in each lane to
12980   // optimize away operation when it's from a constant.
12981   //
12982   // The general transformation is:
12983   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
12984   //       AND(VECTOR_CMP(x,y), constant2)
12985   //    constant2 = UNARYOP(constant)
12986 
12987   // Early exit if this isn't a vector operation, the operand of the
12988   // unary operation isn't a bitwise AND, or if the sizes of the operations
12989   // aren't the same.
12990   EVT VT = N->getValueType(0);
12991   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
12992       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
12993       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
12994     return SDValue();
12995 
12996   // Now check that the other operand of the AND is a constant. We could
12997   // make the transformation for non-constant splats as well, but it's unclear
12998   // that would be a benefit as it would not eliminate any operations, just
12999   // perform one more step in scalar code before moving to the vector unit.
13000   if (BuildVectorSDNode *BV =
13001           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
13002     // Bail out if the vector isn't a constant.
13003     if (!BV->isConstant())
13004       return SDValue();
13005 
13006     // Everything checks out. Build up the new and improved node.
13007     SDLoc DL(N);
13008     EVT IntVT = BV->getValueType(0);
13009     // Create a new constant of the appropriate type for the transformed
13010     // DAG.
13011     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
13012     // The AND node needs bitcasts to/from an integer vector type around it.
13013     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
13014     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
13015                                  N->getOperand(0)->getOperand(0), MaskConst);
13016     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
13017     return Res;
13018   }
13019 
13020   return SDValue();
13021 }
13022 
performIntToFpCombine(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)13023 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
13024                                      const AArch64Subtarget *Subtarget) {
13025   // First try to optimize away the conversion when it's conditionally from
13026   // a constant. Vectors only.
13027   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
13028     return Res;
13029 
13030   EVT VT = N->getValueType(0);
13031   if (VT != MVT::f32 && VT != MVT::f64)
13032     return SDValue();
13033 
13034   // Only optimize when the source and destination types have the same width.
13035   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
13036     return SDValue();
13037 
13038   // If the result of an integer load is only used by an integer-to-float
13039   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
13040   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
13041   SDValue N0 = N->getOperand(0);
13042   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
13043       // Do not change the width of a volatile load.
13044       !cast<LoadSDNode>(N0)->isVolatile()) {
13045     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13046     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
13047                                LN0->getPointerInfo(), LN0->getAlignment(),
13048                                LN0->getMemOperand()->getFlags());
13049 
13050     // Make sure successors of the original load stay after it by updating them
13051     // to use the new Chain.
13052     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
13053 
13054     unsigned Opcode =
13055         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
13056     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
13057   }
13058 
13059   return SDValue();
13060 }
13061 
13062 /// Fold a floating-point multiply by power of two into floating-point to
13063 /// fixed-point conversion.
performFpToIntCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)13064 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
13065                                      TargetLowering::DAGCombinerInfo &DCI,
13066                                      const AArch64Subtarget *Subtarget) {
13067   if (!Subtarget->hasNEON())
13068     return SDValue();
13069 
13070   if (!N->getValueType(0).isSimple())
13071     return SDValue();
13072 
13073   SDValue Op = N->getOperand(0);
13074   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13075       Op.getOpcode() != ISD::FMUL)
13076     return SDValue();
13077 
13078   SDValue ConstVec = Op->getOperand(1);
13079   if (!isa<BuildVectorSDNode>(ConstVec))
13080     return SDValue();
13081 
13082   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13083   uint32_t FloatBits = FloatTy.getSizeInBits();
13084   if (FloatBits != 32 && FloatBits != 64)
13085     return SDValue();
13086 
13087   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13088   uint32_t IntBits = IntTy.getSizeInBits();
13089   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
13090     return SDValue();
13091 
13092   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
13093   if (IntBits > FloatBits)
13094     return SDValue();
13095 
13096   BitVector UndefElements;
13097   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13098   int32_t Bits = IntBits == 64 ? 64 : 32;
13099   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
13100   if (C == -1 || C == 0 || C > Bits)
13101     return SDValue();
13102 
13103   MVT ResTy;
13104   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13105   switch (NumLanes) {
13106   default:
13107     return SDValue();
13108   case 2:
13109     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
13110     break;
13111   case 4:
13112     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
13113     break;
13114   }
13115 
13116   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
13117     return SDValue();
13118 
13119   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
13120          "Illegal vector type after legalization");
13121 
13122   SDLoc DL(N);
13123   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13124   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
13125                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
13126   SDValue FixConv =
13127       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
13128                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
13129                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
13130   // We can handle smaller integers by generating an extra trunc.
13131   if (IntBits < FloatBits)
13132     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
13133 
13134   return FixConv;
13135 }
13136 
13137 /// Fold a floating-point divide by power of two into fixed-point to
13138 /// floating-point conversion.
performFDivCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)13139 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
13140                                   TargetLowering::DAGCombinerInfo &DCI,
13141                                   const AArch64Subtarget *Subtarget) {
13142   if (!Subtarget->hasNEON())
13143     return SDValue();
13144 
13145   SDValue Op = N->getOperand(0);
13146   unsigned Opc = Op->getOpcode();
13147   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13148       !Op.getOperand(0).getValueType().isSimple() ||
13149       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
13150     return SDValue();
13151 
13152   SDValue ConstVec = N->getOperand(1);
13153   if (!isa<BuildVectorSDNode>(ConstVec))
13154     return SDValue();
13155 
13156   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13157   int32_t IntBits = IntTy.getSizeInBits();
13158   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
13159     return SDValue();
13160 
13161   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13162   int32_t FloatBits = FloatTy.getSizeInBits();
13163   if (FloatBits != 32 && FloatBits != 64)
13164     return SDValue();
13165 
13166   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
13167   if (IntBits > FloatBits)
13168     return SDValue();
13169 
13170   BitVector UndefElements;
13171   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13172   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
13173   if (C == -1 || C == 0 || C > FloatBits)
13174     return SDValue();
13175 
13176   MVT ResTy;
13177   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13178   switch (NumLanes) {
13179   default:
13180     return SDValue();
13181   case 2:
13182     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
13183     break;
13184   case 4:
13185     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
13186     break;
13187   }
13188 
13189   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
13190     return SDValue();
13191 
13192   SDLoc DL(N);
13193   SDValue ConvInput = Op.getOperand(0);
13194   bool IsSigned = Opc == ISD::SINT_TO_FP;
13195   if (IntBits < FloatBits)
13196     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
13197                             ResTy, ConvInput);
13198 
13199   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
13200                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
13201   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
13202                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
13203                      DAG.getConstant(C, DL, MVT::i32));
13204 }
13205 
13206 /// An EXTR instruction is made up of two shifts, ORed together. This helper
13207 /// searches for and classifies those shifts.
findEXTRHalf(SDValue N,SDValue & Src,uint32_t & ShiftAmount,bool & FromHi)13208 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
13209                          bool &FromHi) {
13210   if (N.getOpcode() == ISD::SHL)
13211     FromHi = false;
13212   else if (N.getOpcode() == ISD::SRL)
13213     FromHi = true;
13214   else
13215     return false;
13216 
13217   if (!isa<ConstantSDNode>(N.getOperand(1)))
13218     return false;
13219 
13220   ShiftAmount = N->getConstantOperandVal(1);
13221   Src = N->getOperand(0);
13222   return true;
13223 }
13224 
13225 /// EXTR instruction extracts a contiguous chunk of bits from two existing
13226 /// registers viewed as a high/low pair. This function looks for the pattern:
13227 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
13228 /// with an EXTR. Can't quite be done in TableGen because the two immediates
13229 /// aren't independent.
tryCombineToEXTR(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13230 static SDValue tryCombineToEXTR(SDNode *N,
13231                                 TargetLowering::DAGCombinerInfo &DCI) {
13232   SelectionDAG &DAG = DCI.DAG;
13233   SDLoc DL(N);
13234   EVT VT = N->getValueType(0);
13235 
13236   assert(N->getOpcode() == ISD::OR && "Unexpected root");
13237 
13238   if (VT != MVT::i32 && VT != MVT::i64)
13239     return SDValue();
13240 
13241   SDValue LHS;
13242   uint32_t ShiftLHS = 0;
13243   bool LHSFromHi = false;
13244   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
13245     return SDValue();
13246 
13247   SDValue RHS;
13248   uint32_t ShiftRHS = 0;
13249   bool RHSFromHi = false;
13250   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
13251     return SDValue();
13252 
13253   // If they're both trying to come from the high part of the register, they're
13254   // not really an EXTR.
13255   if (LHSFromHi == RHSFromHi)
13256     return SDValue();
13257 
13258   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
13259     return SDValue();
13260 
13261   if (LHSFromHi) {
13262     std::swap(LHS, RHS);
13263     std::swap(ShiftLHS, ShiftRHS);
13264   }
13265 
13266   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
13267                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
13268 }
13269 
tryCombineToBSL(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13270 static SDValue tryCombineToBSL(SDNode *N,
13271                                 TargetLowering::DAGCombinerInfo &DCI) {
13272   EVT VT = N->getValueType(0);
13273   SelectionDAG &DAG = DCI.DAG;
13274   SDLoc DL(N);
13275 
13276   if (!VT.isVector())
13277     return SDValue();
13278 
13279   // The combining code currently only works for NEON vectors. In particular,
13280   // it does not work for SVE when dealing with vectors wider than 128 bits.
13281   if (!VT.is64BitVector() && !VT.is128BitVector())
13282     return SDValue();
13283 
13284   SDValue N0 = N->getOperand(0);
13285   if (N0.getOpcode() != ISD::AND)
13286     return SDValue();
13287 
13288   SDValue N1 = N->getOperand(1);
13289   if (N1.getOpcode() != ISD::AND)
13290     return SDValue();
13291 
13292   // InstCombine does (not (neg a)) => (add a -1).
13293   // Try: (or (and (neg a) b) (and (add a -1) c)) => (bsl (neg a) b c)
13294   // Loop over all combinations of AND operands.
13295   for (int i = 1; i >= 0; --i) {
13296     for (int j = 1; j >= 0; --j) {
13297       SDValue O0 = N0->getOperand(i);
13298       SDValue O1 = N1->getOperand(j);
13299       SDValue Sub, Add, SubSibling, AddSibling;
13300 
13301       // Find a SUB and an ADD operand, one from each AND.
13302       if (O0.getOpcode() == ISD::SUB && O1.getOpcode() == ISD::ADD) {
13303         Sub = O0;
13304         Add = O1;
13305         SubSibling = N0->getOperand(1 - i);
13306         AddSibling = N1->getOperand(1 - j);
13307       } else if (O0.getOpcode() == ISD::ADD && O1.getOpcode() == ISD::SUB) {
13308         Add = O0;
13309         Sub = O1;
13310         AddSibling = N0->getOperand(1 - i);
13311         SubSibling = N1->getOperand(1 - j);
13312       } else
13313         continue;
13314 
13315       if (!ISD::isBuildVectorAllZeros(Sub.getOperand(0).getNode()))
13316         continue;
13317 
13318       // Constant ones is always righthand operand of the Add.
13319       if (!ISD::isBuildVectorAllOnes(Add.getOperand(1).getNode()))
13320         continue;
13321 
13322       if (Sub.getOperand(1) != Add.getOperand(0))
13323         continue;
13324 
13325       return DAG.getNode(AArch64ISD::BSP, DL, VT, Sub, SubSibling, AddSibling);
13326     }
13327   }
13328 
13329   // (or (and a b) (and (not a) c)) => (bsl a b c)
13330   // We only have to look for constant vectors here since the general, variable
13331   // case can be handled in TableGen.
13332   unsigned Bits = VT.getScalarSizeInBits();
13333   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
13334   for (int i = 1; i >= 0; --i)
13335     for (int j = 1; j >= 0; --j) {
13336       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
13337       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
13338       if (!BVN0 || !BVN1)
13339         continue;
13340 
13341       bool FoundMatch = true;
13342       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
13343         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
13344         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
13345         if (!CN0 || !CN1 ||
13346             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
13347           FoundMatch = false;
13348           break;
13349         }
13350       }
13351 
13352       if (FoundMatch)
13353         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
13354                            N0->getOperand(1 - i), N1->getOperand(1 - j));
13355     }
13356 
13357   return SDValue();
13358 }
13359 
performORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)13360 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13361                                 const AArch64Subtarget *Subtarget) {
13362   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
13363   SelectionDAG &DAG = DCI.DAG;
13364   EVT VT = N->getValueType(0);
13365 
13366   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13367     return SDValue();
13368 
13369   if (SDValue Res = tryCombineToEXTR(N, DCI))
13370     return Res;
13371 
13372   if (SDValue Res = tryCombineToBSL(N, DCI))
13373     return Res;
13374 
13375   return SDValue();
13376 }
13377 
isConstantSplatVectorMaskForType(SDNode * N,EVT MemVT)13378 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
13379   if (!MemVT.getVectorElementType().isSimple())
13380     return false;
13381 
13382   uint64_t MaskForTy = 0ull;
13383   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
13384   case MVT::i8:
13385     MaskForTy = 0xffull;
13386     break;
13387   case MVT::i16:
13388     MaskForTy = 0xffffull;
13389     break;
13390   case MVT::i32:
13391     MaskForTy = 0xffffffffull;
13392     break;
13393   default:
13394     return false;
13395     break;
13396   }
13397 
13398   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
13399     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
13400       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
13401 
13402   return false;
13403 }
13404 
performSVEAndCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13405 static SDValue performSVEAndCombine(SDNode *N,
13406                                     TargetLowering::DAGCombinerInfo &DCI) {
13407   if (DCI.isBeforeLegalizeOps())
13408     return SDValue();
13409 
13410   SelectionDAG &DAG = DCI.DAG;
13411   SDValue Src = N->getOperand(0);
13412   unsigned Opc = Src->getOpcode();
13413 
13414   // Zero/any extend of an unsigned unpack
13415   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
13416     SDValue UnpkOp = Src->getOperand(0);
13417     SDValue Dup = N->getOperand(1);
13418 
13419     if (Dup.getOpcode() != AArch64ISD::DUP)
13420       return SDValue();
13421 
13422     SDLoc DL(N);
13423     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
13424     if (!C)
13425       return SDValue();
13426 
13427     uint64_t ExtVal = C->getZExtValue();
13428 
13429     // If the mask is fully covered by the unpack, we don't need to push
13430     // a new AND onto the operand
13431     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
13432     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
13433         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
13434         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
13435       return Src;
13436 
13437     // Truncate to prevent a DUP with an over wide constant
13438     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
13439 
13440     // Otherwise, make sure we propagate the AND to the operand
13441     // of the unpack
13442     Dup = DAG.getNode(AArch64ISD::DUP, DL,
13443                       UnpkOp->getValueType(0),
13444                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
13445 
13446     SDValue And = DAG.getNode(ISD::AND, DL,
13447                               UnpkOp->getValueType(0), UnpkOp, Dup);
13448 
13449     return DAG.getNode(Opc, DL, N->getValueType(0), And);
13450   }
13451 
13452   if (!EnableCombineMGatherIntrinsics)
13453     return SDValue();
13454 
13455   SDValue Mask = N->getOperand(1);
13456 
13457   if (!Src.hasOneUse())
13458     return SDValue();
13459 
13460   EVT MemVT;
13461 
13462   // SVE load instructions perform an implicit zero-extend, which makes them
13463   // perfect candidates for combining.
13464   switch (Opc) {
13465   case AArch64ISD::LD1_MERGE_ZERO:
13466   case AArch64ISD::LDNF1_MERGE_ZERO:
13467   case AArch64ISD::LDFF1_MERGE_ZERO:
13468     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
13469     break;
13470   case AArch64ISD::GLD1_MERGE_ZERO:
13471   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
13472   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
13473   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
13474   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
13475   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
13476   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
13477   case AArch64ISD::GLDFF1_MERGE_ZERO:
13478   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
13479   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
13480   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
13481   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
13482   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
13483   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
13484   case AArch64ISD::GLDNT1_MERGE_ZERO:
13485     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
13486     break;
13487   default:
13488     return SDValue();
13489   }
13490 
13491   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
13492     return Src;
13493 
13494   return SDValue();
13495 }
13496 
performANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13497 static SDValue performANDCombine(SDNode *N,
13498                                  TargetLowering::DAGCombinerInfo &DCI) {
13499   SelectionDAG &DAG = DCI.DAG;
13500   SDValue LHS = N->getOperand(0);
13501   EVT VT = N->getValueType(0);
13502   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
13503     return SDValue();
13504 
13505   if (VT.isScalableVector())
13506     return performSVEAndCombine(N, DCI);
13507 
13508   // The combining code below works only for NEON vectors. In particular, it
13509   // does not work for SVE when dealing with vectors wider than 128 bits.
13510   if (!(VT.is64BitVector() || VT.is128BitVector()))
13511     return SDValue();
13512 
13513   BuildVectorSDNode *BVN =
13514       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
13515   if (!BVN)
13516     return SDValue();
13517 
13518   // AND does not accept an immediate, so check if we can use a BIC immediate
13519   // instruction instead. We do this here instead of using a (and x, (mvni imm))
13520   // pattern in isel, because some immediates may be lowered to the preferred
13521   // (and x, (movi imm)) form, even though an mvni representation also exists.
13522   APInt DefBits(VT.getSizeInBits(), 0);
13523   APInt UndefBits(VT.getSizeInBits(), 0);
13524   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
13525     SDValue NewOp;
13526 
13527     DefBits = ~DefBits;
13528     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
13529                                     DefBits, &LHS)) ||
13530         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
13531                                     DefBits, &LHS)))
13532       return NewOp;
13533 
13534     UndefBits = ~UndefBits;
13535     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
13536                                     UndefBits, &LHS)) ||
13537         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
13538                                     UndefBits, &LHS)))
13539       return NewOp;
13540   }
13541 
13542   return SDValue();
13543 }
13544 
performSRLCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13545 static SDValue performSRLCombine(SDNode *N,
13546                                  TargetLowering::DAGCombinerInfo &DCI) {
13547   SelectionDAG &DAG = DCI.DAG;
13548   EVT VT = N->getValueType(0);
13549   if (VT != MVT::i32 && VT != MVT::i64)
13550     return SDValue();
13551 
13552   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
13553   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
13554   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
13555   SDValue N0 = N->getOperand(0);
13556   if (N0.getOpcode() == ISD::BSWAP) {
13557     SDLoc DL(N);
13558     SDValue N1 = N->getOperand(1);
13559     SDValue N00 = N0.getOperand(0);
13560     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13561       uint64_t ShiftAmt = C->getZExtValue();
13562       if (VT == MVT::i32 && ShiftAmt == 16 &&
13563           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
13564         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
13565       if (VT == MVT::i64 && ShiftAmt == 32 &&
13566           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
13567         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
13568     }
13569   }
13570   return SDValue();
13571 }
13572 
13573 // Attempt to form urhadd(OpA, OpB) from
13574 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
13575 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
13576 // The original form of the first expression is
13577 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
13578 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
13579 // Before this function is called the srl will have been lowered to
13580 // AArch64ISD::VLSHR.
13581 // This pass can also recognize signed variants of the patterns that use sign
13582 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
13583 // shadd(OpA, OpB) from them.
13584 static SDValue
performVectorTruncateCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13585 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13586                              SelectionDAG &DAG) {
13587   EVT VT = N->getValueType(0);
13588 
13589   // Since we are looking for a right shift by a constant value of 1 and we are
13590   // operating on types at least 16 bits in length (sign/zero extended OpA and
13591   // OpB, which are at least 8 bits), it follows that the truncate will always
13592   // discard the shifted-in bit and therefore the right shift will be logical
13593   // regardless of the signedness of OpA and OpB.
13594   SDValue Shift = N->getOperand(0);
13595   if (Shift.getOpcode() != AArch64ISD::VLSHR)
13596     return SDValue();
13597 
13598   // Is the right shift using an immediate value of 1?
13599   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
13600   if (ShiftAmount != 1)
13601     return SDValue();
13602 
13603   SDValue ExtendOpA, ExtendOpB;
13604   SDValue ShiftOp0 = Shift.getOperand(0);
13605   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
13606   if (ShiftOp0Opc == ISD::SUB) {
13607 
13608     SDValue Xor = ShiftOp0.getOperand(1);
13609     if (Xor.getOpcode() != ISD::XOR)
13610       return SDValue();
13611 
13612     // Is the XOR using a constant amount of all ones in the right hand side?
13613     uint64_t C;
13614     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
13615       return SDValue();
13616 
13617     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
13618     APInt CAsAPInt(ElemSizeInBits, C);
13619     if (CAsAPInt != APInt::getAllOnes(ElemSizeInBits))
13620       return SDValue();
13621 
13622     ExtendOpA = Xor.getOperand(0);
13623     ExtendOpB = ShiftOp0.getOperand(0);
13624   } else if (ShiftOp0Opc == ISD::ADD) {
13625     ExtendOpA = ShiftOp0.getOperand(0);
13626     ExtendOpB = ShiftOp0.getOperand(1);
13627   } else
13628     return SDValue();
13629 
13630   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
13631   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
13632   if (!(ExtendOpAOpc == ExtendOpBOpc &&
13633         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
13634     return SDValue();
13635 
13636   // Is the result of the right shift being truncated to the same value type as
13637   // the original operands, OpA and OpB?
13638   SDValue OpA = ExtendOpA.getOperand(0);
13639   SDValue OpB = ExtendOpB.getOperand(0);
13640   EVT OpAVT = OpA.getValueType();
13641   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
13642   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
13643     return SDValue();
13644 
13645   SDLoc DL(N);
13646   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
13647   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
13648   unsigned HADDOpc = IsSignExtend
13649                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
13650                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
13651   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
13652 
13653   return ResultHADD;
13654 }
13655 
hasPairwiseAdd(unsigned Opcode,EVT VT,bool FullFP16)13656 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
13657   switch (Opcode) {
13658   case ISD::FADD:
13659     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
13660   case ISD::ADD:
13661     return VT == MVT::i64;
13662   default:
13663     return false;
13664   }
13665 }
13666 
performExtractVectorEltCombine(SDNode * N,SelectionDAG & DAG)13667 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
13668   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
13669   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
13670 
13671   EVT VT = N->getValueType(0);
13672   const bool FullFP16 =
13673       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
13674 
13675   // Rewrite for pairwise fadd pattern
13676   //   (f32 (extract_vector_elt
13677   //           (fadd (vXf32 Other)
13678   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
13679   // ->
13680   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
13681   //              (extract_vector_elt (vXf32 Other) 1))
13682   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
13683       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
13684     SDLoc DL(N0);
13685     SDValue N00 = N0->getOperand(0);
13686     SDValue N01 = N0->getOperand(1);
13687 
13688     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
13689     SDValue Other = N00;
13690 
13691     // And handle the commutative case.
13692     if (!Shuffle) {
13693       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
13694       Other = N01;
13695     }
13696 
13697     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
13698         Other == Shuffle->getOperand(0)) {
13699       return DAG.getNode(N0->getOpcode(), DL, VT,
13700                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
13701                                      DAG.getConstant(0, DL, MVT::i64)),
13702                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
13703                                      DAG.getConstant(1, DL, MVT::i64)));
13704     }
13705   }
13706 
13707   return SDValue();
13708 }
13709 
performConcatVectorsCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13710 static SDValue performConcatVectorsCombine(SDNode *N,
13711                                            TargetLowering::DAGCombinerInfo &DCI,
13712                                            SelectionDAG &DAG) {
13713   SDLoc dl(N);
13714   EVT VT = N->getValueType(0);
13715   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
13716   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
13717 
13718   // Optimize concat_vectors of truncated vectors, where the intermediate
13719   // type is illegal, to avoid said illegality,  e.g.,
13720   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
13721   //                          (v2i16 (truncate (v2i64)))))
13722   // ->
13723   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
13724   //                                    (v4i32 (bitcast (v2i64))),
13725   //                                    <0, 2, 4, 6>)))
13726   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
13727   // on both input and result type, so we might generate worse code.
13728   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
13729   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
13730       N1Opc == ISD::TRUNCATE) {
13731     SDValue N00 = N0->getOperand(0);
13732     SDValue N10 = N1->getOperand(0);
13733     EVT N00VT = N00.getValueType();
13734 
13735     if (N00VT == N10.getValueType() &&
13736         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
13737         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
13738       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
13739       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
13740       for (size_t i = 0; i < Mask.size(); ++i)
13741         Mask[i] = i * 2;
13742       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13743                          DAG.getVectorShuffle(
13744                              MidVT, dl,
13745                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
13746                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
13747     }
13748   }
13749 
13750   // Wait 'til after everything is legalized to try this. That way we have
13751   // legal vector types and such.
13752   if (DCI.isBeforeLegalizeOps())
13753     return SDValue();
13754 
13755   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
13756   // subvectors from the same original vectors. Combine these into a single
13757   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
13758   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
13759   //                                        extract_subvector (v16i8 OpB,
13760   //                                        <0>))),
13761   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
13762   //                                        extract_subvector (v16i8 OpB,
13763   //                                        <8>)))))
13764   // ->
13765   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
13766   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
13767       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
13768        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
13769     SDValue N00 = N0->getOperand(0);
13770     SDValue N01 = N0->getOperand(1);
13771     SDValue N10 = N1->getOperand(0);
13772     SDValue N11 = N1->getOperand(1);
13773 
13774     EVT N00VT = N00.getValueType();
13775     EVT N10VT = N10.getValueType();
13776 
13777     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13778         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13779         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13780         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
13781       SDValue N00Source = N00->getOperand(0);
13782       SDValue N01Source = N01->getOperand(0);
13783       SDValue N10Source = N10->getOperand(0);
13784       SDValue N11Source = N11->getOperand(0);
13785 
13786       if (N00Source == N10Source && N01Source == N11Source &&
13787           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
13788         assert(N0.getValueType() == N1.getValueType());
13789 
13790         uint64_t N00Index = N00.getConstantOperandVal(1);
13791         uint64_t N01Index = N01.getConstantOperandVal(1);
13792         uint64_t N10Index = N10.getConstantOperandVal(1);
13793         uint64_t N11Index = N11.getConstantOperandVal(1);
13794 
13795         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
13796             N10Index == N00VT.getVectorNumElements())
13797           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
13798       }
13799     }
13800   }
13801 
13802   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
13803   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
13804   // canonicalise to that.
13805   if (N->getNumOperands() == 2 && N0 == N1 && VT.getVectorNumElements() == 2) {
13806     assert(VT.getScalarSizeInBits() == 64);
13807     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
13808                        DAG.getConstant(0, dl, MVT::i64));
13809   }
13810 
13811   // Canonicalise concat_vectors so that the right-hand vector has as few
13812   // bit-casts as possible before its real operation. The primary matching
13813   // destination for these operations will be the narrowing "2" instructions,
13814   // which depend on the operation being performed on this right-hand vector.
13815   // For example,
13816   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
13817   // becomes
13818   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
13819 
13820   if (N->getNumOperands() != 2 || N1Opc != ISD::BITCAST)
13821     return SDValue();
13822   SDValue RHS = N1->getOperand(0);
13823   MVT RHSTy = RHS.getValueType().getSimpleVT();
13824   // If the RHS is not a vector, this is not the pattern we're looking for.
13825   if (!RHSTy.isVector())
13826     return SDValue();
13827 
13828   LLVM_DEBUG(
13829       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
13830 
13831   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
13832                                   RHSTy.getVectorNumElements() * 2);
13833   return DAG.getNode(ISD::BITCAST, dl, VT,
13834                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
13835                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
13836                                  RHS));
13837 }
13838 
13839 static SDValue
performInsertSubvectorCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13840 performInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13841                               SelectionDAG &DAG) {
13842   SDValue Vec = N->getOperand(0);
13843   SDValue SubVec = N->getOperand(1);
13844   uint64_t IdxVal = N->getConstantOperandVal(2);
13845   EVT VecVT = Vec.getValueType();
13846   EVT SubVT = SubVec.getValueType();
13847 
13848   // Only do this for legal fixed vector types.
13849   if (!VecVT.isFixedLengthVector() ||
13850       !DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
13851       !DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
13852     return SDValue();
13853 
13854   // Ignore widening patterns.
13855   if (IdxVal == 0 && Vec.isUndef())
13856     return SDValue();
13857 
13858   // Subvector must be half the width and an "aligned" insertion.
13859   unsigned NumSubElts = SubVT.getVectorNumElements();
13860   if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
13861       (IdxVal != 0 && IdxVal != NumSubElts))
13862     return SDValue();
13863 
13864   // Fold insert_subvector -> concat_vectors
13865   // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
13866   // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
13867   SDLoc DL(N);
13868   SDValue Lo, Hi;
13869   if (IdxVal == 0) {
13870     Lo = SubVec;
13871     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
13872                      DAG.getVectorIdxConstant(NumSubElts, DL));
13873   } else {
13874     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
13875                      DAG.getVectorIdxConstant(0, DL));
13876     Hi = SubVec;
13877   }
13878   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
13879 }
13880 
tryCombineFixedPointConvert(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13881 static SDValue tryCombineFixedPointConvert(SDNode *N,
13882                                            TargetLowering::DAGCombinerInfo &DCI,
13883                                            SelectionDAG &DAG) {
13884   // Wait until after everything is legalized to try this. That way we have
13885   // legal vector types and such.
13886   if (DCI.isBeforeLegalizeOps())
13887     return SDValue();
13888   // Transform a scalar conversion of a value from a lane extract into a
13889   // lane extract of a vector conversion. E.g., from foo1 to foo2:
13890   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
13891   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
13892   //
13893   // The second form interacts better with instruction selection and the
13894   // register allocator to avoid cross-class register copies that aren't
13895   // coalescable due to a lane reference.
13896 
13897   // Check the operand and see if it originates from a lane extract.
13898   SDValue Op1 = N->getOperand(1);
13899   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13900     // Yep, no additional predication needed. Perform the transform.
13901     SDValue IID = N->getOperand(0);
13902     SDValue Shift = N->getOperand(2);
13903     SDValue Vec = Op1.getOperand(0);
13904     SDValue Lane = Op1.getOperand(1);
13905     EVT ResTy = N->getValueType(0);
13906     EVT VecResTy;
13907     SDLoc DL(N);
13908 
13909     // The vector width should be 128 bits by the time we get here, even
13910     // if it started as 64 bits (the extract_vector handling will have
13911     // done so).
13912     assert(Vec.getValueSizeInBits() == 128 &&
13913            "unexpected vector size on extract_vector_elt!");
13914     if (Vec.getValueType() == MVT::v4i32)
13915       VecResTy = MVT::v4f32;
13916     else if (Vec.getValueType() == MVT::v2i64)
13917       VecResTy = MVT::v2f64;
13918     else
13919       llvm_unreachable("unexpected vector type!");
13920 
13921     SDValue Convert =
13922         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
13923     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
13924   }
13925   return SDValue();
13926 }
13927 
13928 // AArch64 high-vector "long" operations are formed by performing the non-high
13929 // version on an extract_subvector of each operand which gets the high half:
13930 //
13931 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
13932 //
13933 // However, there are cases which don't have an extract_high explicitly, but
13934 // have another operation that can be made compatible with one for free. For
13935 // example:
13936 //
13937 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
13938 //
13939 // This routine does the actual conversion of such DUPs, once outer routines
13940 // have determined that everything else is in order.
13941 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
13942 // similarly here.
tryExtendDUPToExtractHigh(SDValue N,SelectionDAG & DAG)13943 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
13944   switch (N.getOpcode()) {
13945   case AArch64ISD::DUP:
13946   case AArch64ISD::DUPLANE8:
13947   case AArch64ISD::DUPLANE16:
13948   case AArch64ISD::DUPLANE32:
13949   case AArch64ISD::DUPLANE64:
13950   case AArch64ISD::MOVI:
13951   case AArch64ISD::MOVIshift:
13952   case AArch64ISD::MOVIedit:
13953   case AArch64ISD::MOVImsl:
13954   case AArch64ISD::MVNIshift:
13955   case AArch64ISD::MVNImsl:
13956     break;
13957   default:
13958     // FMOV could be supported, but isn't very useful, as it would only occur
13959     // if you passed a bitcast' floating point immediate to an eligible long
13960     // integer op (addl, smull, ...).
13961     return SDValue();
13962   }
13963 
13964   MVT NarrowTy = N.getSimpleValueType();
13965   if (!NarrowTy.is64BitVector())
13966     return SDValue();
13967 
13968   MVT ElementTy = NarrowTy.getVectorElementType();
13969   unsigned NumElems = NarrowTy.getVectorNumElements();
13970   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
13971 
13972   SDLoc dl(N);
13973   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
13974                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
13975                      DAG.getConstant(NumElems, dl, MVT::i64));
13976 }
13977 
isEssentiallyExtractHighSubvector(SDValue N)13978 static bool isEssentiallyExtractHighSubvector(SDValue N) {
13979   if (N.getOpcode() == ISD::BITCAST)
13980     N = N.getOperand(0);
13981   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13982     return false;
13983   if (N.getOperand(0).getValueType().isScalableVector())
13984     return false;
13985   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
13986          N.getOperand(0).getValueType().getVectorNumElements() / 2;
13987 }
13988 
13989 /// Helper structure to keep track of ISD::SET_CC operands.
13990 struct GenericSetCCInfo {
13991   const SDValue *Opnd0;
13992   const SDValue *Opnd1;
13993   ISD::CondCode CC;
13994 };
13995 
13996 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
13997 struct AArch64SetCCInfo {
13998   const SDValue *Cmp;
13999   AArch64CC::CondCode CC;
14000 };
14001 
14002 /// Helper structure to keep track of SetCC information.
14003 union SetCCInfo {
14004   GenericSetCCInfo Generic;
14005   AArch64SetCCInfo AArch64;
14006 };
14007 
14008 /// Helper structure to be able to read SetCC information.  If set to
14009 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
14010 /// GenericSetCCInfo.
14011 struct SetCCInfoAndKind {
14012   SetCCInfo Info;
14013   bool IsAArch64;
14014 };
14015 
14016 /// Check whether or not \p Op is a SET_CC operation, either a generic or
14017 /// an
14018 /// AArch64 lowered one.
14019 /// \p SetCCInfo is filled accordingly.
14020 /// \post SetCCInfo is meanginfull only when this function returns true.
14021 /// \return True when Op is a kind of SET_CC operation.
isSetCC(SDValue Op,SetCCInfoAndKind & SetCCInfo)14022 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
14023   // If this is a setcc, this is straight forward.
14024   if (Op.getOpcode() == ISD::SETCC) {
14025     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
14026     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
14027     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14028     SetCCInfo.IsAArch64 = false;
14029     return true;
14030   }
14031   // Otherwise, check if this is a matching csel instruction.
14032   // In other words:
14033   // - csel 1, 0, cc
14034   // - csel 0, 1, !cc
14035   if (Op.getOpcode() != AArch64ISD::CSEL)
14036     return false;
14037   // Set the information about the operands.
14038   // TODO: we want the operands of the Cmp not the csel
14039   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
14040   SetCCInfo.IsAArch64 = true;
14041   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
14042       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14043 
14044   // Check that the operands matches the constraints:
14045   // (1) Both operands must be constants.
14046   // (2) One must be 1 and the other must be 0.
14047   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
14048   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14049 
14050   // Check (1).
14051   if (!TValue || !FValue)
14052     return false;
14053 
14054   // Check (2).
14055   if (!TValue->isOne()) {
14056     // Update the comparison when we are interested in !cc.
14057     std::swap(TValue, FValue);
14058     SetCCInfo.Info.AArch64.CC =
14059         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
14060   }
14061   return TValue->isOne() && FValue->isZero();
14062 }
14063 
14064 // Returns true if Op is setcc or zext of setcc.
isSetCCOrZExtSetCC(const SDValue & Op,SetCCInfoAndKind & Info)14065 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
14066   if (isSetCC(Op, Info))
14067     return true;
14068   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
14069     isSetCC(Op->getOperand(0), Info));
14070 }
14071 
14072 // The folding we want to perform is:
14073 // (add x, [zext] (setcc cc ...) )
14074 //   -->
14075 // (csel x, (add x, 1), !cc ...)
14076 //
14077 // The latter will get matched to a CSINC instruction.
performSetccAddFolding(SDNode * Op,SelectionDAG & DAG)14078 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
14079   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
14080   SDValue LHS = Op->getOperand(0);
14081   SDValue RHS = Op->getOperand(1);
14082   SetCCInfoAndKind InfoAndKind;
14083 
14084   // If both operands are a SET_CC, then we don't want to perform this
14085   // folding and create another csel as this results in more instructions
14086   // (and higher register usage).
14087   if (isSetCCOrZExtSetCC(LHS, InfoAndKind) &&
14088       isSetCCOrZExtSetCC(RHS, InfoAndKind))
14089     return SDValue();
14090 
14091   // If neither operand is a SET_CC, give up.
14092   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
14093     std::swap(LHS, RHS);
14094     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
14095       return SDValue();
14096   }
14097 
14098   // FIXME: This could be generatized to work for FP comparisons.
14099   EVT CmpVT = InfoAndKind.IsAArch64
14100                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
14101                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
14102   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
14103     return SDValue();
14104 
14105   SDValue CCVal;
14106   SDValue Cmp;
14107   SDLoc dl(Op);
14108   if (InfoAndKind.IsAArch64) {
14109     CCVal = DAG.getConstant(
14110         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
14111         MVT::i32);
14112     Cmp = *InfoAndKind.Info.AArch64.Cmp;
14113   } else
14114     Cmp = getAArch64Cmp(
14115         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
14116         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
14117         dl);
14118 
14119   EVT VT = Op->getValueType(0);
14120   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
14121   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
14122 }
14123 
14124 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
performUADDVCombine(SDNode * N,SelectionDAG & DAG)14125 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
14126   EVT VT = N->getValueType(0);
14127   // Only scalar integer and vector types.
14128   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
14129     return SDValue();
14130 
14131   SDValue LHS = N->getOperand(0);
14132   SDValue RHS = N->getOperand(1);
14133   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14134       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
14135     return SDValue();
14136 
14137   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14138   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
14139   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isZero())
14140     return SDValue();
14141 
14142   SDValue Op1 = LHS->getOperand(0);
14143   SDValue Op2 = RHS->getOperand(0);
14144   EVT OpVT1 = Op1.getValueType();
14145   EVT OpVT2 = Op2.getValueType();
14146   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
14147       Op2.getOpcode() != AArch64ISD::UADDV ||
14148       OpVT1.getVectorElementType() != VT)
14149     return SDValue();
14150 
14151   SDValue Val1 = Op1.getOperand(0);
14152   SDValue Val2 = Op2.getOperand(0);
14153   EVT ValVT = Val1->getValueType(0);
14154   SDLoc DL(N);
14155   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
14156   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14157                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
14158                      DAG.getConstant(0, DL, MVT::i64));
14159 }
14160 
14161 // ADD(UDOT(zero, x, y), A) -->  UDOT(A, x, y)
performAddDotCombine(SDNode * N,SelectionDAG & DAG)14162 static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) {
14163   EVT VT = N->getValueType(0);
14164   if (N->getOpcode() != ISD::ADD)
14165     return SDValue();
14166 
14167   SDValue Dot = N->getOperand(0);
14168   SDValue A = N->getOperand(1);
14169   // Handle commutivity
14170   auto isZeroDot = [](SDValue Dot) {
14171     return (Dot.getOpcode() == AArch64ISD::UDOT ||
14172             Dot.getOpcode() == AArch64ISD::SDOT) &&
14173            isZerosVector(Dot.getOperand(0).getNode());
14174   };
14175   if (!isZeroDot(Dot))
14176     std::swap(Dot, A);
14177   if (!isZeroDot(Dot))
14178     return SDValue();
14179 
14180   return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1),
14181                      Dot.getOperand(2));
14182 }
14183 
14184 // The basic add/sub long vector instructions have variants with "2" on the end
14185 // which act on the high-half of their inputs. They are normally matched by
14186 // patterns like:
14187 //
14188 // (add (zeroext (extract_high LHS)),
14189 //      (zeroext (extract_high RHS)))
14190 // -> uaddl2 vD, vN, vM
14191 //
14192 // However, if one of the extracts is something like a duplicate, this
14193 // instruction can still be used profitably. This function puts the DAG into a
14194 // more appropriate form for those patterns to trigger.
performAddSubLongCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14195 static SDValue performAddSubLongCombine(SDNode *N,
14196                                         TargetLowering::DAGCombinerInfo &DCI,
14197                                         SelectionDAG &DAG) {
14198   if (DCI.isBeforeLegalizeOps())
14199     return SDValue();
14200 
14201   MVT VT = N->getSimpleValueType(0);
14202   if (!VT.is128BitVector()) {
14203     if (N->getOpcode() == ISD::ADD)
14204       return performSetccAddFolding(N, DAG);
14205     return SDValue();
14206   }
14207 
14208   // Make sure both branches are extended in the same way.
14209   SDValue LHS = N->getOperand(0);
14210   SDValue RHS = N->getOperand(1);
14211   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
14212        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
14213       LHS.getOpcode() != RHS.getOpcode())
14214     return SDValue();
14215 
14216   unsigned ExtType = LHS.getOpcode();
14217 
14218   // It's not worth doing if at least one of the inputs isn't already an
14219   // extract, but we don't know which it'll be so we have to try both.
14220   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
14221     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
14222     if (!RHS.getNode())
14223       return SDValue();
14224 
14225     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
14226   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
14227     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
14228     if (!LHS.getNode())
14229       return SDValue();
14230 
14231     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
14232   }
14233 
14234   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
14235 }
14236 
performAddSubCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14237 static SDValue performAddSubCombine(SDNode *N,
14238                                     TargetLowering::DAGCombinerInfo &DCI,
14239                                     SelectionDAG &DAG) {
14240   // Try to change sum of two reductions.
14241   if (SDValue Val = performUADDVCombine(N, DAG))
14242     return Val;
14243   if (SDValue Val = performAddDotCombine(N, DAG))
14244     return Val;
14245 
14246   return performAddSubLongCombine(N, DCI, DAG);
14247 }
14248 
14249 // Massage DAGs which we can use the high-half "long" operations on into
14250 // something isel will recognize better. E.g.
14251 //
14252 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
14253 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
14254 //                     (extract_high (v2i64 (dup128 scalar)))))
14255 //
tryCombineLongOpWithDup(unsigned IID,SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14256 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
14257                                        TargetLowering::DAGCombinerInfo &DCI,
14258                                        SelectionDAG &DAG) {
14259   if (DCI.isBeforeLegalizeOps())
14260     return SDValue();
14261 
14262   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
14263   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
14264   assert(LHS.getValueType().is64BitVector() &&
14265          RHS.getValueType().is64BitVector() &&
14266          "unexpected shape for long operation");
14267 
14268   // Either node could be a DUP, but it's not worth doing both of them (you'd
14269   // just as well use the non-high version) so look for a corresponding extract
14270   // operation on the other "wing".
14271   if (isEssentiallyExtractHighSubvector(LHS)) {
14272     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
14273     if (!RHS.getNode())
14274       return SDValue();
14275   } else if (isEssentiallyExtractHighSubvector(RHS)) {
14276     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
14277     if (!LHS.getNode())
14278       return SDValue();
14279   }
14280 
14281   if (IID == Intrinsic::not_intrinsic)
14282     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
14283 
14284   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
14285                      N->getOperand(0), LHS, RHS);
14286 }
14287 
tryCombineShiftImm(unsigned IID,SDNode * N,SelectionDAG & DAG)14288 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
14289   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
14290   unsigned ElemBits = ElemTy.getSizeInBits();
14291 
14292   int64_t ShiftAmount;
14293   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
14294     APInt SplatValue, SplatUndef;
14295     unsigned SplatBitSize;
14296     bool HasAnyUndefs;
14297     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
14298                               HasAnyUndefs, ElemBits) ||
14299         SplatBitSize != ElemBits)
14300       return SDValue();
14301 
14302     ShiftAmount = SplatValue.getSExtValue();
14303   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14304     ShiftAmount = CVN->getSExtValue();
14305   } else
14306     return SDValue();
14307 
14308   unsigned Opcode;
14309   bool IsRightShift;
14310   switch (IID) {
14311   default:
14312     llvm_unreachable("Unknown shift intrinsic");
14313   case Intrinsic::aarch64_neon_sqshl:
14314     Opcode = AArch64ISD::SQSHL_I;
14315     IsRightShift = false;
14316     break;
14317   case Intrinsic::aarch64_neon_uqshl:
14318     Opcode = AArch64ISD::UQSHL_I;
14319     IsRightShift = false;
14320     break;
14321   case Intrinsic::aarch64_neon_srshl:
14322     Opcode = AArch64ISD::SRSHR_I;
14323     IsRightShift = true;
14324     break;
14325   case Intrinsic::aarch64_neon_urshl:
14326     Opcode = AArch64ISD::URSHR_I;
14327     IsRightShift = true;
14328     break;
14329   case Intrinsic::aarch64_neon_sqshlu:
14330     Opcode = AArch64ISD::SQSHLU_I;
14331     IsRightShift = false;
14332     break;
14333   case Intrinsic::aarch64_neon_sshl:
14334   case Intrinsic::aarch64_neon_ushl:
14335     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
14336     // left shift for positive shift amounts. Below, we only replace the current
14337     // node with VSHL, if this condition is met.
14338     Opcode = AArch64ISD::VSHL;
14339     IsRightShift = false;
14340     break;
14341   }
14342 
14343   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
14344     SDLoc dl(N);
14345     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
14346                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
14347   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
14348     SDLoc dl(N);
14349     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
14350                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
14351   }
14352 
14353   return SDValue();
14354 }
14355 
14356 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
14357 // the intrinsics must be legal and take an i32, this means there's almost
14358 // certainly going to be a zext in the DAG which we can eliminate.
tryCombineCRC32(unsigned Mask,SDNode * N,SelectionDAG & DAG)14359 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
14360   SDValue AndN = N->getOperand(2);
14361   if (AndN.getOpcode() != ISD::AND)
14362     return SDValue();
14363 
14364   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
14365   if (!CMask || CMask->getZExtValue() != Mask)
14366     return SDValue();
14367 
14368   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
14369                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
14370 }
14371 
combineAcrossLanesIntrinsic(unsigned Opc,SDNode * N,SelectionDAG & DAG)14372 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
14373                                            SelectionDAG &DAG) {
14374   SDLoc dl(N);
14375   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
14376                      DAG.getNode(Opc, dl,
14377                                  N->getOperand(1).getSimpleValueType(),
14378                                  N->getOperand(1)),
14379                      DAG.getConstant(0, dl, MVT::i64));
14380 }
14381 
LowerSVEIntrinsicIndex(SDNode * N,SelectionDAG & DAG)14382 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
14383   SDLoc DL(N);
14384   SDValue Op1 = N->getOperand(1);
14385   SDValue Op2 = N->getOperand(2);
14386   EVT ScalarTy = Op2.getValueType();
14387   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
14388     ScalarTy = MVT::i32;
14389 
14390   // Lower index_vector(base, step) to mul(step step_vector(1)) + splat(base).
14391   SDValue StepVector = DAG.getStepVector(DL, N->getValueType(0));
14392   SDValue Step = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op2);
14393   SDValue Mul = DAG.getNode(ISD::MUL, DL, N->getValueType(0), StepVector, Step);
14394   SDValue Base = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op1);
14395   return DAG.getNode(ISD::ADD, DL, N->getValueType(0), Mul, Base);
14396 }
14397 
LowerSVEIntrinsicDUP(SDNode * N,SelectionDAG & DAG)14398 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
14399   SDLoc dl(N);
14400   SDValue Scalar = N->getOperand(3);
14401   EVT ScalarTy = Scalar.getValueType();
14402 
14403   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
14404     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
14405 
14406   SDValue Passthru = N->getOperand(1);
14407   SDValue Pred = N->getOperand(2);
14408   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
14409                      Pred, Scalar, Passthru);
14410 }
14411 
LowerSVEIntrinsicEXT(SDNode * N,SelectionDAG & DAG)14412 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
14413   SDLoc dl(N);
14414   LLVMContext &Ctx = *DAG.getContext();
14415   EVT VT = N->getValueType(0);
14416 
14417   assert(VT.isScalableVector() && "Expected a scalable vector.");
14418 
14419   // Current lowering only supports the SVE-ACLE types.
14420   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
14421     return SDValue();
14422 
14423   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
14424   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
14425   EVT ByteVT =
14426       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
14427 
14428   // Convert everything to the domain of EXT (i.e bytes).
14429   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
14430   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
14431   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
14432                             DAG.getConstant(ElemSize, dl, MVT::i32));
14433 
14434   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
14435   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
14436 }
14437 
tryConvertSVEWideCompare(SDNode * N,ISD::CondCode CC,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14438 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
14439                                         TargetLowering::DAGCombinerInfo &DCI,
14440                                         SelectionDAG &DAG) {
14441   if (DCI.isBeforeLegalize())
14442     return SDValue();
14443 
14444   SDValue Comparator = N->getOperand(3);
14445   if (Comparator.getOpcode() == AArch64ISD::DUP ||
14446       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
14447     unsigned IID = getIntrinsicID(N);
14448     EVT VT = N->getValueType(0);
14449     EVT CmpVT = N->getOperand(2).getValueType();
14450     SDValue Pred = N->getOperand(1);
14451     SDValue Imm;
14452     SDLoc DL(N);
14453 
14454     switch (IID) {
14455     default:
14456       llvm_unreachable("Called with wrong intrinsic!");
14457       break;
14458 
14459     // Signed comparisons
14460     case Intrinsic::aarch64_sve_cmpeq_wide:
14461     case Intrinsic::aarch64_sve_cmpne_wide:
14462     case Intrinsic::aarch64_sve_cmpge_wide:
14463     case Intrinsic::aarch64_sve_cmpgt_wide:
14464     case Intrinsic::aarch64_sve_cmplt_wide:
14465     case Intrinsic::aarch64_sve_cmple_wide: {
14466       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
14467         int64_t ImmVal = CN->getSExtValue();
14468         if (ImmVal >= -16 && ImmVal <= 15)
14469           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
14470         else
14471           return SDValue();
14472       }
14473       break;
14474     }
14475     // Unsigned comparisons
14476     case Intrinsic::aarch64_sve_cmphs_wide:
14477     case Intrinsic::aarch64_sve_cmphi_wide:
14478     case Intrinsic::aarch64_sve_cmplo_wide:
14479     case Intrinsic::aarch64_sve_cmpls_wide:  {
14480       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
14481         uint64_t ImmVal = CN->getZExtValue();
14482         if (ImmVal <= 127)
14483           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
14484         else
14485           return SDValue();
14486       }
14487       break;
14488     }
14489     }
14490 
14491     if (!Imm)
14492       return SDValue();
14493 
14494     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
14495     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
14496                        N->getOperand(2), Splat, DAG.getCondCode(CC));
14497   }
14498 
14499   return SDValue();
14500 }
14501 
getPTest(SelectionDAG & DAG,EVT VT,SDValue Pg,SDValue Op,AArch64CC::CondCode Cond)14502 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
14503                         AArch64CC::CondCode Cond) {
14504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14505 
14506   SDLoc DL(Op);
14507   assert(Op.getValueType().isScalableVector() &&
14508          TLI.isTypeLegal(Op.getValueType()) &&
14509          "Expected legal scalable vector type!");
14510 
14511   // Ensure target specific opcodes are using legal type.
14512   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
14513   SDValue TVal = DAG.getConstant(1, DL, OutVT);
14514   SDValue FVal = DAG.getConstant(0, DL, OutVT);
14515 
14516   // Set condition code (CC) flags.
14517   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
14518 
14519   // Convert CC to integer based on requested condition.
14520   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
14521   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
14522   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
14523   return DAG.getZExtOrTrunc(Res, DL, VT);
14524 }
14525 
combineSVEReductionInt(SDNode * N,unsigned Opc,SelectionDAG & DAG)14526 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
14527                                       SelectionDAG &DAG) {
14528   SDLoc DL(N);
14529 
14530   SDValue Pred = N->getOperand(1);
14531   SDValue VecToReduce = N->getOperand(2);
14532 
14533   // NOTE: The integer reduction's result type is not always linked to the
14534   // operand's element type so we construct it from the intrinsic's result type.
14535   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
14536   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
14537 
14538   // SVE reductions set the whole vector register with the first element
14539   // containing the reduction result, which we'll now extract.
14540   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
14541   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
14542                      Zero);
14543 }
14544 
combineSVEReductionFP(SDNode * N,unsigned Opc,SelectionDAG & DAG)14545 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
14546                                      SelectionDAG &DAG) {
14547   SDLoc DL(N);
14548 
14549   SDValue Pred = N->getOperand(1);
14550   SDValue VecToReduce = N->getOperand(2);
14551 
14552   EVT ReduceVT = VecToReduce.getValueType();
14553   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
14554 
14555   // SVE reductions set the whole vector register with the first element
14556   // containing the reduction result, which we'll now extract.
14557   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
14558   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
14559                      Zero);
14560 }
14561 
combineSVEReductionOrderedFP(SDNode * N,unsigned Opc,SelectionDAG & DAG)14562 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
14563                                             SelectionDAG &DAG) {
14564   SDLoc DL(N);
14565 
14566   SDValue Pred = N->getOperand(1);
14567   SDValue InitVal = N->getOperand(2);
14568   SDValue VecToReduce = N->getOperand(3);
14569   EVT ReduceVT = VecToReduce.getValueType();
14570 
14571   // Ordered reductions use the first lane of the result vector as the
14572   // reduction's initial value.
14573   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
14574   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
14575                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
14576 
14577   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
14578 
14579   // SVE reductions set the whole vector register with the first element
14580   // containing the reduction result, which we'll now extract.
14581   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
14582                      Zero);
14583 }
14584 
isAllActivePredicate(SDValue N)14585 static bool isAllActivePredicate(SDValue N) {
14586   unsigned NumElts = N.getValueType().getVectorMinNumElements();
14587 
14588   // Look through cast.
14589   while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST) {
14590     N = N.getOperand(0);
14591     // When reinterpreting from a type with fewer elements the "new" elements
14592     // are not active, so bail if they're likely to be used.
14593     if (N.getValueType().getVectorMinNumElements() < NumElts)
14594       return false;
14595   }
14596 
14597   // "ptrue p.<ty>, all" can be considered all active when <ty> is the same size
14598   // or smaller than the implicit element type represented by N.
14599   // NOTE: A larger element count implies a smaller element type.
14600   if (N.getOpcode() == AArch64ISD::PTRUE &&
14601       N.getConstantOperandVal(0) == AArch64SVEPredPattern::all)
14602     return N.getValueType().getVectorMinNumElements() >= NumElts;
14603 
14604   return false;
14605 }
14606 
14607 // If a merged operation has no inactive lanes we can relax it to a predicated
14608 // or unpredicated operation, which potentially allows better isel (perhaps
14609 // using immediate forms) or relaxing register reuse requirements.
convertMergedOpToPredOp(SDNode * N,unsigned Opc,SelectionDAG & DAG,bool UnpredOp=false,bool SwapOperands=false)14610 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned Opc,
14611                                        SelectionDAG &DAG, bool UnpredOp = false,
14612                                        bool SwapOperands = false) {
14613   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
14614   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
14615   SDValue Pg = N->getOperand(1);
14616   SDValue Op1 = N->getOperand(SwapOperands ? 3 : 2);
14617   SDValue Op2 = N->getOperand(SwapOperands ? 2 : 3);
14618 
14619   // ISD way to specify an all active predicate.
14620   if (isAllActivePredicate(Pg)) {
14621     if (UnpredOp)
14622       return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Op1, Op2);
14623 
14624     return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Pg, Op1, Op2);
14625   }
14626 
14627   // FUTURE: SplatVector(true)
14628   return SDValue();
14629 }
14630 
performIntrinsicCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)14631 static SDValue performIntrinsicCombine(SDNode *N,
14632                                        TargetLowering::DAGCombinerInfo &DCI,
14633                                        const AArch64Subtarget *Subtarget) {
14634   SelectionDAG &DAG = DCI.DAG;
14635   unsigned IID = getIntrinsicID(N);
14636   switch (IID) {
14637   default:
14638     break;
14639   case Intrinsic::aarch64_neon_vcvtfxs2fp:
14640   case Intrinsic::aarch64_neon_vcvtfxu2fp:
14641     return tryCombineFixedPointConvert(N, DCI, DAG);
14642   case Intrinsic::aarch64_neon_saddv:
14643     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
14644   case Intrinsic::aarch64_neon_uaddv:
14645     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
14646   case Intrinsic::aarch64_neon_sminv:
14647     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
14648   case Intrinsic::aarch64_neon_uminv:
14649     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
14650   case Intrinsic::aarch64_neon_smaxv:
14651     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
14652   case Intrinsic::aarch64_neon_umaxv:
14653     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
14654   case Intrinsic::aarch64_neon_fmax:
14655     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
14656                        N->getOperand(1), N->getOperand(2));
14657   case Intrinsic::aarch64_neon_fmin:
14658     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
14659                        N->getOperand(1), N->getOperand(2));
14660   case Intrinsic::aarch64_neon_fmaxnm:
14661     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
14662                        N->getOperand(1), N->getOperand(2));
14663   case Intrinsic::aarch64_neon_fminnm:
14664     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
14665                        N->getOperand(1), N->getOperand(2));
14666   case Intrinsic::aarch64_neon_smull:
14667   case Intrinsic::aarch64_neon_umull:
14668   case Intrinsic::aarch64_neon_pmull:
14669   case Intrinsic::aarch64_neon_sqdmull:
14670     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
14671   case Intrinsic::aarch64_neon_sqshl:
14672   case Intrinsic::aarch64_neon_uqshl:
14673   case Intrinsic::aarch64_neon_sqshlu:
14674   case Intrinsic::aarch64_neon_srshl:
14675   case Intrinsic::aarch64_neon_urshl:
14676   case Intrinsic::aarch64_neon_sshl:
14677   case Intrinsic::aarch64_neon_ushl:
14678     return tryCombineShiftImm(IID, N, DAG);
14679   case Intrinsic::aarch64_crc32b:
14680   case Intrinsic::aarch64_crc32cb:
14681     return tryCombineCRC32(0xff, N, DAG);
14682   case Intrinsic::aarch64_crc32h:
14683   case Intrinsic::aarch64_crc32ch:
14684     return tryCombineCRC32(0xffff, N, DAG);
14685   case Intrinsic::aarch64_sve_saddv:
14686     // There is no i64 version of SADDV because the sign is irrelevant.
14687     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
14688       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
14689     else
14690       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
14691   case Intrinsic::aarch64_sve_uaddv:
14692     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
14693   case Intrinsic::aarch64_sve_smaxv:
14694     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
14695   case Intrinsic::aarch64_sve_umaxv:
14696     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
14697   case Intrinsic::aarch64_sve_sminv:
14698     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
14699   case Intrinsic::aarch64_sve_uminv:
14700     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
14701   case Intrinsic::aarch64_sve_orv:
14702     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
14703   case Intrinsic::aarch64_sve_eorv:
14704     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
14705   case Intrinsic::aarch64_sve_andv:
14706     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
14707   case Intrinsic::aarch64_sve_index:
14708     return LowerSVEIntrinsicIndex(N, DAG);
14709   case Intrinsic::aarch64_sve_dup:
14710     return LowerSVEIntrinsicDUP(N, DAG);
14711   case Intrinsic::aarch64_sve_dup_x:
14712     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
14713                        N->getOperand(1));
14714   case Intrinsic::aarch64_sve_ext:
14715     return LowerSVEIntrinsicEXT(N, DAG);
14716   case Intrinsic::aarch64_sve_mul:
14717     return convertMergedOpToPredOp(N, AArch64ISD::MUL_PRED, DAG);
14718   case Intrinsic::aarch64_sve_smulh:
14719     return convertMergedOpToPredOp(N, AArch64ISD::MULHS_PRED, DAG);
14720   case Intrinsic::aarch64_sve_umulh:
14721     return convertMergedOpToPredOp(N, AArch64ISD::MULHU_PRED, DAG);
14722   case Intrinsic::aarch64_sve_smin:
14723     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
14724   case Intrinsic::aarch64_sve_umin:
14725     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
14726   case Intrinsic::aarch64_sve_smax:
14727     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
14728   case Intrinsic::aarch64_sve_umax:
14729     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
14730   case Intrinsic::aarch64_sve_lsl:
14731     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
14732   case Intrinsic::aarch64_sve_lsr:
14733     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
14734   case Intrinsic::aarch64_sve_asr:
14735     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
14736   case Intrinsic::aarch64_sve_fadd:
14737     return convertMergedOpToPredOp(N, AArch64ISD::FADD_PRED, DAG);
14738   case Intrinsic::aarch64_sve_fsub:
14739     return convertMergedOpToPredOp(N, AArch64ISD::FSUB_PRED, DAG);
14740   case Intrinsic::aarch64_sve_fmul:
14741     return convertMergedOpToPredOp(N, AArch64ISD::FMUL_PRED, DAG);
14742   case Intrinsic::aarch64_sve_add:
14743     return convertMergedOpToPredOp(N, ISD::ADD, DAG, true);
14744   case Intrinsic::aarch64_sve_sub:
14745     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true);
14746   case Intrinsic::aarch64_sve_subr:
14747     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true, true);
14748   case Intrinsic::aarch64_sve_and:
14749     return convertMergedOpToPredOp(N, ISD::AND, DAG, true);
14750   case Intrinsic::aarch64_sve_bic:
14751     return convertMergedOpToPredOp(N, AArch64ISD::BIC, DAG, true);
14752   case Intrinsic::aarch64_sve_eor:
14753     return convertMergedOpToPredOp(N, ISD::XOR, DAG, true);
14754   case Intrinsic::aarch64_sve_orr:
14755     return convertMergedOpToPredOp(N, ISD::OR, DAG, true);
14756   case Intrinsic::aarch64_sve_sqadd:
14757     return convertMergedOpToPredOp(N, ISD::SADDSAT, DAG, true);
14758   case Intrinsic::aarch64_sve_sqsub:
14759     return convertMergedOpToPredOp(N, ISD::SSUBSAT, DAG, true);
14760   case Intrinsic::aarch64_sve_uqadd:
14761     return convertMergedOpToPredOp(N, ISD::UADDSAT, DAG, true);
14762   case Intrinsic::aarch64_sve_uqsub:
14763     return convertMergedOpToPredOp(N, ISD::USUBSAT, DAG, true);
14764   case Intrinsic::aarch64_sve_sqadd_x:
14765     return DAG.getNode(ISD::SADDSAT, SDLoc(N), N->getValueType(0),
14766                        N->getOperand(1), N->getOperand(2));
14767   case Intrinsic::aarch64_sve_sqsub_x:
14768     return DAG.getNode(ISD::SSUBSAT, SDLoc(N), N->getValueType(0),
14769                        N->getOperand(1), N->getOperand(2));
14770   case Intrinsic::aarch64_sve_uqadd_x:
14771     return DAG.getNode(ISD::UADDSAT, SDLoc(N), N->getValueType(0),
14772                        N->getOperand(1), N->getOperand(2));
14773   case Intrinsic::aarch64_sve_uqsub_x:
14774     return DAG.getNode(ISD::USUBSAT, SDLoc(N), N->getValueType(0),
14775                        N->getOperand(1), N->getOperand(2));
14776   case Intrinsic::aarch64_sve_cmphs:
14777     if (!N->getOperand(2).getValueType().isFloatingPoint())
14778       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14779                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
14780                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
14781     break;
14782   case Intrinsic::aarch64_sve_cmphi:
14783     if (!N->getOperand(2).getValueType().isFloatingPoint())
14784       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14785                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
14786                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
14787     break;
14788   case Intrinsic::aarch64_sve_fcmpge:
14789   case Intrinsic::aarch64_sve_cmpge:
14790     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14791                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14792                        N->getOperand(3), DAG.getCondCode(ISD::SETGE));
14793     break;
14794   case Intrinsic::aarch64_sve_fcmpgt:
14795   case Intrinsic::aarch64_sve_cmpgt:
14796     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14797                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14798                        N->getOperand(3), DAG.getCondCode(ISD::SETGT));
14799     break;
14800   case Intrinsic::aarch64_sve_fcmpeq:
14801   case Intrinsic::aarch64_sve_cmpeq:
14802     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14803                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14804                        N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
14805     break;
14806   case Intrinsic::aarch64_sve_fcmpne:
14807   case Intrinsic::aarch64_sve_cmpne:
14808     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14809                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14810                        N->getOperand(3), DAG.getCondCode(ISD::SETNE));
14811     break;
14812   case Intrinsic::aarch64_sve_fcmpuo:
14813     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14814                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14815                        N->getOperand(3), DAG.getCondCode(ISD::SETUO));
14816     break;
14817   case Intrinsic::aarch64_sve_fadda:
14818     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
14819   case Intrinsic::aarch64_sve_faddv:
14820     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
14821   case Intrinsic::aarch64_sve_fmaxnmv:
14822     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
14823   case Intrinsic::aarch64_sve_fmaxv:
14824     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
14825   case Intrinsic::aarch64_sve_fminnmv:
14826     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
14827   case Intrinsic::aarch64_sve_fminv:
14828     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
14829   case Intrinsic::aarch64_sve_sel:
14830     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
14831                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
14832   case Intrinsic::aarch64_sve_cmpeq_wide:
14833     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
14834   case Intrinsic::aarch64_sve_cmpne_wide:
14835     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
14836   case Intrinsic::aarch64_sve_cmpge_wide:
14837     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
14838   case Intrinsic::aarch64_sve_cmpgt_wide:
14839     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
14840   case Intrinsic::aarch64_sve_cmplt_wide:
14841     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
14842   case Intrinsic::aarch64_sve_cmple_wide:
14843     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
14844   case Intrinsic::aarch64_sve_cmphs_wide:
14845     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
14846   case Intrinsic::aarch64_sve_cmphi_wide:
14847     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
14848   case Intrinsic::aarch64_sve_cmplo_wide:
14849     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
14850   case Intrinsic::aarch64_sve_cmpls_wide:
14851     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
14852   case Intrinsic::aarch64_sve_ptest_any:
14853     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
14854                     AArch64CC::ANY_ACTIVE);
14855   case Intrinsic::aarch64_sve_ptest_first:
14856     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
14857                     AArch64CC::FIRST_ACTIVE);
14858   case Intrinsic::aarch64_sve_ptest_last:
14859     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
14860                     AArch64CC::LAST_ACTIVE);
14861   }
14862   return SDValue();
14863 }
14864 
performExtendCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14865 static SDValue performExtendCombine(SDNode *N,
14866                                     TargetLowering::DAGCombinerInfo &DCI,
14867                                     SelectionDAG &DAG) {
14868   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
14869   // we can convert that DUP into another extract_high (of a bigger DUP), which
14870   // helps the backend to decide that an sabdl2 would be useful, saving a real
14871   // extract_high operation.
14872   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
14873       (N->getOperand(0).getOpcode() == ISD::ABDU ||
14874        N->getOperand(0).getOpcode() == ISD::ABDS)) {
14875     SDNode *ABDNode = N->getOperand(0).getNode();
14876     SDValue NewABD =
14877         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
14878     if (!NewABD.getNode())
14879       return SDValue();
14880 
14881     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
14882   }
14883   return SDValue();
14884 }
14885 
splitStoreSplat(SelectionDAG & DAG,StoreSDNode & St,SDValue SplatVal,unsigned NumVecElts)14886 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
14887                                SDValue SplatVal, unsigned NumVecElts) {
14888   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
14889   unsigned OrigAlignment = St.getAlignment();
14890   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
14891 
14892   // Create scalar stores. This is at least as good as the code sequence for a
14893   // split unaligned store which is a dup.s, ext.b, and two stores.
14894   // Most of the time the three stores should be replaced by store pair
14895   // instructions (stp).
14896   SDLoc DL(&St);
14897   SDValue BasePtr = St.getBasePtr();
14898   uint64_t BaseOffset = 0;
14899 
14900   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
14901   SDValue NewST1 =
14902       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
14903                    OrigAlignment, St.getMemOperand()->getFlags());
14904 
14905   // As this in ISel, we will not merge this add which may degrade results.
14906   if (BasePtr->getOpcode() == ISD::ADD &&
14907       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
14908     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
14909     BasePtr = BasePtr->getOperand(0);
14910   }
14911 
14912   unsigned Offset = EltOffset;
14913   while (--NumVecElts) {
14914     unsigned Alignment = MinAlign(OrigAlignment, Offset);
14915     SDValue OffsetPtr =
14916         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
14917                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
14918     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
14919                           PtrInfo.getWithOffset(Offset), Alignment,
14920                           St.getMemOperand()->getFlags());
14921     Offset += EltOffset;
14922   }
14923   return NewST1;
14924 }
14925 
14926 // Returns an SVE type that ContentTy can be trivially sign or zero extended
14927 // into.
getSVEContainerType(EVT ContentTy)14928 static MVT getSVEContainerType(EVT ContentTy) {
14929   assert(ContentTy.isSimple() && "No SVE containers for extended types");
14930 
14931   switch (ContentTy.getSimpleVT().SimpleTy) {
14932   default:
14933     llvm_unreachable("No known SVE container for this MVT type");
14934   case MVT::nxv2i8:
14935   case MVT::nxv2i16:
14936   case MVT::nxv2i32:
14937   case MVT::nxv2i64:
14938   case MVT::nxv2f32:
14939   case MVT::nxv2f64:
14940     return MVT::nxv2i64;
14941   case MVT::nxv4i8:
14942   case MVT::nxv4i16:
14943   case MVT::nxv4i32:
14944   case MVT::nxv4f32:
14945     return MVT::nxv4i32;
14946   case MVT::nxv8i8:
14947   case MVT::nxv8i16:
14948   case MVT::nxv8f16:
14949   case MVT::nxv8bf16:
14950     return MVT::nxv8i16;
14951   case MVT::nxv16i8:
14952     return MVT::nxv16i8;
14953   }
14954 }
14955 
performLD1Combine(SDNode * N,SelectionDAG & DAG,unsigned Opc)14956 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
14957   SDLoc DL(N);
14958   EVT VT = N->getValueType(0);
14959 
14960   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14961     return SDValue();
14962 
14963   EVT ContainerVT = VT;
14964   if (ContainerVT.isInteger())
14965     ContainerVT = getSVEContainerType(ContainerVT);
14966 
14967   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
14968   SDValue Ops[] = { N->getOperand(0), // Chain
14969                     N->getOperand(2), // Pg
14970                     N->getOperand(3), // Base
14971                     DAG.getValueType(VT) };
14972 
14973   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
14974   SDValue LoadChain = SDValue(Load.getNode(), 1);
14975 
14976   if (ContainerVT.isInteger() && (VT != ContainerVT))
14977     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
14978 
14979   return DAG.getMergeValues({ Load, LoadChain }, DL);
14980 }
14981 
performLDNT1Combine(SDNode * N,SelectionDAG & DAG)14982 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
14983   SDLoc DL(N);
14984   EVT VT = N->getValueType(0);
14985   EVT PtrTy = N->getOperand(3).getValueType();
14986 
14987   if (VT == MVT::nxv8bf16 &&
14988       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
14989     return SDValue();
14990 
14991   EVT LoadVT = VT;
14992   if (VT.isFloatingPoint())
14993     LoadVT = VT.changeTypeToInteger();
14994 
14995   auto *MINode = cast<MemIntrinsicSDNode>(N);
14996   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
14997   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
14998                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
14999                                 MINode->getOperand(2), PassThru,
15000                                 MINode->getMemoryVT(), MINode->getMemOperand(),
15001                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
15002 
15003    if (VT.isFloatingPoint()) {
15004      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
15005      return DAG.getMergeValues(Ops, DL);
15006    }
15007 
15008   return L;
15009 }
15010 
15011 template <unsigned Opcode>
performLD1ReplicateCombine(SDNode * N,SelectionDAG & DAG)15012 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
15013   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
15014                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
15015                 "Unsupported opcode.");
15016   SDLoc DL(N);
15017   EVT VT = N->getValueType(0);
15018   if (VT == MVT::nxv8bf16 &&
15019       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15020     return SDValue();
15021 
15022   EVT LoadVT = VT;
15023   if (VT.isFloatingPoint())
15024     LoadVT = VT.changeTypeToInteger();
15025 
15026   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
15027   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
15028   SDValue LoadChain = SDValue(Load.getNode(), 1);
15029 
15030   if (VT.isFloatingPoint())
15031     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
15032 
15033   return DAG.getMergeValues({Load, LoadChain}, DL);
15034 }
15035 
performST1Combine(SDNode * N,SelectionDAG & DAG)15036 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
15037   SDLoc DL(N);
15038   SDValue Data = N->getOperand(2);
15039   EVT DataVT = Data.getValueType();
15040   EVT HwSrcVt = getSVEContainerType(DataVT);
15041   SDValue InputVT = DAG.getValueType(DataVT);
15042 
15043   if (DataVT == MVT::nxv8bf16 &&
15044       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15045     return SDValue();
15046 
15047   if (DataVT.isFloatingPoint())
15048     InputVT = DAG.getValueType(HwSrcVt);
15049 
15050   SDValue SrcNew;
15051   if (Data.getValueType().isFloatingPoint())
15052     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
15053   else
15054     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
15055 
15056   SDValue Ops[] = { N->getOperand(0), // Chain
15057                     SrcNew,
15058                     N->getOperand(4), // Base
15059                     N->getOperand(3), // Pg
15060                     InputVT
15061                   };
15062 
15063   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
15064 }
15065 
performSTNT1Combine(SDNode * N,SelectionDAG & DAG)15066 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
15067   SDLoc DL(N);
15068 
15069   SDValue Data = N->getOperand(2);
15070   EVT DataVT = Data.getValueType();
15071   EVT PtrTy = N->getOperand(4).getValueType();
15072 
15073   if (DataVT == MVT::nxv8bf16 &&
15074       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15075     return SDValue();
15076 
15077   if (DataVT.isFloatingPoint())
15078     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
15079 
15080   auto *MINode = cast<MemIntrinsicSDNode>(N);
15081   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
15082                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
15083                             MINode->getMemoryVT(), MINode->getMemOperand(),
15084                             ISD::UNINDEXED, false, false);
15085 }
15086 
15087 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
15088 /// load store optimizer pass will merge them to store pair stores.  This should
15089 /// be better than a movi to create the vector zero followed by a vector store
15090 /// if the zero constant is not re-used, since one instructions and one register
15091 /// live range will be removed.
15092 ///
15093 /// For example, the final generated code should be:
15094 ///
15095 ///   stp xzr, xzr, [x0]
15096 ///
15097 /// instead of:
15098 ///
15099 ///   movi v0.2d, #0
15100 ///   str q0, [x0]
15101 ///
replaceZeroVectorStore(SelectionDAG & DAG,StoreSDNode & St)15102 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
15103   SDValue StVal = St.getValue();
15104   EVT VT = StVal.getValueType();
15105 
15106   // Avoid scalarizing zero splat stores for scalable vectors.
15107   if (VT.isScalableVector())
15108     return SDValue();
15109 
15110   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
15111   // 2, 3 or 4 i32 elements.
15112   int NumVecElts = VT.getVectorNumElements();
15113   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
15114          VT.getVectorElementType().getSizeInBits() == 64) ||
15115         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
15116          VT.getVectorElementType().getSizeInBits() == 32)))
15117     return SDValue();
15118 
15119   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
15120     return SDValue();
15121 
15122   // If the zero constant has more than one use then the vector store could be
15123   // better since the constant mov will be amortized and stp q instructions
15124   // should be able to be formed.
15125   if (!StVal.hasOneUse())
15126     return SDValue();
15127 
15128   // If the store is truncating then it's going down to i16 or smaller, which
15129   // means it can be implemented in a single store anyway.
15130   if (St.isTruncatingStore())
15131     return SDValue();
15132 
15133   // If the immediate offset of the address operand is too large for the stp
15134   // instruction, then bail out.
15135   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
15136     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
15137     if (Offset < -512 || Offset > 504)
15138       return SDValue();
15139   }
15140 
15141   for (int I = 0; I < NumVecElts; ++I) {
15142     SDValue EltVal = StVal.getOperand(I);
15143     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
15144       return SDValue();
15145   }
15146 
15147   // Use a CopyFromReg WZR/XZR here to prevent
15148   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
15149   SDLoc DL(&St);
15150   unsigned ZeroReg;
15151   EVT ZeroVT;
15152   if (VT.getVectorElementType().getSizeInBits() == 32) {
15153     ZeroReg = AArch64::WZR;
15154     ZeroVT = MVT::i32;
15155   } else {
15156     ZeroReg = AArch64::XZR;
15157     ZeroVT = MVT::i64;
15158   }
15159   SDValue SplatVal =
15160       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
15161   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
15162 }
15163 
15164 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
15165 /// value. The load store optimizer pass will merge them to store pair stores.
15166 /// This has better performance than a splat of the scalar followed by a split
15167 /// vector store. Even if the stores are not merged it is four stores vs a dup,
15168 /// followed by an ext.b and two stores.
replaceSplatVectorStore(SelectionDAG & DAG,StoreSDNode & St)15169 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
15170   SDValue StVal = St.getValue();
15171   EVT VT = StVal.getValueType();
15172 
15173   // Don't replace floating point stores, they possibly won't be transformed to
15174   // stp because of the store pair suppress pass.
15175   if (VT.isFloatingPoint())
15176     return SDValue();
15177 
15178   // We can express a splat as store pair(s) for 2 or 4 elements.
15179   unsigned NumVecElts = VT.getVectorNumElements();
15180   if (NumVecElts != 4 && NumVecElts != 2)
15181     return SDValue();
15182 
15183   // If the store is truncating then it's going down to i16 or smaller, which
15184   // means it can be implemented in a single store anyway.
15185   if (St.isTruncatingStore())
15186     return SDValue();
15187 
15188   // Check that this is a splat.
15189   // Make sure that each of the relevant vector element locations are inserted
15190   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
15191   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
15192   SDValue SplatVal;
15193   for (unsigned I = 0; I < NumVecElts; ++I) {
15194     // Check for insert vector elements.
15195     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
15196       return SDValue();
15197 
15198     // Check that same value is inserted at each vector element.
15199     if (I == 0)
15200       SplatVal = StVal.getOperand(1);
15201     else if (StVal.getOperand(1) != SplatVal)
15202       return SDValue();
15203 
15204     // Check insert element index.
15205     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
15206     if (!CIndex)
15207       return SDValue();
15208     uint64_t IndexVal = CIndex->getZExtValue();
15209     if (IndexVal >= NumVecElts)
15210       return SDValue();
15211     IndexNotInserted.reset(IndexVal);
15212 
15213     StVal = StVal.getOperand(0);
15214   }
15215   // Check that all vector element locations were inserted to.
15216   if (IndexNotInserted.any())
15217       return SDValue();
15218 
15219   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
15220 }
15221 
splitStores(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)15222 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
15223                            SelectionDAG &DAG,
15224                            const AArch64Subtarget *Subtarget) {
15225 
15226   StoreSDNode *S = cast<StoreSDNode>(N);
15227   if (S->isVolatile() || S->isIndexed())
15228     return SDValue();
15229 
15230   SDValue StVal = S->getValue();
15231   EVT VT = StVal.getValueType();
15232 
15233   if (!VT.isFixedLengthVector())
15234     return SDValue();
15235 
15236   // If we get a splat of zeros, convert this vector store to a store of
15237   // scalars. They will be merged into store pairs of xzr thereby removing one
15238   // instruction and one register.
15239   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
15240     return ReplacedZeroSplat;
15241 
15242   // FIXME: The logic for deciding if an unaligned store should be split should
15243   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
15244   // a call to that function here.
15245 
15246   if (!Subtarget->isMisaligned128StoreSlow())
15247     return SDValue();
15248 
15249   // Don't split at -Oz.
15250   if (DAG.getMachineFunction().getFunction().hasMinSize())
15251     return SDValue();
15252 
15253   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
15254   // those up regresses performance on micro-benchmarks and olden/bh.
15255   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
15256     return SDValue();
15257 
15258   // Split unaligned 16B stores. They are terrible for performance.
15259   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
15260   // extensions can use this to mark that it does not want splitting to happen
15261   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
15262   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
15263   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
15264       S->getAlignment() <= 2)
15265     return SDValue();
15266 
15267   // If we get a splat of a scalar convert this vector store to a store of
15268   // scalars. They will be merged into store pairs thereby removing two
15269   // instructions.
15270   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
15271     return ReplacedSplat;
15272 
15273   SDLoc DL(S);
15274 
15275   // Split VT into two.
15276   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
15277   unsigned NumElts = HalfVT.getVectorNumElements();
15278   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
15279                                    DAG.getConstant(0, DL, MVT::i64));
15280   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
15281                                    DAG.getConstant(NumElts, DL, MVT::i64));
15282   SDValue BasePtr = S->getBasePtr();
15283   SDValue NewST1 =
15284       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
15285                    S->getAlignment(), S->getMemOperand()->getFlags());
15286   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
15287                                   DAG.getConstant(8, DL, MVT::i64));
15288   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
15289                       S->getPointerInfo(), S->getAlignment(),
15290                       S->getMemOperand()->getFlags());
15291 }
15292 
performSpliceCombine(SDNode * N,SelectionDAG & DAG)15293 static SDValue performSpliceCombine(SDNode *N, SelectionDAG &DAG) {
15294   assert(N->getOpcode() == AArch64ISD::SPLICE && "Unexepected Opcode!");
15295 
15296   // splice(pg, op1, undef) -> op1
15297   if (N->getOperand(2).isUndef())
15298     return N->getOperand(1);
15299 
15300   return SDValue();
15301 }
15302 
performUzpCombine(SDNode * N,SelectionDAG & DAG)15303 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
15304   SDLoc DL(N);
15305   SDValue Op0 = N->getOperand(0);
15306   SDValue Op1 = N->getOperand(1);
15307   EVT ResVT = N->getValueType(0);
15308 
15309   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
15310   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
15311     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
15312       SDValue X = Op0.getOperand(0).getOperand(0);
15313       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
15314     }
15315   }
15316 
15317   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
15318   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
15319     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
15320       SDValue Z = Op1.getOperand(0).getOperand(1);
15321       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
15322     }
15323   }
15324 
15325   return SDValue();
15326 }
15327 
performGLD1Combine(SDNode * N,SelectionDAG & DAG)15328 static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) {
15329   unsigned Opc = N->getOpcode();
15330 
15331   assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads
15332            Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) ||
15333           (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads
15334            Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) &&
15335          "Invalid opcode.");
15336 
15337   const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO ||
15338                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
15339   const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO ||
15340                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
15341   const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO ||
15342                         Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO ||
15343                         Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO ||
15344                         Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO;
15345 
15346   SDLoc DL(N);
15347   SDValue Chain = N->getOperand(0);
15348   SDValue Pg = N->getOperand(1);
15349   SDValue Base = N->getOperand(2);
15350   SDValue Offset = N->getOperand(3);
15351   SDValue Ty = N->getOperand(4);
15352 
15353   EVT ResVT = N->getValueType(0);
15354 
15355   const auto OffsetOpc = Offset.getOpcode();
15356   const bool OffsetIsZExt =
15357       OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU;
15358   const bool OffsetIsSExt =
15359       OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU;
15360 
15361   // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible.
15362   if (!Extended && (OffsetIsSExt || OffsetIsZExt)) {
15363     SDValue ExtPg = Offset.getOperand(0);
15364     VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode());
15365     EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType();
15366 
15367     // If the predicate for the sign- or zero-extended offset is the
15368     // same as the predicate used for this load and the sign-/zero-extension
15369     // was from a 32-bits...
15370     if (ExtPg == Pg && ExtFromEVT == MVT::i32) {
15371       SDValue UnextendedOffset = Offset.getOperand(1);
15372 
15373       unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true);
15374       if (Signed)
15375         NewOpc = getSignExtendedGatherOpcode(NewOpc);
15376 
15377       return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other},
15378                          {Chain, Pg, Base, UnextendedOffset, Ty});
15379     }
15380   }
15381 
15382   return SDValue();
15383 }
15384 
15385 /// Optimize a vector shift instruction and its operand if shifted out
15386 /// bits are not used.
performVectorShiftCombine(SDNode * N,const AArch64TargetLowering & TLI,TargetLowering::DAGCombinerInfo & DCI)15387 static SDValue performVectorShiftCombine(SDNode *N,
15388                                          const AArch64TargetLowering &TLI,
15389                                          TargetLowering::DAGCombinerInfo &DCI) {
15390   assert(N->getOpcode() == AArch64ISD::VASHR ||
15391          N->getOpcode() == AArch64ISD::VLSHR);
15392 
15393   SDValue Op = N->getOperand(0);
15394   unsigned OpScalarSize = Op.getScalarValueSizeInBits();
15395 
15396   unsigned ShiftImm = N->getConstantOperandVal(1);
15397   assert(OpScalarSize > ShiftImm && "Invalid shift imm");
15398 
15399   APInt ShiftedOutBits = APInt::getLowBitsSet(OpScalarSize, ShiftImm);
15400   APInt DemandedMask = ~ShiftedOutBits;
15401 
15402   if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15403     return SDValue(N, 0);
15404 
15405   return SDValue();
15406 }
15407 
15408 /// Target-specific DAG combine function for post-increment LD1 (lane) and
15409 /// post-increment LD1R.
performPostLD1Combine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,bool IsLaneOp)15410 static SDValue performPostLD1Combine(SDNode *N,
15411                                      TargetLowering::DAGCombinerInfo &DCI,
15412                                      bool IsLaneOp) {
15413   if (DCI.isBeforeLegalizeOps())
15414     return SDValue();
15415 
15416   SelectionDAG &DAG = DCI.DAG;
15417   EVT VT = N->getValueType(0);
15418 
15419   if (VT.isScalableVector())
15420     return SDValue();
15421 
15422   unsigned LoadIdx = IsLaneOp ? 1 : 0;
15423   SDNode *LD = N->getOperand(LoadIdx).getNode();
15424   // If it is not LOAD, can not do such combine.
15425   if (LD->getOpcode() != ISD::LOAD)
15426     return SDValue();
15427 
15428   // The vector lane must be a constant in the LD1LANE opcode.
15429   SDValue Lane;
15430   if (IsLaneOp) {
15431     Lane = N->getOperand(2);
15432     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
15433     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
15434       return SDValue();
15435   }
15436 
15437   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
15438   EVT MemVT = LoadSDN->getMemoryVT();
15439   // Check if memory operand is the same type as the vector element.
15440   if (MemVT != VT.getVectorElementType())
15441     return SDValue();
15442 
15443   // Check if there are other uses. If so, do not combine as it will introduce
15444   // an extra load.
15445   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
15446        ++UI) {
15447     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
15448       continue;
15449     if (*UI != N)
15450       return SDValue();
15451   }
15452 
15453   SDValue Addr = LD->getOperand(1);
15454   SDValue Vector = N->getOperand(0);
15455   // Search for a use of the address operand that is an increment.
15456   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
15457        Addr.getNode()->use_end(); UI != UE; ++UI) {
15458     SDNode *User = *UI;
15459     if (User->getOpcode() != ISD::ADD
15460         || UI.getUse().getResNo() != Addr.getResNo())
15461       continue;
15462 
15463     // If the increment is a constant, it must match the memory ref size.
15464     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15465     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
15466       uint32_t IncVal = CInc->getZExtValue();
15467       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
15468       if (IncVal != NumBytes)
15469         continue;
15470       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
15471     }
15472 
15473     // To avoid cycle construction make sure that neither the load nor the add
15474     // are predecessors to each other or the Vector.
15475     SmallPtrSet<const SDNode *, 32> Visited;
15476     SmallVector<const SDNode *, 16> Worklist;
15477     Visited.insert(Addr.getNode());
15478     Worklist.push_back(User);
15479     Worklist.push_back(LD);
15480     Worklist.push_back(Vector.getNode());
15481     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
15482         SDNode::hasPredecessorHelper(User, Visited, Worklist))
15483       continue;
15484 
15485     SmallVector<SDValue, 8> Ops;
15486     Ops.push_back(LD->getOperand(0));  // Chain
15487     if (IsLaneOp) {
15488       Ops.push_back(Vector);           // The vector to be inserted
15489       Ops.push_back(Lane);             // The lane to be inserted in the vector
15490     }
15491     Ops.push_back(Addr);
15492     Ops.push_back(Inc);
15493 
15494     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
15495     SDVTList SDTys = DAG.getVTList(Tys);
15496     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
15497     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
15498                                            MemVT,
15499                                            LoadSDN->getMemOperand());
15500 
15501     // Update the uses.
15502     SDValue NewResults[] = {
15503         SDValue(LD, 0),            // The result of load
15504         SDValue(UpdN.getNode(), 2) // Chain
15505     };
15506     DCI.CombineTo(LD, NewResults);
15507     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
15508     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
15509 
15510     break;
15511   }
15512   return SDValue();
15513 }
15514 
15515 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
15516 /// address translation.
performTBISimplification(SDValue Addr,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)15517 static bool performTBISimplification(SDValue Addr,
15518                                      TargetLowering::DAGCombinerInfo &DCI,
15519                                      SelectionDAG &DAG) {
15520   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
15521   KnownBits Known;
15522   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15523                                         !DCI.isBeforeLegalizeOps());
15524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15525   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
15526     DCI.CommitTargetLoweringOpt(TLO);
15527     return true;
15528   }
15529   return false;
15530 }
15531 
foldTruncStoreOfExt(SelectionDAG & DAG,SDNode * N)15532 static SDValue foldTruncStoreOfExt(SelectionDAG &DAG, SDNode *N) {
15533   assert((N->getOpcode() == ISD::STORE || N->getOpcode() == ISD::MSTORE) &&
15534          "Expected STORE dag node in input!");
15535 
15536   if (auto Store = dyn_cast<StoreSDNode>(N)) {
15537     if (!Store->isTruncatingStore() || Store->isIndexed())
15538       return SDValue();
15539     SDValue Ext = Store->getValue();
15540     auto ExtOpCode = Ext.getOpcode();
15541     if (ExtOpCode != ISD::ZERO_EXTEND && ExtOpCode != ISD::SIGN_EXTEND &&
15542         ExtOpCode != ISD::ANY_EXTEND)
15543       return SDValue();
15544     SDValue Orig = Ext->getOperand(0);
15545     if (Store->getMemoryVT() != Orig.getValueType())
15546       return SDValue();
15547     return DAG.getStore(Store->getChain(), SDLoc(Store), Orig,
15548                         Store->getBasePtr(), Store->getMemOperand());
15549   }
15550 
15551   return SDValue();
15552 }
15553 
performSTORECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)15554 static SDValue performSTORECombine(SDNode *N,
15555                                    TargetLowering::DAGCombinerInfo &DCI,
15556                                    SelectionDAG &DAG,
15557                                    const AArch64Subtarget *Subtarget) {
15558   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
15559     return Split;
15560 
15561   if (Subtarget->supportsAddressTopByteIgnored() &&
15562       performTBISimplification(N->getOperand(2), DCI, DAG))
15563     return SDValue(N, 0);
15564 
15565   if (SDValue Store = foldTruncStoreOfExt(DAG, N))
15566     return Store;
15567 
15568   return SDValue();
15569 }
15570 
15571 /// Target-specific DAG combine function for NEON load/store intrinsics
15572 /// to merge base address updates.
performNEONPostLDSTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)15573 static SDValue performNEONPostLDSTCombine(SDNode *N,
15574                                           TargetLowering::DAGCombinerInfo &DCI,
15575                                           SelectionDAG &DAG) {
15576   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15577     return SDValue();
15578 
15579   unsigned AddrOpIdx = N->getNumOperands() - 1;
15580   SDValue Addr = N->getOperand(AddrOpIdx);
15581 
15582   // Search for a use of the address operand that is an increment.
15583   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15584        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
15585     SDNode *User = *UI;
15586     if (User->getOpcode() != ISD::ADD ||
15587         UI.getUse().getResNo() != Addr.getResNo())
15588       continue;
15589 
15590     // Check that the add is independent of the load/store.  Otherwise, folding
15591     // it would create a cycle.
15592     SmallPtrSet<const SDNode *, 32> Visited;
15593     SmallVector<const SDNode *, 16> Worklist;
15594     Visited.insert(Addr.getNode());
15595     Worklist.push_back(N);
15596     Worklist.push_back(User);
15597     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15598         SDNode::hasPredecessorHelper(User, Visited, Worklist))
15599       continue;
15600 
15601     // Find the new opcode for the updating load/store.
15602     bool IsStore = false;
15603     bool IsLaneOp = false;
15604     bool IsDupOp = false;
15605     unsigned NewOpc = 0;
15606     unsigned NumVecs = 0;
15607     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15608     switch (IntNo) {
15609     default: llvm_unreachable("unexpected intrinsic for Neon base update");
15610     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
15611       NumVecs = 2; break;
15612     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
15613       NumVecs = 3; break;
15614     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
15615       NumVecs = 4; break;
15616     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
15617       NumVecs = 2; IsStore = true; break;
15618     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
15619       NumVecs = 3; IsStore = true; break;
15620     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
15621       NumVecs = 4; IsStore = true; break;
15622     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
15623       NumVecs = 2; break;
15624     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
15625       NumVecs = 3; break;
15626     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
15627       NumVecs = 4; break;
15628     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
15629       NumVecs = 2; IsStore = true; break;
15630     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
15631       NumVecs = 3; IsStore = true; break;
15632     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
15633       NumVecs = 4; IsStore = true; break;
15634     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
15635       NumVecs = 2; IsDupOp = true; break;
15636     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
15637       NumVecs = 3; IsDupOp = true; break;
15638     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
15639       NumVecs = 4; IsDupOp = true; break;
15640     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
15641       NumVecs = 2; IsLaneOp = true; break;
15642     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
15643       NumVecs = 3; IsLaneOp = true; break;
15644     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
15645       NumVecs = 4; IsLaneOp = true; break;
15646     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
15647       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
15648     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
15649       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
15650     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
15651       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
15652     }
15653 
15654     EVT VecTy;
15655     if (IsStore)
15656       VecTy = N->getOperand(2).getValueType();
15657     else
15658       VecTy = N->getValueType(0);
15659 
15660     // If the increment is a constant, it must match the memory ref size.
15661     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15662     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
15663       uint32_t IncVal = CInc->getZExtValue();
15664       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15665       if (IsLaneOp || IsDupOp)
15666         NumBytes /= VecTy.getVectorNumElements();
15667       if (IncVal != NumBytes)
15668         continue;
15669       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
15670     }
15671     SmallVector<SDValue, 8> Ops;
15672     Ops.push_back(N->getOperand(0)); // Incoming chain
15673     // Load lane and store have vector list as input.
15674     if (IsLaneOp || IsStore)
15675       for (unsigned i = 2; i < AddrOpIdx; ++i)
15676         Ops.push_back(N->getOperand(i));
15677     Ops.push_back(Addr); // Base register
15678     Ops.push_back(Inc);
15679 
15680     // Return Types.
15681     EVT Tys[6];
15682     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
15683     unsigned n;
15684     for (n = 0; n < NumResultVecs; ++n)
15685       Tys[n] = VecTy;
15686     Tys[n++] = MVT::i64;  // Type of write back register
15687     Tys[n] = MVT::Other;  // Type of the chain
15688     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
15689 
15690     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
15691     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
15692                                            MemInt->getMemoryVT(),
15693                                            MemInt->getMemOperand());
15694 
15695     // Update the uses.
15696     std::vector<SDValue> NewResults;
15697     for (unsigned i = 0; i < NumResultVecs; ++i) {
15698       NewResults.push_back(SDValue(UpdN.getNode(), i));
15699     }
15700     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
15701     DCI.CombineTo(N, NewResults);
15702     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
15703 
15704     break;
15705   }
15706   return SDValue();
15707 }
15708 
15709 // Checks to see if the value is the prescribed width and returns information
15710 // about its extension mode.
15711 static
checkValueWidth(SDValue V,unsigned width,ISD::LoadExtType & ExtType)15712 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
15713   ExtType = ISD::NON_EXTLOAD;
15714   switch(V.getNode()->getOpcode()) {
15715   default:
15716     return false;
15717   case ISD::LOAD: {
15718     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
15719     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
15720        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
15721       ExtType = LoadNode->getExtensionType();
15722       return true;
15723     }
15724     return false;
15725   }
15726   case ISD::AssertSext: {
15727     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
15728     if ((TypeNode->getVT() == MVT::i8 && width == 8)
15729        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
15730       ExtType = ISD::SEXTLOAD;
15731       return true;
15732     }
15733     return false;
15734   }
15735   case ISD::AssertZext: {
15736     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
15737     if ((TypeNode->getVT() == MVT::i8 && width == 8)
15738        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
15739       ExtType = ISD::ZEXTLOAD;
15740       return true;
15741     }
15742     return false;
15743   }
15744   case ISD::Constant:
15745   case ISD::TargetConstant: {
15746     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
15747            1LL << (width - 1);
15748   }
15749   }
15750 
15751   return true;
15752 }
15753 
15754 // This function does a whole lot of voodoo to determine if the tests are
15755 // equivalent without and with a mask. Essentially what happens is that given a
15756 // DAG resembling:
15757 //
15758 //  +-------------+ +-------------+ +-------------+ +-------------+
15759 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
15760 //  +-------------+ +-------------+ +-------------+ +-------------+
15761 //           |           |           |               |
15762 //           V           V           |    +----------+
15763 //          +-------------+  +----+  |    |
15764 //          |     ADD     |  |0xff|  |    |
15765 //          +-------------+  +----+  |    |
15766 //                  |           |    |    |
15767 //                  V           V    |    |
15768 //                 +-------------+   |    |
15769 //                 |     AND     |   |    |
15770 //                 +-------------+   |    |
15771 //                      |            |    |
15772 //                      +-----+      |    |
15773 //                            |      |    |
15774 //                            V      V    V
15775 //                           +-------------+
15776 //                           |     CMP     |
15777 //                           +-------------+
15778 //
15779 // The AND node may be safely removed for some combinations of inputs. In
15780 // particular we need to take into account the extension type of the Input,
15781 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
15782 // width of the input (this can work for any width inputs, the above graph is
15783 // specific to 8 bits.
15784 //
15785 // The specific equations were worked out by generating output tables for each
15786 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
15787 // problem was simplified by working with 4 bit inputs, which means we only
15788 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
15789 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
15790 // patterns present in both extensions (0,7). For every distinct set of
15791 // AddConstant and CompConstants bit patterns we can consider the masked and
15792 // unmasked versions to be equivalent if the result of this function is true for
15793 // all 16 distinct bit patterns of for the current extension type of Input (w0).
15794 //
15795 //   sub      w8, w0, w1
15796 //   and      w10, w8, #0x0f
15797 //   cmp      w8, w2
15798 //   cset     w9, AArch64CC
15799 //   cmp      w10, w2
15800 //   cset     w11, AArch64CC
15801 //   cmp      w9, w11
15802 //   cset     w0, eq
15803 //   ret
15804 //
15805 // Since the above function shows when the outputs are equivalent it defines
15806 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
15807 // would be expensive to run during compiles. The equations below were written
15808 // in a test harness that confirmed they gave equivalent outputs to the above
15809 // for all inputs function, so they can be used determine if the removal is
15810 // legal instead.
15811 //
15812 // isEquivalentMaskless() is the code for testing if the AND can be removed
15813 // factored out of the DAG recognition as the DAG can take several forms.
15814 
isEquivalentMaskless(unsigned CC,unsigned width,ISD::LoadExtType ExtType,int AddConstant,int CompConstant)15815 static bool isEquivalentMaskless(unsigned CC, unsigned width,
15816                                  ISD::LoadExtType ExtType, int AddConstant,
15817                                  int CompConstant) {
15818   // By being careful about our equations and only writing the in term
15819   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
15820   // make them generally applicable to all bit widths.
15821   int MaxUInt = (1 << width);
15822 
15823   // For the purposes of these comparisons sign extending the type is
15824   // equivalent to zero extending the add and displacing it by half the integer
15825   // width. Provided we are careful and make sure our equations are valid over
15826   // the whole range we can just adjust the input and avoid writing equations
15827   // for sign extended inputs.
15828   if (ExtType == ISD::SEXTLOAD)
15829     AddConstant -= (1 << (width-1));
15830 
15831   switch(CC) {
15832   case AArch64CC::LE:
15833   case AArch64CC::GT:
15834     if ((AddConstant == 0) ||
15835         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
15836         (AddConstant >= 0 && CompConstant < 0) ||
15837         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
15838       return true;
15839     break;
15840   case AArch64CC::LT:
15841   case AArch64CC::GE:
15842     if ((AddConstant == 0) ||
15843         (AddConstant >= 0 && CompConstant <= 0) ||
15844         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
15845       return true;
15846     break;
15847   case AArch64CC::HI:
15848   case AArch64CC::LS:
15849     if ((AddConstant >= 0 && CompConstant < 0) ||
15850        (AddConstant <= 0 && CompConstant >= -1 &&
15851         CompConstant < AddConstant + MaxUInt))
15852       return true;
15853    break;
15854   case AArch64CC::PL:
15855   case AArch64CC::MI:
15856     if ((AddConstant == 0) ||
15857         (AddConstant > 0 && CompConstant <= 0) ||
15858         (AddConstant < 0 && CompConstant <= AddConstant))
15859       return true;
15860     break;
15861   case AArch64CC::LO:
15862   case AArch64CC::HS:
15863     if ((AddConstant >= 0 && CompConstant <= 0) ||
15864         (AddConstant <= 0 && CompConstant >= 0 &&
15865          CompConstant <= AddConstant + MaxUInt))
15866       return true;
15867     break;
15868   case AArch64CC::EQ:
15869   case AArch64CC::NE:
15870     if ((AddConstant > 0 && CompConstant < 0) ||
15871         (AddConstant < 0 && CompConstant >= 0 &&
15872          CompConstant < AddConstant + MaxUInt) ||
15873         (AddConstant >= 0 && CompConstant >= 0 &&
15874          CompConstant >= AddConstant) ||
15875         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
15876       return true;
15877     break;
15878   case AArch64CC::VS:
15879   case AArch64CC::VC:
15880   case AArch64CC::AL:
15881   case AArch64CC::NV:
15882     return true;
15883   case AArch64CC::Invalid:
15884     break;
15885   }
15886 
15887   return false;
15888 }
15889 
15890 static
performCONDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG,unsigned CCIndex,unsigned CmpIndex)15891 SDValue performCONDCombine(SDNode *N,
15892                            TargetLowering::DAGCombinerInfo &DCI,
15893                            SelectionDAG &DAG, unsigned CCIndex,
15894                            unsigned CmpIndex) {
15895   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
15896   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
15897   unsigned CondOpcode = SubsNode->getOpcode();
15898 
15899   if (CondOpcode != AArch64ISD::SUBS)
15900     return SDValue();
15901 
15902   // There is a SUBS feeding this condition. Is it fed by a mask we can
15903   // use?
15904 
15905   SDNode *AndNode = SubsNode->getOperand(0).getNode();
15906   unsigned MaskBits = 0;
15907 
15908   if (AndNode->getOpcode() != ISD::AND)
15909     return SDValue();
15910 
15911   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
15912     uint32_t CNV = CN->getZExtValue();
15913     if (CNV == 255)
15914       MaskBits = 8;
15915     else if (CNV == 65535)
15916       MaskBits = 16;
15917   }
15918 
15919   if (!MaskBits)
15920     return SDValue();
15921 
15922   SDValue AddValue = AndNode->getOperand(0);
15923 
15924   if (AddValue.getOpcode() != ISD::ADD)
15925     return SDValue();
15926 
15927   // The basic dag structure is correct, grab the inputs and validate them.
15928 
15929   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
15930   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
15931   SDValue SubsInputValue = SubsNode->getOperand(1);
15932 
15933   // The mask is present and the provenance of all the values is a smaller type,
15934   // lets see if the mask is superfluous.
15935 
15936   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
15937       !isa<ConstantSDNode>(SubsInputValue.getNode()))
15938     return SDValue();
15939 
15940   ISD::LoadExtType ExtType;
15941 
15942   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
15943       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
15944       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
15945     return SDValue();
15946 
15947   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
15948                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
15949                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
15950     return SDValue();
15951 
15952   // The AND is not necessary, remove it.
15953 
15954   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
15955                                SubsNode->getValueType(1));
15956   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
15957 
15958   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
15959   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
15960 
15961   return SDValue(N, 0);
15962 }
15963 
15964 // Optimize compare with zero and branch.
performBRCONDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)15965 static SDValue performBRCONDCombine(SDNode *N,
15966                                     TargetLowering::DAGCombinerInfo &DCI,
15967                                     SelectionDAG &DAG) {
15968   MachineFunction &MF = DAG.getMachineFunction();
15969   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
15970   // will not be produced, as they are conditional branch instructions that do
15971   // not set flags.
15972   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
15973     return SDValue();
15974 
15975   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
15976     N = NV.getNode();
15977   SDValue Chain = N->getOperand(0);
15978   SDValue Dest = N->getOperand(1);
15979   SDValue CCVal = N->getOperand(2);
15980   SDValue Cmp = N->getOperand(3);
15981 
15982   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
15983   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
15984   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
15985     return SDValue();
15986 
15987   unsigned CmpOpc = Cmp.getOpcode();
15988   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
15989     return SDValue();
15990 
15991   // Only attempt folding if there is only one use of the flag and no use of the
15992   // value.
15993   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
15994     return SDValue();
15995 
15996   SDValue LHS = Cmp.getOperand(0);
15997   SDValue RHS = Cmp.getOperand(1);
15998 
15999   assert(LHS.getValueType() == RHS.getValueType() &&
16000          "Expected the value type to be the same for both operands!");
16001   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
16002     return SDValue();
16003 
16004   if (isNullConstant(LHS))
16005     std::swap(LHS, RHS);
16006 
16007   if (!isNullConstant(RHS))
16008     return SDValue();
16009 
16010   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
16011       LHS.getOpcode() == ISD::SRL)
16012     return SDValue();
16013 
16014   // Fold the compare into the branch instruction.
16015   SDValue BR;
16016   if (CC == AArch64CC::EQ)
16017     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
16018   else
16019     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
16020 
16021   // Do not add new nodes to DAG combiner worklist.
16022   DCI.CombineTo(N, BR, false);
16023 
16024   return SDValue();
16025 }
16026 
16027 // Optimize CSEL instructions
performCSELCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)16028 static SDValue performCSELCombine(SDNode *N,
16029                                   TargetLowering::DAGCombinerInfo &DCI,
16030                                   SelectionDAG &DAG) {
16031   // CSEL x, x, cc -> x
16032   if (N->getOperand(0) == N->getOperand(1))
16033     return N->getOperand(0);
16034 
16035   return performCONDCombine(N, DCI, DAG, 2, 3);
16036 }
16037 
performSETCCCombine(SDNode * N,SelectionDAG & DAG)16038 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16039   assert(N->getOpcode() == ISD::SETCC && "Unexpected opcode!");
16040   SDValue LHS = N->getOperand(0);
16041   SDValue RHS = N->getOperand(1);
16042   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
16043 
16044   // setcc (csel 0, 1, cond, X), 1, ne ==> csel 0, 1, !cond, X
16045   if (Cond == ISD::SETNE && isOneConstant(RHS) &&
16046       LHS->getOpcode() == AArch64ISD::CSEL &&
16047       isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
16048       LHS->hasOneUse()) {
16049     SDLoc DL(N);
16050 
16051     // Invert CSEL's condition.
16052     auto *OpCC = cast<ConstantSDNode>(LHS.getOperand(2));
16053     auto OldCond = static_cast<AArch64CC::CondCode>(OpCC->getZExtValue());
16054     auto NewCond = getInvertedCondCode(OldCond);
16055 
16056     // csel 0, 1, !cond, X
16057     SDValue CSEL =
16058         DAG.getNode(AArch64ISD::CSEL, DL, LHS.getValueType(), LHS.getOperand(0),
16059                     LHS.getOperand(1), DAG.getConstant(NewCond, DL, MVT::i32),
16060                     LHS.getOperand(3));
16061     return DAG.getZExtOrTrunc(CSEL, DL, N->getValueType(0));
16062   }
16063 
16064   return SDValue();
16065 }
16066 
performSetccMergeZeroCombine(SDNode * N,SelectionDAG & DAG)16067 static SDValue performSetccMergeZeroCombine(SDNode *N, SelectionDAG &DAG) {
16068   assert(N->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
16069          "Unexpected opcode!");
16070 
16071   SDValue Pred = N->getOperand(0);
16072   SDValue LHS = N->getOperand(1);
16073   SDValue RHS = N->getOperand(2);
16074   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
16075 
16076   // setcc_merge_zero pred (sign_extend (setcc_merge_zero ... pred ...)), 0, ne
16077   //    => inner setcc_merge_zero
16078   if (Cond == ISD::SETNE && isZerosVector(RHS.getNode()) &&
16079       LHS->getOpcode() == ISD::SIGN_EXTEND &&
16080       LHS->getOperand(0)->getValueType(0) == N->getValueType(0) &&
16081       LHS->getOperand(0)->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
16082       LHS->getOperand(0)->getOperand(0) == Pred)
16083     return LHS->getOperand(0);
16084 
16085   return SDValue();
16086 }
16087 
16088 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
16089 // as well as whether the test should be inverted.  This code is required to
16090 // catch these cases (as opposed to standard dag combines) because
16091 // AArch64ISD::TBZ is matched during legalization.
getTestBitOperand(SDValue Op,unsigned & Bit,bool & Invert,SelectionDAG & DAG)16092 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
16093                                  SelectionDAG &DAG) {
16094 
16095   if (!Op->hasOneUse())
16096     return Op;
16097 
16098   // We don't handle undef/constant-fold cases below, as they should have
16099   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
16100   // etc.)
16101 
16102   // (tbz (trunc x), b) -> (tbz x, b)
16103   // This case is just here to enable more of the below cases to be caught.
16104   if (Op->getOpcode() == ISD::TRUNCATE &&
16105       Bit < Op->getValueType(0).getSizeInBits()) {
16106     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16107   }
16108 
16109   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
16110   if (Op->getOpcode() == ISD::ANY_EXTEND &&
16111       Bit < Op->getOperand(0).getValueSizeInBits()) {
16112     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16113   }
16114 
16115   if (Op->getNumOperands() != 2)
16116     return Op;
16117 
16118   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
16119   if (!C)
16120     return Op;
16121 
16122   switch (Op->getOpcode()) {
16123   default:
16124     return Op;
16125 
16126   // (tbz (and x, m), b) -> (tbz x, b)
16127   case ISD::AND:
16128     if ((C->getZExtValue() >> Bit) & 1)
16129       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16130     return Op;
16131 
16132   // (tbz (shl x, c), b) -> (tbz x, b-c)
16133   case ISD::SHL:
16134     if (C->getZExtValue() <= Bit &&
16135         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
16136       Bit = Bit - C->getZExtValue();
16137       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16138     }
16139     return Op;
16140 
16141   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
16142   case ISD::SRA:
16143     Bit = Bit + C->getZExtValue();
16144     if (Bit >= Op->getValueType(0).getSizeInBits())
16145       Bit = Op->getValueType(0).getSizeInBits() - 1;
16146     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16147 
16148   // (tbz (srl x, c), b) -> (tbz x, b+c)
16149   case ISD::SRL:
16150     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
16151       Bit = Bit + C->getZExtValue();
16152       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16153     }
16154     return Op;
16155 
16156   // (tbz (xor x, -1), b) -> (tbnz x, b)
16157   case ISD::XOR:
16158     if ((C->getZExtValue() >> Bit) & 1)
16159       Invert = !Invert;
16160     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16161   }
16162 }
16163 
16164 // Optimize test single bit zero/non-zero and branch.
performTBZCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)16165 static SDValue performTBZCombine(SDNode *N,
16166                                  TargetLowering::DAGCombinerInfo &DCI,
16167                                  SelectionDAG &DAG) {
16168   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
16169   bool Invert = false;
16170   SDValue TestSrc = N->getOperand(1);
16171   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
16172 
16173   if (TestSrc == NewTestSrc)
16174     return SDValue();
16175 
16176   unsigned NewOpc = N->getOpcode();
16177   if (Invert) {
16178     if (NewOpc == AArch64ISD::TBZ)
16179       NewOpc = AArch64ISD::TBNZ;
16180     else {
16181       assert(NewOpc == AArch64ISD::TBNZ);
16182       NewOpc = AArch64ISD::TBZ;
16183     }
16184   }
16185 
16186   SDLoc DL(N);
16187   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
16188                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
16189 }
16190 
16191 // vselect (v1i1 setcc) ->
16192 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
16193 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
16194 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
16195 // such VSELECT.
performVSelectCombine(SDNode * N,SelectionDAG & DAG)16196 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
16197   SDValue N0 = N->getOperand(0);
16198   EVT CCVT = N0.getValueType();
16199 
16200   // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform
16201   // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
16202   // supported types.
16203   SDValue SetCC = N->getOperand(0);
16204   if (SetCC.getOpcode() == ISD::SETCC &&
16205       SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) {
16206     SDValue CmpLHS = SetCC.getOperand(0);
16207     EVT VT = CmpLHS.getValueType();
16208     SDNode *CmpRHS = SetCC.getOperand(1).getNode();
16209     SDNode *SplatLHS = N->getOperand(1).getNode();
16210     SDNode *SplatRHS = N->getOperand(2).getNode();
16211     APInt SplatLHSVal;
16212     if (CmpLHS.getValueType() == N->getOperand(1).getValueType() &&
16213         VT.isSimple() &&
16214         is_contained(
16215             makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
16216                           MVT::v2i32, MVT::v4i32, MVT::v2i64}),
16217             VT.getSimpleVT().SimpleTy) &&
16218         ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) &&
16219         SplatLHSVal.isOne() && ISD::isConstantSplatVectorAllOnes(CmpRHS) &&
16220         ISD::isConstantSplatVectorAllOnes(SplatRHS)) {
16221       unsigned NumElts = VT.getVectorNumElements();
16222       SmallVector<SDValue, 8> Ops(
16223           NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N),
16224                                    VT.getScalarType()));
16225       SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops);
16226 
16227       auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val);
16228       auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1));
16229       return Or;
16230     }
16231   }
16232 
16233   if (N0.getOpcode() != ISD::SETCC ||
16234       CCVT.getVectorElementCount() != ElementCount::getFixed(1) ||
16235       CCVT.getVectorElementType() != MVT::i1)
16236     return SDValue();
16237 
16238   EVT ResVT = N->getValueType(0);
16239   EVT CmpVT = N0.getOperand(0).getValueType();
16240   // Only combine when the result type is of the same size as the compared
16241   // operands.
16242   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
16243     return SDValue();
16244 
16245   SDValue IfTrue = N->getOperand(1);
16246   SDValue IfFalse = N->getOperand(2);
16247   SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
16248                        N0.getOperand(0), N0.getOperand(1),
16249                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
16250   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
16251                      IfTrue, IfFalse);
16252 }
16253 
16254 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
16255 /// the compare-mask instructions rather than going via NZCV, even if LHS and
16256 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
16257 /// with a vector one followed by a DUP shuffle on the result.
performSelectCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)16258 static SDValue performSelectCombine(SDNode *N,
16259                                     TargetLowering::DAGCombinerInfo &DCI) {
16260   SelectionDAG &DAG = DCI.DAG;
16261   SDValue N0 = N->getOperand(0);
16262   EVT ResVT = N->getValueType(0);
16263 
16264   if (N0.getOpcode() != ISD::SETCC)
16265     return SDValue();
16266 
16267   if (ResVT.isScalableVector())
16268     return SDValue();
16269 
16270   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
16271   // scalar SetCCResultType. We also don't expect vectors, because we assume
16272   // that selects fed by vector SETCCs are canonicalized to VSELECT.
16273   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
16274          "Scalar-SETCC feeding SELECT has unexpected result type!");
16275 
16276   // If NumMaskElts == 0, the comparison is larger than select result. The
16277   // largest real NEON comparison is 64-bits per lane, which means the result is
16278   // at most 32-bits and an illegal vector. Just bail out for now.
16279   EVT SrcVT = N0.getOperand(0).getValueType();
16280 
16281   // Don't try to do this optimization when the setcc itself has i1 operands.
16282   // There are no legal vectors of i1, so this would be pointless.
16283   if (SrcVT == MVT::i1)
16284     return SDValue();
16285 
16286   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
16287   if (!ResVT.isVector() || NumMaskElts == 0)
16288     return SDValue();
16289 
16290   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
16291   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
16292 
16293   // Also bail out if the vector CCVT isn't the same size as ResVT.
16294   // This can happen if the SETCC operand size doesn't divide the ResVT size
16295   // (e.g., f64 vs v3f32).
16296   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
16297     return SDValue();
16298 
16299   // Make sure we didn't create illegal types, if we're not supposed to.
16300   assert(DCI.isBeforeLegalize() ||
16301          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
16302 
16303   // First perform a vector comparison, where lane 0 is the one we're interested
16304   // in.
16305   SDLoc DL(N0);
16306   SDValue LHS =
16307       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
16308   SDValue RHS =
16309       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
16310   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
16311 
16312   // Now duplicate the comparison mask we want across all other lanes.
16313   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
16314   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
16315   Mask = DAG.getNode(ISD::BITCAST, DL,
16316                      ResVT.changeVectorElementTypeToInteger(), Mask);
16317 
16318   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
16319 }
16320 
16321 /// Get rid of unnecessary NVCASTs (that don't change the type).
performNVCASTCombine(SDNode * N)16322 static SDValue performNVCASTCombine(SDNode *N) {
16323   if (N->getValueType(0) == N->getOperand(0).getValueType())
16324     return N->getOperand(0);
16325 
16326   return SDValue();
16327 }
16328 
16329 // If all users of the globaladdr are of the form (globaladdr + constant), find
16330 // the smallest constant, fold it into the globaladdr's offset and rewrite the
16331 // globaladdr as (globaladdr + constant) - constant.
performGlobalAddressCombine(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * Subtarget,const TargetMachine & TM)16332 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
16333                                            const AArch64Subtarget *Subtarget,
16334                                            const TargetMachine &TM) {
16335   auto *GN = cast<GlobalAddressSDNode>(N);
16336   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
16337       AArch64II::MO_NO_FLAG)
16338     return SDValue();
16339 
16340   uint64_t MinOffset = -1ull;
16341   for (SDNode *N : GN->uses()) {
16342     if (N->getOpcode() != ISD::ADD)
16343       return SDValue();
16344     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
16345     if (!C)
16346       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16347     if (!C)
16348       return SDValue();
16349     MinOffset = std::min(MinOffset, C->getZExtValue());
16350   }
16351   uint64_t Offset = MinOffset + GN->getOffset();
16352 
16353   // Require that the new offset is larger than the existing one. Otherwise, we
16354   // can end up oscillating between two possible DAGs, for example,
16355   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
16356   if (Offset <= uint64_t(GN->getOffset()))
16357     return SDValue();
16358 
16359   // Check whether folding this offset is legal. It must not go out of bounds of
16360   // the referenced object to avoid violating the code model, and must be
16361   // smaller than 2^21 because this is the largest offset expressible in all
16362   // object formats.
16363   //
16364   // This check also prevents us from folding negative offsets, which will end
16365   // up being treated in the same way as large positive ones. They could also
16366   // cause code model violations, and aren't really common enough to matter.
16367   if (Offset >= (1 << 21))
16368     return SDValue();
16369 
16370   const GlobalValue *GV = GN->getGlobal();
16371   Type *T = GV->getValueType();
16372   if (!T->isSized() ||
16373       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
16374     return SDValue();
16375 
16376   SDLoc DL(GN);
16377   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
16378   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
16379                      DAG.getConstant(MinOffset, DL, MVT::i64));
16380 }
16381 
16382 // Turns the vector of indices into a vector of byte offstes by scaling Offset
16383 // by (BitWidth / 8).
getScaledOffsetForBitWidth(SelectionDAG & DAG,SDValue Offset,SDLoc DL,unsigned BitWidth)16384 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
16385                                           SDLoc DL, unsigned BitWidth) {
16386   assert(Offset.getValueType().isScalableVector() &&
16387          "This method is only for scalable vectors of offsets");
16388 
16389   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
16390   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
16391 
16392   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
16393 }
16394 
16395 /// Check if the value of \p OffsetInBytes can be used as an immediate for
16396 /// the gather load/prefetch and scatter store instructions with vector base and
16397 /// immediate offset addressing mode:
16398 ///
16399 ///      [<Zn>.[S|D]{, #<imm>}]
16400 ///
16401 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,unsigned ScalarSizeInBytes)16402 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
16403                                                   unsigned ScalarSizeInBytes) {
16404   // The immediate is not a multiple of the scalar size.
16405   if (OffsetInBytes % ScalarSizeInBytes)
16406     return false;
16407 
16408   // The immediate is out of range.
16409   if (OffsetInBytes / ScalarSizeInBytes > 31)
16410     return false;
16411 
16412   return true;
16413 }
16414 
16415 /// Check if the value of \p Offset represents a valid immediate for the SVE
16416 /// gather load/prefetch and scatter store instructiona with vector base and
16417 /// immediate offset addressing mode:
16418 ///
16419 ///      [<Zn>.[S|D]{, #<imm>}]
16420 ///
16421 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
isValidImmForSVEVecImmAddrMode(SDValue Offset,unsigned ScalarSizeInBytes)16422 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
16423                                            unsigned ScalarSizeInBytes) {
16424   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
16425   return OffsetConst && isValidImmForSVEVecImmAddrMode(
16426                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
16427 }
16428 
performScatterStoreCombine(SDNode * N,SelectionDAG & DAG,unsigned Opcode,bool OnlyPackedOffsets=true)16429 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
16430                                           unsigned Opcode,
16431                                           bool OnlyPackedOffsets = true) {
16432   const SDValue Src = N->getOperand(2);
16433   const EVT SrcVT = Src->getValueType(0);
16434   assert(SrcVT.isScalableVector() &&
16435          "Scatter stores are only possible for SVE vectors");
16436 
16437   SDLoc DL(N);
16438   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
16439 
16440   // Make sure that source data will fit into an SVE register
16441   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
16442     return SDValue();
16443 
16444   // For FPs, ACLE only supports _packed_ single and double precision types.
16445   if (SrcElVT.isFloatingPoint())
16446     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
16447       return SDValue();
16448 
16449   // Depending on the addressing mode, this is either a pointer or a vector of
16450   // pointers (that fits into one register)
16451   SDValue Base = N->getOperand(4);
16452   // Depending on the addressing mode, this is either a single offset or a
16453   // vector of offsets  (that fits into one register)
16454   SDValue Offset = N->getOperand(5);
16455 
16456   // For "scalar + vector of indices", just scale the indices. This only
16457   // applies to non-temporal scatters because there's no instruction that takes
16458   // indicies.
16459   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
16460     Offset =
16461         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
16462     Opcode = AArch64ISD::SSTNT1_PRED;
16463   }
16464 
16465   // In the case of non-temporal gather loads there's only one SVE instruction
16466   // per data-size: "scalar + vector", i.e.
16467   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
16468   // Since we do have intrinsics that allow the arguments to be in a different
16469   // order, we may need to swap them to match the spec.
16470   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
16471     std::swap(Base, Offset);
16472 
16473   // SST1_IMM requires that the offset is an immediate that is:
16474   //    * a multiple of #SizeInBytes,
16475   //    * in the range [0, 31 x #SizeInBytes],
16476   // where #SizeInBytes is the size in bytes of the stored items. For
16477   // immediates outside that range and non-immediate scalar offsets use SST1 or
16478   // SST1_UXTW instead.
16479   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
16480     if (!isValidImmForSVEVecImmAddrMode(Offset,
16481                                         SrcVT.getScalarSizeInBits() / 8)) {
16482       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
16483         Opcode = AArch64ISD::SST1_UXTW_PRED;
16484       else
16485         Opcode = AArch64ISD::SST1_PRED;
16486 
16487       std::swap(Base, Offset);
16488     }
16489   }
16490 
16491   auto &TLI = DAG.getTargetLoweringInfo();
16492   if (!TLI.isTypeLegal(Base.getValueType()))
16493     return SDValue();
16494 
16495   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
16496   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
16497   // nxv2i64. Legalize accordingly.
16498   if (!OnlyPackedOffsets &&
16499       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
16500     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
16501 
16502   if (!TLI.isTypeLegal(Offset.getValueType()))
16503     return SDValue();
16504 
16505   // Source value type that is representable in hardware
16506   EVT HwSrcVt = getSVEContainerType(SrcVT);
16507 
16508   // Keep the original type of the input data to store - this is needed to be
16509   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
16510   // FP values we want the integer equivalent, so just use HwSrcVt.
16511   SDValue InputVT = DAG.getValueType(SrcVT);
16512   if (SrcVT.isFloatingPoint())
16513     InputVT = DAG.getValueType(HwSrcVt);
16514 
16515   SDVTList VTs = DAG.getVTList(MVT::Other);
16516   SDValue SrcNew;
16517 
16518   if (Src.getValueType().isFloatingPoint())
16519     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
16520   else
16521     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
16522 
16523   SDValue Ops[] = {N->getOperand(0), // Chain
16524                    SrcNew,
16525                    N->getOperand(3), // Pg
16526                    Base,
16527                    Offset,
16528                    InputVT};
16529 
16530   return DAG.getNode(Opcode, DL, VTs, Ops);
16531 }
16532 
performGatherLoadCombine(SDNode * N,SelectionDAG & DAG,unsigned Opcode,bool OnlyPackedOffsets=true)16533 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
16534                                         unsigned Opcode,
16535                                         bool OnlyPackedOffsets = true) {
16536   const EVT RetVT = N->getValueType(0);
16537   assert(RetVT.isScalableVector() &&
16538          "Gather loads are only possible for SVE vectors");
16539 
16540   SDLoc DL(N);
16541 
16542   // Make sure that the loaded data will fit into an SVE register
16543   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
16544     return SDValue();
16545 
16546   // Depending on the addressing mode, this is either a pointer or a vector of
16547   // pointers (that fits into one register)
16548   SDValue Base = N->getOperand(3);
16549   // Depending on the addressing mode, this is either a single offset or a
16550   // vector of offsets  (that fits into one register)
16551   SDValue Offset = N->getOperand(4);
16552 
16553   // For "scalar + vector of indices", just scale the indices. This only
16554   // applies to non-temporal gathers because there's no instruction that takes
16555   // indicies.
16556   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
16557     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
16558                                         RetVT.getScalarSizeInBits());
16559     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
16560   }
16561 
16562   // In the case of non-temporal gather loads there's only one SVE instruction
16563   // per data-size: "scalar + vector", i.e.
16564   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
16565   // Since we do have intrinsics that allow the arguments to be in a different
16566   // order, we may need to swap them to match the spec.
16567   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
16568       Offset.getValueType().isVector())
16569     std::swap(Base, Offset);
16570 
16571   // GLD{FF}1_IMM requires that the offset is an immediate that is:
16572   //    * a multiple of #SizeInBytes,
16573   //    * in the range [0, 31 x #SizeInBytes],
16574   // where #SizeInBytes is the size in bytes of the loaded items. For
16575   // immediates outside that range and non-immediate scalar offsets use
16576   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
16577   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
16578       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
16579     if (!isValidImmForSVEVecImmAddrMode(Offset,
16580                                         RetVT.getScalarSizeInBits() / 8)) {
16581       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
16582         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
16583                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
16584                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
16585       else
16586         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
16587                      ? AArch64ISD::GLD1_MERGE_ZERO
16588                      : AArch64ISD::GLDFF1_MERGE_ZERO;
16589 
16590       std::swap(Base, Offset);
16591     }
16592   }
16593 
16594   auto &TLI = DAG.getTargetLoweringInfo();
16595   if (!TLI.isTypeLegal(Base.getValueType()))
16596     return SDValue();
16597 
16598   // Some gather load variants allow unpacked offsets, but only as nxv2i32
16599   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
16600   // nxv2i64. Legalize accordingly.
16601   if (!OnlyPackedOffsets &&
16602       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
16603     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
16604 
16605   // Return value type that is representable in hardware
16606   EVT HwRetVt = getSVEContainerType(RetVT);
16607 
16608   // Keep the original output value type around - this is needed to be able to
16609   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
16610   // values we want the integer equivalent, so just use HwRetVT.
16611   SDValue OutVT = DAG.getValueType(RetVT);
16612   if (RetVT.isFloatingPoint())
16613     OutVT = DAG.getValueType(HwRetVt);
16614 
16615   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
16616   SDValue Ops[] = {N->getOperand(0), // Chain
16617                    N->getOperand(2), // Pg
16618                    Base, Offset, OutVT};
16619 
16620   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
16621   SDValue LoadChain = SDValue(Load.getNode(), 1);
16622 
16623   if (RetVT.isInteger() && (RetVT != HwRetVt))
16624     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
16625 
16626   // If the original return value was FP, bitcast accordingly. Doing it here
16627   // means that we can avoid adding TableGen patterns for FPs.
16628   if (RetVT.isFloatingPoint())
16629     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
16630 
16631   return DAG.getMergeValues({Load, LoadChain}, DL);
16632 }
16633 
16634 static SDValue
performSignExtendInRegCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)16635 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
16636                               SelectionDAG &DAG) {
16637   SDLoc DL(N);
16638   SDValue Src = N->getOperand(0);
16639   unsigned Opc = Src->getOpcode();
16640 
16641   // Sign extend of an unsigned unpack -> signed unpack
16642   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
16643 
16644     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
16645                                                : AArch64ISD::SUNPKLO;
16646 
16647     // Push the sign extend to the operand of the unpack
16648     // This is necessary where, for example, the operand of the unpack
16649     // is another unpack:
16650     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
16651     // ->
16652     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
16653     // ->
16654     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
16655     SDValue ExtOp = Src->getOperand(0);
16656     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
16657     EVT EltTy = VT.getVectorElementType();
16658     (void)EltTy;
16659 
16660     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
16661            "Sign extending from an invalid type");
16662 
16663     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
16664 
16665     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
16666                               ExtOp, DAG.getValueType(ExtVT));
16667 
16668     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
16669   }
16670 
16671   if (DCI.isBeforeLegalizeOps())
16672     return SDValue();
16673 
16674   if (!EnableCombineMGatherIntrinsics)
16675     return SDValue();
16676 
16677   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
16678   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
16679   unsigned NewOpc;
16680   unsigned MemVTOpNum = 4;
16681   switch (Opc) {
16682   case AArch64ISD::LD1_MERGE_ZERO:
16683     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
16684     MemVTOpNum = 3;
16685     break;
16686   case AArch64ISD::LDNF1_MERGE_ZERO:
16687     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
16688     MemVTOpNum = 3;
16689     break;
16690   case AArch64ISD::LDFF1_MERGE_ZERO:
16691     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
16692     MemVTOpNum = 3;
16693     break;
16694   case AArch64ISD::GLD1_MERGE_ZERO:
16695     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
16696     break;
16697   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
16698     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
16699     break;
16700   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
16701     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
16702     break;
16703   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
16704     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
16705     break;
16706   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
16707     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
16708     break;
16709   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
16710     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
16711     break;
16712   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
16713     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
16714     break;
16715   case AArch64ISD::GLDFF1_MERGE_ZERO:
16716     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
16717     break;
16718   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
16719     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
16720     break;
16721   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
16722     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
16723     break;
16724   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
16725     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
16726     break;
16727   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
16728     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
16729     break;
16730   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
16731     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
16732     break;
16733   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
16734     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
16735     break;
16736   case AArch64ISD::GLDNT1_MERGE_ZERO:
16737     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
16738     break;
16739   default:
16740     return SDValue();
16741   }
16742 
16743   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
16744   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
16745 
16746   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
16747     return SDValue();
16748 
16749   EVT DstVT = N->getValueType(0);
16750   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
16751 
16752   SmallVector<SDValue, 5> Ops;
16753   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
16754     Ops.push_back(Src->getOperand(I));
16755 
16756   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
16757   DCI.CombineTo(N, ExtLoad);
16758   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
16759 
16760   // Return N so it doesn't get rechecked
16761   return SDValue(N, 0);
16762 }
16763 
16764 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
16765 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
16766 /// != nxv2i32) do not need legalization.
legalizeSVEGatherPrefetchOffsVec(SDNode * N,SelectionDAG & DAG)16767 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
16768   const unsigned OffsetPos = 4;
16769   SDValue Offset = N->getOperand(OffsetPos);
16770 
16771   // Not an unpacked vector, bail out.
16772   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
16773     return SDValue();
16774 
16775   // Extend the unpacked offset vector to 64-bit lanes.
16776   SDLoc DL(N);
16777   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
16778   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
16779   // Replace the offset operand with the 64-bit one.
16780   Ops[OffsetPos] = Offset;
16781 
16782   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
16783 }
16784 
16785 /// Combines a node carrying the intrinsic
16786 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
16787 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
16788 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
16789 /// sve gather prefetch instruction with vector plus immediate addressing mode.
combineSVEPrefetchVecBaseImmOff(SDNode * N,SelectionDAG & DAG,unsigned ScalarSizeInBytes)16790 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
16791                                                unsigned ScalarSizeInBytes) {
16792   const unsigned ImmPos = 4, OffsetPos = 3;
16793   // No need to combine the node if the immediate is valid...
16794   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
16795     return SDValue();
16796 
16797   // ...otherwise swap the offset base with the offset...
16798   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
16799   std::swap(Ops[ImmPos], Ops[OffsetPos]);
16800   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
16801   // `aarch64_sve_prfb_gather_uxtw_index`.
16802   SDLoc DL(N);
16803   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
16804                            MVT::i64);
16805 
16806   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
16807 }
16808 
16809 // Return true if the vector operation can guarantee only the first lane of its
16810 // result contains data, with all bits in other lanes set to zero.
isLanes1toNKnownZero(SDValue Op)16811 static bool isLanes1toNKnownZero(SDValue Op) {
16812   switch (Op.getOpcode()) {
16813   default:
16814     return false;
16815   case AArch64ISD::ANDV_PRED:
16816   case AArch64ISD::EORV_PRED:
16817   case AArch64ISD::FADDA_PRED:
16818   case AArch64ISD::FADDV_PRED:
16819   case AArch64ISD::FMAXNMV_PRED:
16820   case AArch64ISD::FMAXV_PRED:
16821   case AArch64ISD::FMINNMV_PRED:
16822   case AArch64ISD::FMINV_PRED:
16823   case AArch64ISD::ORV_PRED:
16824   case AArch64ISD::SADDV_PRED:
16825   case AArch64ISD::SMAXV_PRED:
16826   case AArch64ISD::SMINV_PRED:
16827   case AArch64ISD::UADDV_PRED:
16828   case AArch64ISD::UMAXV_PRED:
16829   case AArch64ISD::UMINV_PRED:
16830     return true;
16831   }
16832 }
16833 
removeRedundantInsertVectorElt(SDNode * N)16834 static SDValue removeRedundantInsertVectorElt(SDNode *N) {
16835   assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Unexpected node!");
16836   SDValue InsertVec = N->getOperand(0);
16837   SDValue InsertElt = N->getOperand(1);
16838   SDValue InsertIdx = N->getOperand(2);
16839 
16840   // We only care about inserts into the first element...
16841   if (!isNullConstant(InsertIdx))
16842     return SDValue();
16843   // ...of a zero'd vector...
16844   if (!ISD::isConstantSplatVectorAllZeros(InsertVec.getNode()))
16845     return SDValue();
16846   // ...where the inserted data was previously extracted...
16847   if (InsertElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16848     return SDValue();
16849 
16850   SDValue ExtractVec = InsertElt.getOperand(0);
16851   SDValue ExtractIdx = InsertElt.getOperand(1);
16852 
16853   // ...from the first element of a vector.
16854   if (!isNullConstant(ExtractIdx))
16855     return SDValue();
16856 
16857   // If we get here we are effectively trying to zero lanes 1-N of a vector.
16858 
16859   // Ensure there's no type conversion going on.
16860   if (N->getValueType(0) != ExtractVec.getValueType())
16861     return SDValue();
16862 
16863   if (!isLanes1toNKnownZero(ExtractVec))
16864     return SDValue();
16865 
16866   // The explicit zeroing is redundant.
16867   return ExtractVec;
16868 }
16869 
16870 static SDValue
performInsertVectorEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)16871 performInsertVectorEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
16872   if (SDValue Res = removeRedundantInsertVectorElt(N))
16873     return Res;
16874 
16875   return performPostLD1Combine(N, DCI, true);
16876 }
16877 
performSVESpliceCombine(SDNode * N,SelectionDAG & DAG)16878 SDValue performSVESpliceCombine(SDNode *N, SelectionDAG &DAG) {
16879   EVT Ty = N->getValueType(0);
16880   if (Ty.isInteger())
16881     return SDValue();
16882 
16883   EVT IntTy = Ty.changeVectorElementTypeToInteger();
16884   EVT ExtIntTy = getPackedSVEVectorVT(IntTy.getVectorElementCount());
16885   if (ExtIntTy.getVectorElementType().getScalarSizeInBits() <
16886       IntTy.getVectorElementType().getScalarSizeInBits())
16887     return SDValue();
16888 
16889   SDLoc DL(N);
16890   SDValue LHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(0)),
16891                                      DL, ExtIntTy);
16892   SDValue RHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(1)),
16893                                      DL, ExtIntTy);
16894   SDValue Idx = N->getOperand(2);
16895   SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ExtIntTy, LHS, RHS, Idx);
16896   SDValue Trunc = DAG.getAnyExtOrTrunc(Splice, DL, IntTy);
16897   return DAG.getBitcast(Ty, Trunc);
16898 }
16899 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const16900 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
16901                                                  DAGCombinerInfo &DCI) const {
16902   SelectionDAG &DAG = DCI.DAG;
16903   switch (N->getOpcode()) {
16904   default:
16905     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
16906     break;
16907   case ISD::ADD:
16908   case ISD::SUB:
16909     return performAddSubCombine(N, DCI, DAG);
16910   case ISD::XOR:
16911     return performXorCombine(N, DAG, DCI, Subtarget);
16912   case ISD::MUL:
16913     return performMulCombine(N, DAG, DCI, Subtarget);
16914   case ISD::SINT_TO_FP:
16915   case ISD::UINT_TO_FP:
16916     return performIntToFpCombine(N, DAG, Subtarget);
16917   case ISD::FP_TO_SINT:
16918   case ISD::FP_TO_UINT:
16919     return performFpToIntCombine(N, DAG, DCI, Subtarget);
16920   case ISD::FDIV:
16921     return performFDivCombine(N, DAG, DCI, Subtarget);
16922   case ISD::OR:
16923     return performORCombine(N, DCI, Subtarget);
16924   case ISD::AND:
16925     return performANDCombine(N, DCI);
16926   case ISD::SRL:
16927     return performSRLCombine(N, DCI);
16928   case ISD::INTRINSIC_WO_CHAIN:
16929     return performIntrinsicCombine(N, DCI, Subtarget);
16930   case ISD::ANY_EXTEND:
16931   case ISD::ZERO_EXTEND:
16932   case ISD::SIGN_EXTEND:
16933     return performExtendCombine(N, DCI, DAG);
16934   case ISD::SIGN_EXTEND_INREG:
16935     return performSignExtendInRegCombine(N, DCI, DAG);
16936   case ISD::TRUNCATE:
16937     return performVectorTruncateCombine(N, DCI, DAG);
16938   case ISD::CONCAT_VECTORS:
16939     return performConcatVectorsCombine(N, DCI, DAG);
16940   case ISD::INSERT_SUBVECTOR:
16941     return performInsertSubvectorCombine(N, DCI, DAG);
16942   case ISD::SELECT:
16943     return performSelectCombine(N, DCI);
16944   case ISD::VSELECT:
16945     return performVSelectCombine(N, DCI.DAG);
16946   case ISD::SETCC:
16947     return performSETCCCombine(N, DAG);
16948   case ISD::LOAD:
16949     if (performTBISimplification(N->getOperand(1), DCI, DAG))
16950       return SDValue(N, 0);
16951     break;
16952   case ISD::STORE:
16953     return performSTORECombine(N, DCI, DAG, Subtarget);
16954   case ISD::VECTOR_SPLICE:
16955     return performSVESpliceCombine(N, DAG);
16956   case AArch64ISD::BRCOND:
16957     return performBRCONDCombine(N, DCI, DAG);
16958   case AArch64ISD::TBNZ:
16959   case AArch64ISD::TBZ:
16960     return performTBZCombine(N, DCI, DAG);
16961   case AArch64ISD::CSEL:
16962     return performCSELCombine(N, DCI, DAG);
16963   case AArch64ISD::DUP:
16964     return performPostLD1Combine(N, DCI, false);
16965   case AArch64ISD::NVCAST:
16966     return performNVCASTCombine(N);
16967   case AArch64ISD::SPLICE:
16968     return performSpliceCombine(N, DAG);
16969   case AArch64ISD::UZP1:
16970     return performUzpCombine(N, DAG);
16971   case AArch64ISD::SETCC_MERGE_ZERO:
16972     return performSetccMergeZeroCombine(N, DAG);
16973   case AArch64ISD::GLD1_MERGE_ZERO:
16974   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
16975   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
16976   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
16977   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
16978   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
16979   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
16980   case AArch64ISD::GLD1S_MERGE_ZERO:
16981   case AArch64ISD::GLD1S_SCALED_MERGE_ZERO:
16982   case AArch64ISD::GLD1S_UXTW_MERGE_ZERO:
16983   case AArch64ISD::GLD1S_SXTW_MERGE_ZERO:
16984   case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO:
16985   case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO:
16986   case AArch64ISD::GLD1S_IMM_MERGE_ZERO:
16987     return performGLD1Combine(N, DAG);
16988   case AArch64ISD::VASHR:
16989   case AArch64ISD::VLSHR:
16990     return performVectorShiftCombine(N, *this, DCI);
16991   case ISD::INSERT_VECTOR_ELT:
16992     return performInsertVectorEltCombine(N, DCI);
16993   case ISD::EXTRACT_VECTOR_ELT:
16994     return performExtractVectorEltCombine(N, DAG);
16995   case ISD::VECREDUCE_ADD:
16996     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
16997   case ISD::INTRINSIC_VOID:
16998   case ISD::INTRINSIC_W_CHAIN:
16999     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
17000     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
17001       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
17002     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
17003       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
17004     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
17005       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
17006     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
17007       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
17008     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
17009     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
17010     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
17011     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
17012     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
17013     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
17014     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
17015     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
17016       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
17017     case Intrinsic::aarch64_neon_ld2:
17018     case Intrinsic::aarch64_neon_ld3:
17019     case Intrinsic::aarch64_neon_ld4:
17020     case Intrinsic::aarch64_neon_ld1x2:
17021     case Intrinsic::aarch64_neon_ld1x3:
17022     case Intrinsic::aarch64_neon_ld1x4:
17023     case Intrinsic::aarch64_neon_ld2lane:
17024     case Intrinsic::aarch64_neon_ld3lane:
17025     case Intrinsic::aarch64_neon_ld4lane:
17026     case Intrinsic::aarch64_neon_ld2r:
17027     case Intrinsic::aarch64_neon_ld3r:
17028     case Intrinsic::aarch64_neon_ld4r:
17029     case Intrinsic::aarch64_neon_st2:
17030     case Intrinsic::aarch64_neon_st3:
17031     case Intrinsic::aarch64_neon_st4:
17032     case Intrinsic::aarch64_neon_st1x2:
17033     case Intrinsic::aarch64_neon_st1x3:
17034     case Intrinsic::aarch64_neon_st1x4:
17035     case Intrinsic::aarch64_neon_st2lane:
17036     case Intrinsic::aarch64_neon_st3lane:
17037     case Intrinsic::aarch64_neon_st4lane:
17038       return performNEONPostLDSTCombine(N, DCI, DAG);
17039     case Intrinsic::aarch64_sve_ldnt1:
17040       return performLDNT1Combine(N, DAG);
17041     case Intrinsic::aarch64_sve_ld1rq:
17042       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
17043     case Intrinsic::aarch64_sve_ld1ro:
17044       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
17045     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
17046       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17047     case Intrinsic::aarch64_sve_ldnt1_gather:
17048       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17049     case Intrinsic::aarch64_sve_ldnt1_gather_index:
17050       return performGatherLoadCombine(N, DAG,
17051                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
17052     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
17053       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17054     case Intrinsic::aarch64_sve_ld1:
17055       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
17056     case Intrinsic::aarch64_sve_ldnf1:
17057       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
17058     case Intrinsic::aarch64_sve_ldff1:
17059       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
17060     case Intrinsic::aarch64_sve_st1:
17061       return performST1Combine(N, DAG);
17062     case Intrinsic::aarch64_sve_stnt1:
17063       return performSTNT1Combine(N, DAG);
17064     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
17065       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17066     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
17067       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17068     case Intrinsic::aarch64_sve_stnt1_scatter:
17069       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17070     case Intrinsic::aarch64_sve_stnt1_scatter_index:
17071       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
17072     case Intrinsic::aarch64_sve_ld1_gather:
17073       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
17074     case Intrinsic::aarch64_sve_ld1_gather_index:
17075       return performGatherLoadCombine(N, DAG,
17076                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
17077     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
17078       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
17079                                       /*OnlyPackedOffsets=*/false);
17080     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
17081       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
17082                                       /*OnlyPackedOffsets=*/false);
17083     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
17084       return performGatherLoadCombine(N, DAG,
17085                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
17086                                       /*OnlyPackedOffsets=*/false);
17087     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
17088       return performGatherLoadCombine(N, DAG,
17089                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
17090                                       /*OnlyPackedOffsets=*/false);
17091     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
17092       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
17093     case Intrinsic::aarch64_sve_ldff1_gather:
17094       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
17095     case Intrinsic::aarch64_sve_ldff1_gather_index:
17096       return performGatherLoadCombine(N, DAG,
17097                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
17098     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
17099       return performGatherLoadCombine(N, DAG,
17100                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
17101                                       /*OnlyPackedOffsets=*/false);
17102     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
17103       return performGatherLoadCombine(N, DAG,
17104                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
17105                                       /*OnlyPackedOffsets=*/false);
17106     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
17107       return performGatherLoadCombine(N, DAG,
17108                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
17109                                       /*OnlyPackedOffsets=*/false);
17110     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
17111       return performGatherLoadCombine(N, DAG,
17112                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
17113                                       /*OnlyPackedOffsets=*/false);
17114     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
17115       return performGatherLoadCombine(N, DAG,
17116                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
17117     case Intrinsic::aarch64_sve_st1_scatter:
17118       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
17119     case Intrinsic::aarch64_sve_st1_scatter_index:
17120       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
17121     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
17122       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
17123                                         /*OnlyPackedOffsets=*/false);
17124     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
17125       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
17126                                         /*OnlyPackedOffsets=*/false);
17127     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
17128       return performScatterStoreCombine(N, DAG,
17129                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
17130                                         /*OnlyPackedOffsets=*/false);
17131     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
17132       return performScatterStoreCombine(N, DAG,
17133                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
17134                                         /*OnlyPackedOffsets=*/false);
17135     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
17136       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
17137     case Intrinsic::aarch64_sve_tuple_get: {
17138       SDLoc DL(N);
17139       SDValue Chain = N->getOperand(0);
17140       SDValue Src1 = N->getOperand(2);
17141       SDValue Idx = N->getOperand(3);
17142 
17143       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
17144       EVT ResVT = N->getValueType(0);
17145       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
17146       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
17147       SDValue Val =
17148           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
17149       return DAG.getMergeValues({Val, Chain}, DL);
17150     }
17151     case Intrinsic::aarch64_sve_tuple_set: {
17152       SDLoc DL(N);
17153       SDValue Chain = N->getOperand(0);
17154       SDValue Tuple = N->getOperand(2);
17155       SDValue Idx = N->getOperand(3);
17156       SDValue Vec = N->getOperand(4);
17157 
17158       EVT TupleVT = Tuple.getValueType();
17159       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
17160 
17161       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
17162       uint64_t NumLanes =
17163           Vec.getValueType().getVectorElementCount().getKnownMinValue();
17164 
17165       if ((TupleLanes % NumLanes) != 0)
17166         report_fatal_error("invalid tuple vector!");
17167 
17168       uint64_t NumVecs = TupleLanes / NumLanes;
17169 
17170       SmallVector<SDValue, 4> Opnds;
17171       for (unsigned I = 0; I < NumVecs; ++I) {
17172         if (I == IdxConst)
17173           Opnds.push_back(Vec);
17174         else {
17175           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
17176           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
17177                                       Vec.getValueType(), Tuple, ExtIdx));
17178         }
17179       }
17180       SDValue Concat =
17181           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
17182       return DAG.getMergeValues({Concat, Chain}, DL);
17183     }
17184     case Intrinsic::aarch64_sve_tuple_create2:
17185     case Intrinsic::aarch64_sve_tuple_create3:
17186     case Intrinsic::aarch64_sve_tuple_create4: {
17187       SDLoc DL(N);
17188       SDValue Chain = N->getOperand(0);
17189 
17190       SmallVector<SDValue, 4> Opnds;
17191       for (unsigned I = 2; I < N->getNumOperands(); ++I)
17192         Opnds.push_back(N->getOperand(I));
17193 
17194       EVT VT = Opnds[0].getValueType();
17195       EVT EltVT = VT.getVectorElementType();
17196       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
17197                                     VT.getVectorElementCount() *
17198                                         (N->getNumOperands() - 2));
17199       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
17200       return DAG.getMergeValues({Concat, Chain}, DL);
17201     }
17202     case Intrinsic::aarch64_sve_ld2:
17203     case Intrinsic::aarch64_sve_ld3:
17204     case Intrinsic::aarch64_sve_ld4: {
17205       SDLoc DL(N);
17206       SDValue Chain = N->getOperand(0);
17207       SDValue Mask = N->getOperand(2);
17208       SDValue BasePtr = N->getOperand(3);
17209       SDValue LoadOps[] = {Chain, Mask, BasePtr};
17210       unsigned IntrinsicID =
17211           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17212       SDValue Result =
17213           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
17214       return DAG.getMergeValues({Result, Chain}, DL);
17215     }
17216     case Intrinsic::aarch64_rndr:
17217     case Intrinsic::aarch64_rndrrs: {
17218       unsigned IntrinsicID =
17219           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17220       auto Register =
17221           (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR
17222                                                   : AArch64SysReg::RNDRRS);
17223       SDLoc DL(N);
17224       SDValue A = DAG.getNode(
17225           AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other),
17226           N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64));
17227       SDValue B = DAG.getNode(
17228           AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32),
17229           DAG.getConstant(0, DL, MVT::i32),
17230           DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1));
17231       return DAG.getMergeValues(
17232           {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL);
17233     }
17234     default:
17235       break;
17236     }
17237     break;
17238   case ISD::GlobalAddress:
17239     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
17240   }
17241   return SDValue();
17242 }
17243 
17244 // Check if the return value is used as only a return value, as otherwise
17245 // we can't perform a tail-call. In particular, we need to check for
17246 // target ISD nodes that are returns and any other "odd" constructs
17247 // that the generic analysis code won't necessarily catch.
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const17248 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
17249                                                SDValue &Chain) const {
17250   if (N->getNumValues() != 1)
17251     return false;
17252   if (!N->hasNUsesOfValue(1, 0))
17253     return false;
17254 
17255   SDValue TCChain = Chain;
17256   SDNode *Copy = *N->use_begin();
17257   if (Copy->getOpcode() == ISD::CopyToReg) {
17258     // If the copy has a glue operand, we conservatively assume it isn't safe to
17259     // perform a tail call.
17260     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
17261         MVT::Glue)
17262       return false;
17263     TCChain = Copy->getOperand(0);
17264   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
17265     return false;
17266 
17267   bool HasRet = false;
17268   for (SDNode *Node : Copy->uses()) {
17269     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
17270       return false;
17271     HasRet = true;
17272   }
17273 
17274   if (!HasRet)
17275     return false;
17276 
17277   Chain = TCChain;
17278   return true;
17279 }
17280 
17281 // Return whether the an instruction can potentially be optimized to a tail
17282 // call. This will cause the optimizers to attempt to move, or duplicate,
17283 // return instructions to help enable tail call optimizations for this
17284 // instruction.
mayBeEmittedAsTailCall(const CallInst * CI) const17285 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17286   return CI->isTailCall();
17287 }
17288 
getIndexedAddressParts(SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,bool & IsInc,SelectionDAG & DAG) const17289 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
17290                                                    SDValue &Offset,
17291                                                    ISD::MemIndexedMode &AM,
17292                                                    bool &IsInc,
17293                                                    SelectionDAG &DAG) const {
17294   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
17295     return false;
17296 
17297   Base = Op->getOperand(0);
17298   // All of the indexed addressing mode instructions take a signed
17299   // 9 bit immediate offset.
17300   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
17301     int64_t RHSC = RHS->getSExtValue();
17302     if (Op->getOpcode() == ISD::SUB)
17303       RHSC = -(uint64_t)RHSC;
17304     if (!isInt<9>(RHSC))
17305       return false;
17306     IsInc = (Op->getOpcode() == ISD::ADD);
17307     Offset = Op->getOperand(1);
17308     return true;
17309   }
17310   return false;
17311 }
17312 
getPreIndexedAddressParts(SDNode * N,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const17313 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
17314                                                       SDValue &Offset,
17315                                                       ISD::MemIndexedMode &AM,
17316                                                       SelectionDAG &DAG) const {
17317   EVT VT;
17318   SDValue Ptr;
17319   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17320     VT = LD->getMemoryVT();
17321     Ptr = LD->getBasePtr();
17322   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17323     VT = ST->getMemoryVT();
17324     Ptr = ST->getBasePtr();
17325   } else
17326     return false;
17327 
17328   bool IsInc;
17329   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
17330     return false;
17331   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
17332   return true;
17333 }
17334 
getPostIndexedAddressParts(SDNode * N,SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const17335 bool AArch64TargetLowering::getPostIndexedAddressParts(
17336     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
17337     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
17338   EVT VT;
17339   SDValue Ptr;
17340   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17341     VT = LD->getMemoryVT();
17342     Ptr = LD->getBasePtr();
17343   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17344     VT = ST->getMemoryVT();
17345     Ptr = ST->getBasePtr();
17346   } else
17347     return false;
17348 
17349   bool IsInc;
17350   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
17351     return false;
17352   // Post-indexing updates the base, so it's not a valid transform
17353   // if that's not the same as the load's pointer.
17354   if (Ptr != Base)
17355     return false;
17356   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
17357   return true;
17358 }
17359 
ReplaceBITCASTResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const17360 void AArch64TargetLowering::ReplaceBITCASTResults(
17361     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
17362   SDLoc DL(N);
17363   SDValue Op = N->getOperand(0);
17364   EVT VT = N->getValueType(0);
17365   EVT SrcVT = Op.getValueType();
17366 
17367   if (VT.isScalableVector() && !isTypeLegal(VT) && isTypeLegal(SrcVT)) {
17368     assert(!VT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
17369            "Expected fp->int bitcast!");
17370     SDValue CastResult = getSVESafeBitCast(getSVEContainerType(VT), Op, DAG);
17371     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, CastResult));
17372     return;
17373   }
17374 
17375   if (VT != MVT::i16 || (SrcVT != MVT::f16 && SrcVT != MVT::bf16))
17376     return;
17377 
17378   Op = SDValue(
17379       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
17380                          DAG.getUNDEF(MVT::i32), Op,
17381                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
17382       0);
17383   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
17384   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
17385 }
17386 
ReplaceReductionResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,unsigned InterOp,unsigned AcrossOp)17387 static void ReplaceReductionResults(SDNode *N,
17388                                     SmallVectorImpl<SDValue> &Results,
17389                                     SelectionDAG &DAG, unsigned InterOp,
17390                                     unsigned AcrossOp) {
17391   EVT LoVT, HiVT;
17392   SDValue Lo, Hi;
17393   SDLoc dl(N);
17394   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
17395   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
17396   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
17397   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
17398   Results.push_back(SplitVal);
17399 }
17400 
splitInt128(SDValue N,SelectionDAG & DAG)17401 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
17402   SDLoc DL(N);
17403   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
17404   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
17405                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
17406                                        DAG.getConstant(64, DL, MVT::i64)));
17407   return std::make_pair(Lo, Hi);
17408 }
17409 
ReplaceExtractSubVectorResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const17410 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
17411     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
17412   SDValue In = N->getOperand(0);
17413   EVT InVT = In.getValueType();
17414 
17415   // Common code will handle these just fine.
17416   if (!InVT.isScalableVector() || !InVT.isInteger())
17417     return;
17418 
17419   SDLoc DL(N);
17420   EVT VT = N->getValueType(0);
17421 
17422   // The following checks bail if this is not a halving operation.
17423 
17424   ElementCount ResEC = VT.getVectorElementCount();
17425 
17426   if (InVT.getVectorElementCount() != (ResEC * 2))
17427     return;
17428 
17429   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
17430   if (!CIndex)
17431     return;
17432 
17433   unsigned Index = CIndex->getZExtValue();
17434   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
17435     return;
17436 
17437   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
17438   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
17439 
17440   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
17441   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
17442 }
17443 
17444 // Create an even/odd pair of X registers holding integer value V.
createGPRPairNode(SelectionDAG & DAG,SDValue V)17445 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
17446   SDLoc dl(V.getNode());
17447   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
17448   SDValue VHi = DAG.getAnyExtOrTrunc(
17449       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
17450       dl, MVT::i64);
17451   if (DAG.getDataLayout().isBigEndian())
17452     std::swap (VLo, VHi);
17453   SDValue RegClass =
17454       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
17455   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
17456   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
17457   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
17458   return SDValue(
17459       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
17460 }
17461 
ReplaceCMP_SWAP_128Results(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)17462 static void ReplaceCMP_SWAP_128Results(SDNode *N,
17463                                        SmallVectorImpl<SDValue> &Results,
17464                                        SelectionDAG &DAG,
17465                                        const AArch64Subtarget *Subtarget) {
17466   assert(N->getValueType(0) == MVT::i128 &&
17467          "AtomicCmpSwap on types less than 128 should be legal");
17468 
17469   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
17470   if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
17471     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
17472     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
17473     SDValue Ops[] = {
17474         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
17475         createGPRPairNode(DAG, N->getOperand(3)), // Store value
17476         N->getOperand(1), // Ptr
17477         N->getOperand(0), // Chain in
17478     };
17479 
17480     unsigned Opcode;
17481     switch (MemOp->getMergedOrdering()) {
17482     case AtomicOrdering::Monotonic:
17483       Opcode = AArch64::CASPX;
17484       break;
17485     case AtomicOrdering::Acquire:
17486       Opcode = AArch64::CASPAX;
17487       break;
17488     case AtomicOrdering::Release:
17489       Opcode = AArch64::CASPLX;
17490       break;
17491     case AtomicOrdering::AcquireRelease:
17492     case AtomicOrdering::SequentiallyConsistent:
17493       Opcode = AArch64::CASPALX;
17494       break;
17495     default:
17496       llvm_unreachable("Unexpected ordering!");
17497     }
17498 
17499     MachineSDNode *CmpSwap = DAG.getMachineNode(
17500         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
17501     DAG.setNodeMemRefs(CmpSwap, {MemOp});
17502 
17503     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
17504     if (DAG.getDataLayout().isBigEndian())
17505       std::swap(SubReg1, SubReg2);
17506     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
17507                                             SDValue(CmpSwap, 0));
17508     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
17509                                             SDValue(CmpSwap, 0));
17510     Results.push_back(
17511         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
17512     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
17513     return;
17514   }
17515 
17516   unsigned Opcode;
17517   switch (MemOp->getMergedOrdering()) {
17518   case AtomicOrdering::Monotonic:
17519     Opcode = AArch64::CMP_SWAP_128_MONOTONIC;
17520     break;
17521   case AtomicOrdering::Acquire:
17522     Opcode = AArch64::CMP_SWAP_128_ACQUIRE;
17523     break;
17524   case AtomicOrdering::Release:
17525     Opcode = AArch64::CMP_SWAP_128_RELEASE;
17526     break;
17527   case AtomicOrdering::AcquireRelease:
17528   case AtomicOrdering::SequentiallyConsistent:
17529     Opcode = AArch64::CMP_SWAP_128;
17530     break;
17531   default:
17532     llvm_unreachable("Unexpected ordering!");
17533   }
17534 
17535   auto Desired = splitInt128(N->getOperand(2), DAG);
17536   auto New = splitInt128(N->getOperand(3), DAG);
17537   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
17538                    New.first,        New.second,    N->getOperand(0)};
17539   SDNode *CmpSwap = DAG.getMachineNode(
17540       Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other),
17541       Ops);
17542   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
17543 
17544   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
17545                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
17546   Results.push_back(SDValue(CmpSwap, 3));
17547 }
17548 
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const17549 void AArch64TargetLowering::ReplaceNodeResults(
17550     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
17551   switch (N->getOpcode()) {
17552   default:
17553     llvm_unreachable("Don't know how to custom expand this");
17554   case ISD::BITCAST:
17555     ReplaceBITCASTResults(N, Results, DAG);
17556     return;
17557   case ISD::VECREDUCE_ADD:
17558   case ISD::VECREDUCE_SMAX:
17559   case ISD::VECREDUCE_SMIN:
17560   case ISD::VECREDUCE_UMAX:
17561   case ISD::VECREDUCE_UMIN:
17562     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
17563     return;
17564 
17565   case ISD::CTPOP:
17566     if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG))
17567       Results.push_back(Result);
17568     return;
17569   case AArch64ISD::SADDV:
17570     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
17571     return;
17572   case AArch64ISD::UADDV:
17573     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
17574     return;
17575   case AArch64ISD::SMINV:
17576     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
17577     return;
17578   case AArch64ISD::UMINV:
17579     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
17580     return;
17581   case AArch64ISD::SMAXV:
17582     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
17583     return;
17584   case AArch64ISD::UMAXV:
17585     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
17586     return;
17587   case ISD::FP_TO_UINT:
17588   case ISD::FP_TO_SINT:
17589   case ISD::STRICT_FP_TO_SINT:
17590   case ISD::STRICT_FP_TO_UINT:
17591     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
17592     // Let normal code take care of it by not adding anything to Results.
17593     return;
17594   case ISD::ATOMIC_CMP_SWAP:
17595     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
17596     return;
17597   case ISD::ATOMIC_LOAD:
17598   case ISD::LOAD: {
17599     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
17600            "unexpected load's value type");
17601     MemSDNode *LoadNode = cast<MemSDNode>(N);
17602     if ((!LoadNode->isVolatile() && !LoadNode->isAtomic()) ||
17603         LoadNode->getMemoryVT() != MVT::i128) {
17604       // Non-volatile or atomic loads are optimized later in AArch64's load/store
17605       // optimizer.
17606       return;
17607     }
17608 
17609     SDValue Result = DAG.getMemIntrinsicNode(
17610         AArch64ISD::LDP, SDLoc(N),
17611         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
17612         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
17613         LoadNode->getMemOperand());
17614 
17615     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
17616                                Result.getValue(0), Result.getValue(1));
17617     Results.append({Pair, Result.getValue(2) /* Chain */});
17618     return;
17619   }
17620   case ISD::EXTRACT_SUBVECTOR:
17621     ReplaceExtractSubVectorResults(N, Results, DAG);
17622     return;
17623   case ISD::INSERT_SUBVECTOR:
17624     // Custom lowering has been requested for INSERT_SUBVECTOR -- but delegate
17625     // to common code for result type legalisation
17626     return;
17627   case ISD::INTRINSIC_WO_CHAIN: {
17628     EVT VT = N->getValueType(0);
17629     assert((VT == MVT::i8 || VT == MVT::i16) &&
17630            "custom lowering for unexpected type");
17631 
17632     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
17633     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
17634     switch (IntID) {
17635     default:
17636       return;
17637     case Intrinsic::aarch64_sve_clasta_n: {
17638       SDLoc DL(N);
17639       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
17640       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
17641                            N->getOperand(1), Op2, N->getOperand(3));
17642       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17643       return;
17644     }
17645     case Intrinsic::aarch64_sve_clastb_n: {
17646       SDLoc DL(N);
17647       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
17648       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
17649                            N->getOperand(1), Op2, N->getOperand(3));
17650       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17651       return;
17652     }
17653     case Intrinsic::aarch64_sve_lasta: {
17654       SDLoc DL(N);
17655       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
17656                            N->getOperand(1), N->getOperand(2));
17657       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17658       return;
17659     }
17660     case Intrinsic::aarch64_sve_lastb: {
17661       SDLoc DL(N);
17662       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
17663                            N->getOperand(1), N->getOperand(2));
17664       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17665       return;
17666     }
17667     }
17668   }
17669   }
17670 }
17671 
useLoadStackGuardNode() const17672 bool AArch64TargetLowering::useLoadStackGuardNode() const {
17673   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
17674     return TargetLowering::useLoadStackGuardNode();
17675   return true;
17676 }
17677 
combineRepeatedFPDivisors() const17678 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
17679   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
17680   // reciprocal if there are three or more FDIVs.
17681   return 3;
17682 }
17683 
17684 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const17685 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
17686   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
17687   // v4i16, v2i32 instead of to promote.
17688   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
17689       VT == MVT::v1f32)
17690     return TypeWidenVector;
17691 
17692   return TargetLoweringBase::getPreferredVectorAction(VT);
17693 }
17694 
17695 // In v8.4a, ldp and stp instructions are guaranteed to be single-copy atomic
17696 // provided the address is 16-byte aligned.
isOpSuitableForLDPSTP(const Instruction * I) const17697 bool AArch64TargetLowering::isOpSuitableForLDPSTP(const Instruction *I) const {
17698   if (!Subtarget->hasLSE2())
17699     return false;
17700 
17701   if (auto LI = dyn_cast<LoadInst>(I))
17702     return LI->getType()->getPrimitiveSizeInBits() == 128 &&
17703            LI->getAlignment() >= 16;
17704 
17705   if (auto SI = dyn_cast<StoreInst>(I))
17706     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
17707            SI->getAlignment() >= 16;
17708 
17709   return false;
17710 }
17711 
shouldInsertFencesForAtomic(const Instruction * I) const17712 bool AArch64TargetLowering::shouldInsertFencesForAtomic(
17713     const Instruction *I) const {
17714   return isOpSuitableForLDPSTP(I);
17715 }
17716 
17717 // Loads and stores less than 128-bits are already atomic; ones above that
17718 // are doomed anyway, so defer to the default libcall and blame the OS when
17719 // things go wrong.
shouldExpandAtomicStoreInIR(StoreInst * SI) const17720 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17721   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
17722   if (Size != 128)
17723     return false;
17724 
17725   return !isOpSuitableForLDPSTP(SI);
17726 }
17727 
17728 // Loads and stores less than 128-bits are already atomic; ones above that
17729 // are doomed anyway, so defer to the default libcall and blame the OS when
17730 // things go wrong.
17731 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const17732 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17733   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
17734 
17735   if (Size != 128 || isOpSuitableForLDPSTP(LI))
17736     return AtomicExpansionKind::None;
17737 
17738   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17739   // implement atomicrmw without spilling. If the target address is also on the
17740   // stack and close enough to the spill slot, this can lead to a situation
17741   // where the monitor always gets cleared and the atomic operation can never
17742   // succeed. So at -O0 lower this operation to a CAS loop.
17743   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
17744     return AtomicExpansionKind::CmpXChg;
17745 
17746   return AtomicExpansionKind::LLSC;
17747 }
17748 
17749 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
17750 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const17751 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17752   if (AI->isFloatingPointOperation())
17753     return AtomicExpansionKind::CmpXChg;
17754 
17755   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17756   if (Size > 128) return AtomicExpansionKind::None;
17757 
17758   // Nand is not supported in LSE.
17759   // Leave 128 bits to LLSC or CmpXChg.
17760   if (AI->getOperation() != AtomicRMWInst::Nand && Size < 128) {
17761     if (Subtarget->hasLSE())
17762       return AtomicExpansionKind::None;
17763     if (Subtarget->outlineAtomics()) {
17764       // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
17765       // Don't outline them unless
17766       // (1) high level <atomic> support approved:
17767       //   http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
17768       // (2) low level libgcc and compiler-rt support implemented by:
17769       //   min/max outline atomics helpers
17770       if (AI->getOperation() != AtomicRMWInst::Min &&
17771           AI->getOperation() != AtomicRMWInst::Max &&
17772           AI->getOperation() != AtomicRMWInst::UMin &&
17773           AI->getOperation() != AtomicRMWInst::UMax) {
17774         return AtomicExpansionKind::None;
17775       }
17776     }
17777   }
17778 
17779   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17780   // implement atomicrmw without spilling. If the target address is also on the
17781   // stack and close enough to the spill slot, this can lead to a situation
17782   // where the monitor always gets cleared and the atomic operation can never
17783   // succeed. So at -O0 lower this operation to a CAS loop.
17784   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
17785     return AtomicExpansionKind::CmpXChg;
17786 
17787   return AtomicExpansionKind::LLSC;
17788 }
17789 
17790 TargetLowering::AtomicExpansionKind
shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst * AI) const17791 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
17792     AtomicCmpXchgInst *AI) const {
17793   // If subtarget has LSE, leave cmpxchg intact for codegen.
17794   if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
17795     return AtomicExpansionKind::None;
17796   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17797   // implement cmpxchg without spilling. If the address being exchanged is also
17798   // on the stack and close enough to the spill slot, this can lead to a
17799   // situation where the monitor always gets cleared and the atomic operation
17800   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
17801   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
17802     return AtomicExpansionKind::None;
17803 
17804   // 128-bit atomic cmpxchg is weird; AtomicExpand doesn't know how to expand
17805   // it.
17806   unsigned Size = AI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
17807   if (Size > 64)
17808     return AtomicExpansionKind::None;
17809 
17810   return AtomicExpansionKind::LLSC;
17811 }
17812 
emitLoadLinked(IRBuilderBase & Builder,Type * ValueTy,Value * Addr,AtomicOrdering Ord) const17813 Value *AArch64TargetLowering::emitLoadLinked(IRBuilderBase &Builder,
17814                                              Type *ValueTy, Value *Addr,
17815                                              AtomicOrdering Ord) const {
17816   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17817   bool IsAcquire = isAcquireOrStronger(Ord);
17818 
17819   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
17820   // intrinsic must return {i64, i64} and we have to recombine them into a
17821   // single i128 here.
17822   if (ValueTy->getPrimitiveSizeInBits() == 128) {
17823     Intrinsic::ID Int =
17824         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
17825     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
17826 
17827     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17828     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
17829 
17830     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17831     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17832     Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
17833     Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
17834     return Builder.CreateOr(
17835         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 64)), "val64");
17836   }
17837 
17838   Type *Tys[] = { Addr->getType() };
17839   Intrinsic::ID Int =
17840       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
17841   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
17842 
17843   const DataLayout &DL = M->getDataLayout();
17844   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(ValueTy));
17845   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
17846 
17847   return Builder.CreateBitCast(Trunc, ValueTy);
17848 }
17849 
emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase & Builder) const17850 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
17851     IRBuilderBase &Builder) const {
17852   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17853   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
17854 }
17855 
emitStoreConditional(IRBuilderBase & Builder,Value * Val,Value * Addr,AtomicOrdering Ord) const17856 Value *AArch64TargetLowering::emitStoreConditional(IRBuilderBase &Builder,
17857                                                    Value *Val, Value *Addr,
17858                                                    AtomicOrdering Ord) const {
17859   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17860   bool IsRelease = isReleaseOrStronger(Ord);
17861 
17862   // Since the intrinsics must have legal type, the i128 intrinsics take two
17863   // parameters: "i64, i64". We must marshal Val into the appropriate form
17864   // before the call.
17865   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
17866     Intrinsic::ID Int =
17867         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
17868     Function *Stxr = Intrinsic::getDeclaration(M, Int);
17869     Type *Int64Ty = Type::getInt64Ty(M->getContext());
17870 
17871     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
17872     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
17873     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17874     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
17875   }
17876 
17877   Intrinsic::ID Int =
17878       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
17879   Type *Tys[] = { Addr->getType() };
17880   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
17881 
17882   const DataLayout &DL = M->getDataLayout();
17883   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
17884   Val = Builder.CreateBitCast(Val, IntValTy);
17885 
17886   return Builder.CreateCall(Stxr,
17887                             {Builder.CreateZExtOrBitCast(
17888                                  Val, Stxr->getFunctionType()->getParamType(0)),
17889                              Addr});
17890 }
17891 
functionArgumentNeedsConsecutiveRegisters(Type * Ty,CallingConv::ID CallConv,bool isVarArg,const DataLayout & DL) const17892 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
17893     Type *Ty, CallingConv::ID CallConv, bool isVarArg,
17894     const DataLayout &DL) const {
17895   if (!Ty->isArrayTy()) {
17896     const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
17897     return TySize.isScalable() && TySize.getKnownMinSize() > 128;
17898   }
17899 
17900   // All non aggregate members of the type must have the same type
17901   SmallVector<EVT> ValueVTs;
17902   ComputeValueVTs(*this, DL, Ty, ValueVTs);
17903   return is_splat(ValueVTs);
17904 }
17905 
shouldNormalizeToSelectSequence(LLVMContext &,EVT) const17906 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
17907                                                             EVT) const {
17908   return false;
17909 }
17910 
UseTlsOffset(IRBuilderBase & IRB,unsigned Offset)17911 static Value *UseTlsOffset(IRBuilderBase &IRB, unsigned Offset) {
17912   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
17913   Function *ThreadPointerFunc =
17914       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
17915   return IRB.CreatePointerCast(
17916       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
17917                              Offset),
17918       IRB.getInt8PtrTy()->getPointerTo(0));
17919 }
17920 
getIRStackGuard(IRBuilderBase & IRB) const17921 Value *AArch64TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
17922   // Android provides a fixed TLS slot for the stack cookie. See the definition
17923   // of TLS_SLOT_STACK_GUARD in
17924   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
17925   if (Subtarget->isTargetAndroid())
17926     return UseTlsOffset(IRB, 0x28);
17927 
17928   // Fuchsia is similar.
17929   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
17930   if (Subtarget->isTargetFuchsia())
17931     return UseTlsOffset(IRB, -0x10);
17932 
17933   return TargetLowering::getIRStackGuard(IRB);
17934 }
17935 
insertSSPDeclarations(Module & M) const17936 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
17937   // MSVC CRT provides functionalities for stack protection.
17938   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
17939     // MSVC CRT has a global variable holding security cookie.
17940     M.getOrInsertGlobal("__security_cookie",
17941                         Type::getInt8PtrTy(M.getContext()));
17942 
17943     // MSVC CRT has a function to validate security cookie.
17944     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
17945         "__security_check_cookie", Type::getVoidTy(M.getContext()),
17946         Type::getInt8PtrTy(M.getContext()));
17947     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
17948       F->setCallingConv(CallingConv::Win64);
17949       F->addParamAttr(0, Attribute::AttrKind::InReg);
17950     }
17951     return;
17952   }
17953   TargetLowering::insertSSPDeclarations(M);
17954 }
17955 
getSDagStackGuard(const Module & M) const17956 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
17957   // MSVC CRT has a global variable holding security cookie.
17958   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17959     return M.getGlobalVariable("__security_cookie");
17960   return TargetLowering::getSDagStackGuard(M);
17961 }
17962 
getSSPStackGuardCheck(const Module & M) const17963 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
17964   // MSVC CRT has a function to validate security cookie.
17965   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17966     return M.getFunction("__security_check_cookie");
17967   return TargetLowering::getSSPStackGuardCheck(M);
17968 }
17969 
17970 Value *
getSafeStackPointerLocation(IRBuilderBase & IRB) const17971 AArch64TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
17972   // Android provides a fixed TLS slot for the SafeStack pointer. See the
17973   // definition of TLS_SLOT_SAFESTACK in
17974   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
17975   if (Subtarget->isTargetAndroid())
17976     return UseTlsOffset(IRB, 0x48);
17977 
17978   // Fuchsia is similar.
17979   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
17980   if (Subtarget->isTargetFuchsia())
17981     return UseTlsOffset(IRB, -0x8);
17982 
17983   return TargetLowering::getSafeStackPointerLocation(IRB);
17984 }
17985 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const17986 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
17987     const Instruction &AndI) const {
17988   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
17989   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
17990   // may be beneficial to sink in other cases, but we would have to check that
17991   // the cmp would not get folded into the br to form a cbz for these to be
17992   // beneficial.
17993   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
17994   if (!Mask)
17995     return false;
17996   return Mask->getValue().isPowerOf2();
17997 }
17998 
17999 bool AArch64TargetLowering::
shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X,ConstantSDNode * XC,ConstantSDNode * CC,SDValue Y,unsigned OldShiftOpcode,unsigned NewShiftOpcode,SelectionDAG & DAG) const18000     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
18001         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
18002         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
18003         SelectionDAG &DAG) const {
18004   // Does baseline recommend not to perform the fold by default?
18005   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
18006           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
18007     return false;
18008   // Else, if this is a vector shift, prefer 'shl'.
18009   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
18010 }
18011 
shouldExpandShift(SelectionDAG & DAG,SDNode * N) const18012 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
18013                                               SDNode *N) const {
18014   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
18015       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
18016     return false;
18017   return true;
18018 }
18019 
initializeSplitCSR(MachineBasicBlock * Entry) const18020 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
18021   // Update IsSplitCSR in AArch64unctionInfo.
18022   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
18023   AFI->setIsSplitCSR(true);
18024 }
18025 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const18026 void AArch64TargetLowering::insertCopiesSplitCSR(
18027     MachineBasicBlock *Entry,
18028     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
18029   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
18030   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
18031   if (!IStart)
18032     return;
18033 
18034   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18035   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
18036   MachineBasicBlock::iterator MBBI = Entry->begin();
18037   for (const MCPhysReg *I = IStart; *I; ++I) {
18038     const TargetRegisterClass *RC = nullptr;
18039     if (AArch64::GPR64RegClass.contains(*I))
18040       RC = &AArch64::GPR64RegClass;
18041     else if (AArch64::FPR64RegClass.contains(*I))
18042       RC = &AArch64::FPR64RegClass;
18043     else
18044       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
18045 
18046     Register NewVR = MRI->createVirtualRegister(RC);
18047     // Create copy from CSR to a virtual register.
18048     // FIXME: this currently does not emit CFI pseudo-instructions, it works
18049     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
18050     // nounwind. If we want to generalize this later, we may need to emit
18051     // CFI pseudo-instructions.
18052     assert(Entry->getParent()->getFunction().hasFnAttribute(
18053                Attribute::NoUnwind) &&
18054            "Function should be nounwind in insertCopiesSplitCSR!");
18055     Entry->addLiveIn(*I);
18056     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
18057         .addReg(*I);
18058 
18059     // Insert the copy-back instructions right before the terminator.
18060     for (auto *Exit : Exits)
18061       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
18062               TII->get(TargetOpcode::COPY), *I)
18063           .addReg(NewVR);
18064   }
18065 }
18066 
isIntDivCheap(EVT VT,AttributeList Attr) const18067 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
18068   // Integer division on AArch64 is expensive. However, when aggressively
18069   // optimizing for code size, we prefer to use a div instruction, as it is
18070   // usually smaller than the alternative sequence.
18071   // The exception to this is vector division. Since AArch64 doesn't have vector
18072   // integer division, leaving the division as-is is a loss even in terms of
18073   // size, because it will have to be scalarized, while the alternative code
18074   // sequence can be performed in vector form.
18075   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
18076   return OptSize && !VT.isVector();
18077 }
18078 
preferIncOfAddToSubOfNot(EVT VT) const18079 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
18080   // We want inc-of-add for scalars and sub-of-not for vectors.
18081   return VT.isScalarInteger();
18082 }
18083 
enableAggressiveFMAFusion(EVT VT) const18084 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
18085   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
18086 }
18087 
18088 unsigned
getVaListSizeInBits(const DataLayout & DL) const18089 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
18090   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
18091     return getPointerTy(DL).getSizeInBits();
18092 
18093   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
18094 }
18095 
finalizeLowering(MachineFunction & MF) const18096 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
18097   MF.getFrameInfo().computeMaxCallFrameSize(MF);
18098   TargetLoweringBase::finalizeLowering(MF);
18099 }
18100 
18101 // Unlike X86, we let frame lowering assign offsets to all catch objects.
needsFixedCatchObjects() const18102 bool AArch64TargetLowering::needsFixedCatchObjects() const {
18103   return false;
18104 }
18105 
shouldLocalize(const MachineInstr & MI,const TargetTransformInfo * TTI) const18106 bool AArch64TargetLowering::shouldLocalize(
18107     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
18108   switch (MI.getOpcode()) {
18109   case TargetOpcode::G_GLOBAL_VALUE: {
18110     // On Darwin, TLS global vars get selected into function calls, which
18111     // we don't want localized, as they can get moved into the middle of a
18112     // another call sequence.
18113     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
18114     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
18115       return false;
18116     break;
18117   }
18118   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
18119   // localizable.
18120   case AArch64::ADRP:
18121   case AArch64::G_ADD_LOW:
18122     return true;
18123   default:
18124     break;
18125   }
18126   return TargetLoweringBase::shouldLocalize(MI, TTI);
18127 }
18128 
fallBackToDAGISel(const Instruction & Inst) const18129 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
18130   if (isa<ScalableVectorType>(Inst.getType()))
18131     return true;
18132 
18133   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
18134     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
18135       return true;
18136 
18137   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
18138     if (isa<ScalableVectorType>(AI->getAllocatedType()))
18139       return true;
18140   }
18141 
18142   return false;
18143 }
18144 
18145 // Return the largest legal scalable vector type that matches VT's element type.
getContainerForFixedLengthVector(SelectionDAG & DAG,EVT VT)18146 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
18147   assert(VT.isFixedLengthVector() &&
18148          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18149          "Expected legal fixed length vector!");
18150   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
18151   default:
18152     llvm_unreachable("unexpected element type for SVE container");
18153   case MVT::i8:
18154     return EVT(MVT::nxv16i8);
18155   case MVT::i16:
18156     return EVT(MVT::nxv8i16);
18157   case MVT::i32:
18158     return EVT(MVT::nxv4i32);
18159   case MVT::i64:
18160     return EVT(MVT::nxv2i64);
18161   case MVT::f16:
18162     return EVT(MVT::nxv8f16);
18163   case MVT::f32:
18164     return EVT(MVT::nxv4f32);
18165   case MVT::f64:
18166     return EVT(MVT::nxv2f64);
18167   }
18168 }
18169 
18170 // Return a PTRUE with active lanes corresponding to the extent of VT.
getPredicateForFixedLengthVector(SelectionDAG & DAG,SDLoc & DL,EVT VT)18171 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
18172                                                 EVT VT) {
18173   assert(VT.isFixedLengthVector() &&
18174          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18175          "Expected legal fixed length vector!");
18176 
18177   unsigned PgPattern =
18178       getSVEPredPatternFromNumElements(VT.getVectorNumElements());
18179   assert(PgPattern && "Unexpected element count for SVE predicate");
18180 
18181   // For vectors that are exactly getMaxSVEVectorSizeInBits big, we can use
18182   // AArch64SVEPredPattern::all, which can enable the use of unpredicated
18183   // variants of instructions when available.
18184   const auto &Subtarget =
18185       static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
18186   unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
18187   unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
18188   if (MaxSVESize && MinSVESize == MaxSVESize &&
18189       MaxSVESize == VT.getSizeInBits())
18190     PgPattern = AArch64SVEPredPattern::all;
18191 
18192   MVT MaskVT;
18193   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
18194   default:
18195     llvm_unreachable("unexpected element type for SVE predicate");
18196   case MVT::i8:
18197     MaskVT = MVT::nxv16i1;
18198     break;
18199   case MVT::i16:
18200   case MVT::f16:
18201     MaskVT = MVT::nxv8i1;
18202     break;
18203   case MVT::i32:
18204   case MVT::f32:
18205     MaskVT = MVT::nxv4i1;
18206     break;
18207   case MVT::i64:
18208   case MVT::f64:
18209     MaskVT = MVT::nxv2i1;
18210     break;
18211   }
18212 
18213   return getPTrue(DAG, DL, MaskVT, PgPattern);
18214 }
18215 
getPredicateForScalableVector(SelectionDAG & DAG,SDLoc & DL,EVT VT)18216 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
18217                                              EVT VT) {
18218   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18219          "Expected legal scalable vector!");
18220   auto PredTy = VT.changeVectorElementType(MVT::i1);
18221   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
18222 }
18223 
getPredicateForVector(SelectionDAG & DAG,SDLoc & DL,EVT VT)18224 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
18225   if (VT.isFixedLengthVector())
18226     return getPredicateForFixedLengthVector(DAG, DL, VT);
18227 
18228   return getPredicateForScalableVector(DAG, DL, VT);
18229 }
18230 
18231 // Grow V to consume an entire SVE register.
convertToScalableVector(SelectionDAG & DAG,EVT VT,SDValue V)18232 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
18233   assert(VT.isScalableVector() &&
18234          "Expected to convert into a scalable vector!");
18235   assert(V.getValueType().isFixedLengthVector() &&
18236          "Expected a fixed length vector operand!");
18237   SDLoc DL(V);
18238   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18239   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
18240 }
18241 
18242 // Shrink V so it's just big enough to maintain a VT's worth of data.
convertFromScalableVector(SelectionDAG & DAG,EVT VT,SDValue V)18243 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
18244   assert(VT.isFixedLengthVector() &&
18245          "Expected to convert into a fixed length vector!");
18246   assert(V.getValueType().isScalableVector() &&
18247          "Expected a scalable vector operand!");
18248   SDLoc DL(V);
18249   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18250   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
18251 }
18252 
18253 // Convert all fixed length vector loads larger than NEON to masked_loads.
LowerFixedLengthVectorLoadToSVE(SDValue Op,SelectionDAG & DAG) const18254 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
18255     SDValue Op, SelectionDAG &DAG) const {
18256   auto Load = cast<LoadSDNode>(Op);
18257 
18258   SDLoc DL(Op);
18259   EVT VT = Op.getValueType();
18260   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18261 
18262   auto NewLoad = DAG.getMaskedLoad(
18263       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
18264       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
18265       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
18266       Load->getExtensionType());
18267 
18268   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
18269   SDValue MergedValues[2] = {Result, Load->getChain()};
18270   return DAG.getMergeValues(MergedValues, DL);
18271 }
18272 
convertFixedMaskToScalableVector(SDValue Mask,SelectionDAG & DAG)18273 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
18274                                                 SelectionDAG &DAG) {
18275   SDLoc DL(Mask);
18276   EVT InVT = Mask.getValueType();
18277   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18278 
18279   auto Op1 = convertToScalableVector(DAG, ContainerVT, Mask);
18280   auto Op2 = DAG.getConstant(0, DL, ContainerVT);
18281   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
18282 
18283   EVT CmpVT = Pg.getValueType();
18284   return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
18285                      {Pg, Op1, Op2, DAG.getCondCode(ISD::SETNE)});
18286 }
18287 
18288 // Convert all fixed length vector loads larger than NEON to masked_loads.
LowerFixedLengthVectorMLoadToSVE(SDValue Op,SelectionDAG & DAG) const18289 SDValue AArch64TargetLowering::LowerFixedLengthVectorMLoadToSVE(
18290     SDValue Op, SelectionDAG &DAG) const {
18291   auto Load = cast<MaskedLoadSDNode>(Op);
18292 
18293   SDLoc DL(Op);
18294   EVT VT = Op.getValueType();
18295   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18296 
18297   SDValue Mask = convertFixedMaskToScalableVector(Load->getMask(), DAG);
18298 
18299   SDValue PassThru;
18300   bool IsPassThruZeroOrUndef = false;
18301 
18302   if (Load->getPassThru()->isUndef()) {
18303     PassThru = DAG.getUNDEF(ContainerVT);
18304     IsPassThruZeroOrUndef = true;
18305   } else {
18306     if (ContainerVT.isInteger())
18307       PassThru = DAG.getConstant(0, DL, ContainerVT);
18308     else
18309       PassThru = DAG.getConstantFP(0, DL, ContainerVT);
18310     if (isZerosVector(Load->getPassThru().getNode()))
18311       IsPassThruZeroOrUndef = true;
18312   }
18313 
18314   auto NewLoad = DAG.getMaskedLoad(
18315       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
18316       Mask, PassThru, Load->getMemoryVT(), Load->getMemOperand(),
18317       Load->getAddressingMode(), Load->getExtensionType());
18318 
18319   if (!IsPassThruZeroOrUndef) {
18320     SDValue OldPassThru =
18321         convertToScalableVector(DAG, ContainerVT, Load->getPassThru());
18322     NewLoad = DAG.getSelect(DL, ContainerVT, Mask, NewLoad, OldPassThru);
18323   }
18324 
18325   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
18326   SDValue MergedValues[2] = {Result, Load->getChain()};
18327   return DAG.getMergeValues(MergedValues, DL);
18328 }
18329 
18330 // Convert all fixed length vector stores larger than NEON to masked_stores.
LowerFixedLengthVectorStoreToSVE(SDValue Op,SelectionDAG & DAG) const18331 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
18332     SDValue Op, SelectionDAG &DAG) const {
18333   auto Store = cast<StoreSDNode>(Op);
18334 
18335   SDLoc DL(Op);
18336   EVT VT = Store->getValue().getValueType();
18337   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18338 
18339   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
18340   return DAG.getMaskedStore(
18341       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
18342       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
18343       Store->getMemOperand(), Store->getAddressingMode(),
18344       Store->isTruncatingStore());
18345 }
18346 
LowerFixedLengthVectorMStoreToSVE(SDValue Op,SelectionDAG & DAG) const18347 SDValue AArch64TargetLowering::LowerFixedLengthVectorMStoreToSVE(
18348     SDValue Op, SelectionDAG &DAG) const {
18349   auto Store = cast<MaskedStoreSDNode>(Op);
18350 
18351   if (Store->isTruncatingStore())
18352     return SDValue();
18353 
18354   SDLoc DL(Op);
18355   EVT VT = Store->getValue().getValueType();
18356   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18357 
18358   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
18359   SDValue Mask = convertFixedMaskToScalableVector(Store->getMask(), DAG);
18360 
18361   return DAG.getMaskedStore(
18362       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
18363       Mask, Store->getMemoryVT(), Store->getMemOperand(),
18364       Store->getAddressingMode(), Store->isTruncatingStore());
18365 }
18366 
LowerFixedLengthVectorIntDivideToSVE(SDValue Op,SelectionDAG & DAG) const18367 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
18368     SDValue Op, SelectionDAG &DAG) const {
18369   SDLoc dl(Op);
18370   EVT VT = Op.getValueType();
18371   EVT EltVT = VT.getVectorElementType();
18372 
18373   bool Signed = Op.getOpcode() == ISD::SDIV;
18374   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
18375 
18376   // Scalable vector i32/i64 DIV is supported.
18377   if (EltVT == MVT::i32 || EltVT == MVT::i64)
18378     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
18379 
18380   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
18381   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18382   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
18383   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
18384   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
18385 
18386   // If this is not a full vector, extend, div, and truncate it.
18387   EVT WidenedVT = VT.widenIntegerVectorElementType(*DAG.getContext());
18388   if (DAG.getTargetLoweringInfo().isTypeLegal(WidenedVT)) {
18389     unsigned ExtendOpcode = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18390     SDValue Op0 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(0));
18391     SDValue Op1 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(1));
18392     SDValue Div = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0, Op1);
18393     return DAG.getNode(ISD::TRUNCATE, dl, VT, Div);
18394   }
18395 
18396   // Convert the operands to scalable vectors.
18397   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
18398   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
18399 
18400   // Extend the scalable operands.
18401   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
18402   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
18403   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
18404   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
18405   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
18406   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
18407 
18408   // Convert back to fixed vectors so the DIV can be further lowered.
18409   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
18410   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
18411   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
18412   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
18413   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
18414                                  Op0Lo, Op1Lo);
18415   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
18416                                  Op0Hi, Op1Hi);
18417 
18418   // Convert again to scalable vectors to truncate.
18419   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
18420   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
18421   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
18422                                        ResultLo, ResultHi);
18423 
18424   return convertFromScalableVector(DAG, VT, ScalableResult);
18425 }
18426 
LowerFixedLengthVectorIntExtendToSVE(SDValue Op,SelectionDAG & DAG) const18427 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
18428     SDValue Op, SelectionDAG &DAG) const {
18429   EVT VT = Op.getValueType();
18430   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18431 
18432   SDLoc DL(Op);
18433   SDValue Val = Op.getOperand(0);
18434   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
18435   Val = convertToScalableVector(DAG, ContainerVT, Val);
18436 
18437   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
18438   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
18439 
18440   // Repeatedly unpack Val until the result is of the desired element type.
18441   switch (ContainerVT.getSimpleVT().SimpleTy) {
18442   default:
18443     llvm_unreachable("unimplemented container type");
18444   case MVT::nxv16i8:
18445     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
18446     if (VT.getVectorElementType() == MVT::i16)
18447       break;
18448     LLVM_FALLTHROUGH;
18449   case MVT::nxv8i16:
18450     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
18451     if (VT.getVectorElementType() == MVT::i32)
18452       break;
18453     LLVM_FALLTHROUGH;
18454   case MVT::nxv4i32:
18455     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
18456     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
18457     break;
18458   }
18459 
18460   return convertFromScalableVector(DAG, VT, Val);
18461 }
18462 
LowerFixedLengthVectorTruncateToSVE(SDValue Op,SelectionDAG & DAG) const18463 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
18464     SDValue Op, SelectionDAG &DAG) const {
18465   EVT VT = Op.getValueType();
18466   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18467 
18468   SDLoc DL(Op);
18469   SDValue Val = Op.getOperand(0);
18470   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
18471   Val = convertToScalableVector(DAG, ContainerVT, Val);
18472 
18473   // Repeatedly truncate Val until the result is of the desired element type.
18474   switch (ContainerVT.getSimpleVT().SimpleTy) {
18475   default:
18476     llvm_unreachable("unimplemented container type");
18477   case MVT::nxv2i64:
18478     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
18479     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
18480     if (VT.getVectorElementType() == MVT::i32)
18481       break;
18482     LLVM_FALLTHROUGH;
18483   case MVT::nxv4i32:
18484     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
18485     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
18486     if (VT.getVectorElementType() == MVT::i16)
18487       break;
18488     LLVM_FALLTHROUGH;
18489   case MVT::nxv8i16:
18490     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
18491     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
18492     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
18493     break;
18494   }
18495 
18496   return convertFromScalableVector(DAG, VT, Val);
18497 }
18498 
LowerFixedLengthExtractVectorElt(SDValue Op,SelectionDAG & DAG) const18499 SDValue AArch64TargetLowering::LowerFixedLengthExtractVectorElt(
18500     SDValue Op, SelectionDAG &DAG) const {
18501   EVT VT = Op.getValueType();
18502   EVT InVT = Op.getOperand(0).getValueType();
18503   assert(InVT.isFixedLengthVector() && "Expected fixed length vector type!");
18504 
18505   SDLoc DL(Op);
18506   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18507   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
18508 
18509   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Op.getOperand(1));
18510 }
18511 
LowerFixedLengthInsertVectorElt(SDValue Op,SelectionDAG & DAG) const18512 SDValue AArch64TargetLowering::LowerFixedLengthInsertVectorElt(
18513     SDValue Op, SelectionDAG &DAG) const {
18514   EVT VT = Op.getValueType();
18515   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18516 
18517   SDLoc DL(Op);
18518   EVT InVT = Op.getOperand(0).getValueType();
18519   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18520   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
18521 
18522   auto ScalableRes = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, Op0,
18523                                  Op.getOperand(1), Op.getOperand(2));
18524 
18525   return convertFromScalableVector(DAG, VT, ScalableRes);
18526 }
18527 
18528 // Convert vector operation 'Op' to an equivalent predicated operation whereby
18529 // the original operation's type is used to construct a suitable predicate.
18530 // NOTE: The results for inactive lanes are undefined.
LowerToPredicatedOp(SDValue Op,SelectionDAG & DAG,unsigned NewOp,bool OverrideNEON) const18531 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
18532                                                    SelectionDAG &DAG,
18533                                                    unsigned NewOp,
18534                                                    bool OverrideNEON) const {
18535   EVT VT = Op.getValueType();
18536   SDLoc DL(Op);
18537   auto Pg = getPredicateForVector(DAG, DL, VT);
18538 
18539   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
18540     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18541 
18542     // Create list of operands by converting existing ones to scalable types.
18543     SmallVector<SDValue, 4> Operands = {Pg};
18544     for (const SDValue &V : Op->op_values()) {
18545       if (isa<CondCodeSDNode>(V)) {
18546         Operands.push_back(V);
18547         continue;
18548       }
18549 
18550       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
18551         EVT VTArg = VTNode->getVT().getVectorElementType();
18552         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
18553         Operands.push_back(DAG.getValueType(NewVTArg));
18554         continue;
18555       }
18556 
18557       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
18558              "Only fixed length vectors are supported!");
18559       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
18560     }
18561 
18562     if (isMergePassthruOpcode(NewOp))
18563       Operands.push_back(DAG.getUNDEF(ContainerVT));
18564 
18565     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
18566     return convertFromScalableVector(DAG, VT, ScalableRes);
18567   }
18568 
18569   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
18570 
18571   SmallVector<SDValue, 4> Operands = {Pg};
18572   for (const SDValue &V : Op->op_values()) {
18573     assert((!V.getValueType().isVector() ||
18574             V.getValueType().isScalableVector()) &&
18575            "Only scalable vectors are supported!");
18576     Operands.push_back(V);
18577   }
18578 
18579   if (isMergePassthruOpcode(NewOp))
18580     Operands.push_back(DAG.getUNDEF(VT));
18581 
18582   return DAG.getNode(NewOp, DL, VT, Operands);
18583 }
18584 
18585 // If a fixed length vector operation has no side effects when applied to
18586 // undefined elements, we can safely use scalable vectors to perform the same
18587 // operation without needing to worry about predication.
LowerToScalableOp(SDValue Op,SelectionDAG & DAG) const18588 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
18589                                                  SelectionDAG &DAG) const {
18590   EVT VT = Op.getValueType();
18591   assert(useSVEForFixedLengthVectorVT(VT) &&
18592          "Only expected to lower fixed length vector operation!");
18593   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18594 
18595   // Create list of operands by converting existing ones to scalable types.
18596   SmallVector<SDValue, 4> Ops;
18597   for (const SDValue &V : Op->op_values()) {
18598     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
18599 
18600     // Pass through non-vector operands.
18601     if (!V.getValueType().isVector()) {
18602       Ops.push_back(V);
18603       continue;
18604     }
18605 
18606     // "cast" fixed length vector to a scalable vector.
18607     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
18608            "Only fixed length vectors are supported!");
18609     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
18610   }
18611 
18612   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
18613   return convertFromScalableVector(DAG, VT, ScalableRes);
18614 }
18615 
LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,SelectionDAG & DAG) const18616 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
18617     SelectionDAG &DAG) const {
18618   SDLoc DL(ScalarOp);
18619   SDValue AccOp = ScalarOp.getOperand(0);
18620   SDValue VecOp = ScalarOp.getOperand(1);
18621   EVT SrcVT = VecOp.getValueType();
18622   EVT ResVT = SrcVT.getVectorElementType();
18623 
18624   EVT ContainerVT = SrcVT;
18625   if (SrcVT.isFixedLengthVector()) {
18626     ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
18627     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
18628   }
18629 
18630   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
18631   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18632 
18633   // Convert operands to Scalable.
18634   AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
18635                       DAG.getUNDEF(ContainerVT), AccOp, Zero);
18636 
18637   // Perform reduction.
18638   SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
18639                             Pg, AccOp, VecOp);
18640 
18641   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
18642 }
18643 
LowerPredReductionToSVE(SDValue ReduceOp,SelectionDAG & DAG) const18644 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
18645                                                        SelectionDAG &DAG) const {
18646   SDLoc DL(ReduceOp);
18647   SDValue Op = ReduceOp.getOperand(0);
18648   EVT OpVT = Op.getValueType();
18649   EVT VT = ReduceOp.getValueType();
18650 
18651   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
18652     return SDValue();
18653 
18654   SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
18655 
18656   switch (ReduceOp.getOpcode()) {
18657   default:
18658     return SDValue();
18659   case ISD::VECREDUCE_OR:
18660     return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
18661   case ISD::VECREDUCE_AND: {
18662     Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
18663     return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
18664   }
18665   case ISD::VECREDUCE_XOR: {
18666     SDValue ID =
18667         DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
18668     SDValue Cntp =
18669         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
18670     return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
18671   }
18672   }
18673 
18674   return SDValue();
18675 }
18676 
LowerReductionToSVE(unsigned Opcode,SDValue ScalarOp,SelectionDAG & DAG) const18677 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
18678                                                    SDValue ScalarOp,
18679                                                    SelectionDAG &DAG) const {
18680   SDLoc DL(ScalarOp);
18681   SDValue VecOp = ScalarOp.getOperand(0);
18682   EVT SrcVT = VecOp.getValueType();
18683 
18684   if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
18685     EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
18686     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
18687   }
18688 
18689   // UADDV always returns an i64 result.
18690   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
18691                                                    SrcVT.getVectorElementType();
18692   EVT RdxVT = SrcVT;
18693   if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
18694     RdxVT = getPackedSVEVectorVT(ResVT);
18695 
18696   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
18697   SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
18698   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
18699                             Rdx, DAG.getConstant(0, DL, MVT::i64));
18700 
18701   // The VEC_REDUCE nodes expect an element size result.
18702   if (ResVT != ScalarOp.getValueType())
18703     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
18704 
18705   return Res;
18706 }
18707 
18708 SDValue
LowerFixedLengthVectorSelectToSVE(SDValue Op,SelectionDAG & DAG) const18709 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
18710     SelectionDAG &DAG) const {
18711   EVT VT = Op.getValueType();
18712   SDLoc DL(Op);
18713 
18714   EVT InVT = Op.getOperand(1).getValueType();
18715   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18716   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
18717   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
18718 
18719   // Convert the mask to a predicated (NOTE: We don't need to worry about
18720   // inactive lanes since VSELECT is safe when given undefined elements).
18721   EVT MaskVT = Op.getOperand(0).getValueType();
18722   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
18723   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
18724   Mask = DAG.getNode(ISD::TRUNCATE, DL,
18725                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
18726 
18727   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
18728                                 Mask, Op1, Op2);
18729 
18730   return convertFromScalableVector(DAG, VT, ScalableRes);
18731 }
18732 
LowerFixedLengthVectorSetccToSVE(SDValue Op,SelectionDAG & DAG) const18733 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
18734     SDValue Op, SelectionDAG &DAG) const {
18735   SDLoc DL(Op);
18736   EVT InVT = Op.getOperand(0).getValueType();
18737   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18738 
18739   assert(useSVEForFixedLengthVectorVT(InVT) &&
18740          "Only expected to lower fixed length vector operation!");
18741   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
18742          "Expected integer result of the same bit length as the inputs!");
18743 
18744   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
18745   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
18746   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
18747 
18748   EVT CmpVT = Pg.getValueType();
18749   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
18750                          {Pg, Op1, Op2, Op.getOperand(2)});
18751 
18752   EVT PromoteVT = ContainerVT.changeTypeToInteger();
18753   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
18754   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
18755 }
18756 
18757 SDValue
LowerFixedLengthBitcastToSVE(SDValue Op,SelectionDAG & DAG) const18758 AArch64TargetLowering::LowerFixedLengthBitcastToSVE(SDValue Op,
18759                                                     SelectionDAG &DAG) const {
18760   SDLoc DL(Op);
18761   auto SrcOp = Op.getOperand(0);
18762   EVT VT = Op.getValueType();
18763   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
18764   EVT ContainerSrcVT =
18765       getContainerForFixedLengthVector(DAG, SrcOp.getValueType());
18766 
18767   SrcOp = convertToScalableVector(DAG, ContainerSrcVT, SrcOp);
18768   Op = DAG.getNode(ISD::BITCAST, DL, ContainerDstVT, SrcOp);
18769   return convertFromScalableVector(DAG, VT, Op);
18770 }
18771 
LowerFixedLengthConcatVectorsToSVE(SDValue Op,SelectionDAG & DAG) const18772 SDValue AArch64TargetLowering::LowerFixedLengthConcatVectorsToSVE(
18773     SDValue Op, SelectionDAG &DAG) const {
18774   SDLoc DL(Op);
18775   unsigned NumOperands = Op->getNumOperands();
18776 
18777   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
18778          "Unexpected number of operands in CONCAT_VECTORS");
18779 
18780   auto SrcOp1 = Op.getOperand(0);
18781   auto SrcOp2 = Op.getOperand(1);
18782   EVT VT = Op.getValueType();
18783   EVT SrcVT = SrcOp1.getValueType();
18784 
18785   if (NumOperands > 2) {
18786     SmallVector<SDValue, 4> Ops;
18787     EVT PairVT = SrcVT.getDoubleNumVectorElementsVT(*DAG.getContext());
18788     for (unsigned I = 0; I < NumOperands; I += 2)
18789       Ops.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, PairVT,
18790                                 Op->getOperand(I), Op->getOperand(I + 1)));
18791 
18792     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Ops);
18793   }
18794 
18795   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18796 
18797   SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
18798   SrcOp1 = convertToScalableVector(DAG, ContainerVT, SrcOp1);
18799   SrcOp2 = convertToScalableVector(DAG, ContainerVT, SrcOp2);
18800 
18801   Op = DAG.getNode(AArch64ISD::SPLICE, DL, ContainerVT, Pg, SrcOp1, SrcOp2);
18802 
18803   return convertFromScalableVector(DAG, VT, Op);
18804 }
18805 
18806 SDValue
LowerFixedLengthFPExtendToSVE(SDValue Op,SelectionDAG & DAG) const18807 AArch64TargetLowering::LowerFixedLengthFPExtendToSVE(SDValue Op,
18808                                                      SelectionDAG &DAG) const {
18809   EVT VT = Op.getValueType();
18810   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18811 
18812   SDLoc DL(Op);
18813   SDValue Val = Op.getOperand(0);
18814   SDValue Pg = getPredicateForVector(DAG, DL, VT);
18815   EVT SrcVT = Val.getValueType();
18816   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18817   EVT ExtendVT = ContainerVT.changeVectorElementType(
18818       SrcVT.getVectorElementType());
18819 
18820   Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
18821   Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT.changeTypeToInteger(), Val);
18822 
18823   Val = convertToScalableVector(DAG, ContainerVT.changeTypeToInteger(), Val);
18824   Val = getSVESafeBitCast(ExtendVT, Val, DAG);
18825   Val = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
18826                     Pg, Val, DAG.getUNDEF(ContainerVT));
18827 
18828   return convertFromScalableVector(DAG, VT, Val);
18829 }
18830 
18831 SDValue
LowerFixedLengthFPRoundToSVE(SDValue Op,SelectionDAG & DAG) const18832 AArch64TargetLowering::LowerFixedLengthFPRoundToSVE(SDValue Op,
18833                                                     SelectionDAG &DAG) const {
18834   EVT VT = Op.getValueType();
18835   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18836 
18837   SDLoc DL(Op);
18838   SDValue Val = Op.getOperand(0);
18839   EVT SrcVT = Val.getValueType();
18840   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
18841   EVT RoundVT = ContainerSrcVT.changeVectorElementType(
18842       VT.getVectorElementType());
18843   SDValue Pg = getPredicateForVector(DAG, DL, RoundVT);
18844 
18845   Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
18846   Val = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, RoundVT, Pg, Val,
18847                     Op.getOperand(1), DAG.getUNDEF(RoundVT));
18848   Val = getSVESafeBitCast(ContainerSrcVT.changeTypeToInteger(), Val, DAG);
18849   Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
18850 
18851   Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
18852   return DAG.getNode(ISD::BITCAST, DL, VT, Val);
18853 }
18854 
18855 SDValue
LowerFixedLengthIntToFPToSVE(SDValue Op,SelectionDAG & DAG) const18856 AArch64TargetLowering::LowerFixedLengthIntToFPToSVE(SDValue Op,
18857                                                     SelectionDAG &DAG) const {
18858   EVT VT = Op.getValueType();
18859   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18860 
18861   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
18862   unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
18863                              : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
18864 
18865   SDLoc DL(Op);
18866   SDValue Val = Op.getOperand(0);
18867   EVT SrcVT = Val.getValueType();
18868   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
18869   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
18870 
18871   if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
18872       ContainerDstVT.getVectorElementType().getSizeInBits()) {
18873     SDValue Pg = getPredicateForVector(DAG, DL, VT);
18874 
18875     Val = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
18876                       VT.changeTypeToInteger(), Val);
18877 
18878     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
18879     Val = getSVESafeBitCast(ContainerDstVT.changeTypeToInteger(), Val, DAG);
18880     // Safe to use a larger than specified operand since we just unpacked the
18881     // data, hence the upper bits are zero.
18882     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
18883                       DAG.getUNDEF(ContainerDstVT));
18884     return convertFromScalableVector(DAG, VT, Val);
18885   } else {
18886     EVT CvtVT = ContainerSrcVT.changeVectorElementType(
18887         ContainerDstVT.getVectorElementType());
18888     SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
18889 
18890     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
18891     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
18892     Val = getSVESafeBitCast(ContainerSrcVT, Val, DAG);
18893     Val = convertFromScalableVector(DAG, SrcVT, Val);
18894 
18895     Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
18896     return DAG.getNode(ISD::BITCAST, DL, VT, Val);
18897   }
18898 }
18899 
18900 SDValue
LowerFixedLengthFPToIntToSVE(SDValue Op,SelectionDAG & DAG) const18901 AArch64TargetLowering::LowerFixedLengthFPToIntToSVE(SDValue Op,
18902                                                     SelectionDAG &DAG) const {
18903   EVT VT = Op.getValueType();
18904   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18905 
18906   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
18907   unsigned Opcode = IsSigned ? AArch64ISD::FCVTZS_MERGE_PASSTHRU
18908                              : AArch64ISD::FCVTZU_MERGE_PASSTHRU;
18909 
18910   SDLoc DL(Op);
18911   SDValue Val = Op.getOperand(0);
18912   EVT SrcVT = Val.getValueType();
18913   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
18914   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
18915 
18916   if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
18917       ContainerDstVT.getVectorElementType().getSizeInBits()) {
18918     EVT CvtVT = ContainerDstVT.changeVectorElementType(
18919       ContainerSrcVT.getVectorElementType());
18920     SDValue Pg = getPredicateForVector(DAG, DL, VT);
18921 
18922     Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
18923     Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Val);
18924 
18925     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
18926     Val = getSVESafeBitCast(CvtVT, Val, DAG);
18927     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
18928                       DAG.getUNDEF(ContainerDstVT));
18929     return convertFromScalableVector(DAG, VT, Val);
18930   } else {
18931     EVT CvtVT = ContainerSrcVT.changeTypeToInteger();
18932     SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
18933 
18934     // Safe to use a larger than specified result since an fp_to_int where the
18935     // result doesn't fit into the destination is undefined.
18936     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
18937     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
18938     Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
18939 
18940     return DAG.getNode(ISD::TRUNCATE, DL, VT, Val);
18941   }
18942 }
18943 
LowerFixedLengthVECTOR_SHUFFLEToSVE(SDValue Op,SelectionDAG & DAG) const18944 SDValue AArch64TargetLowering::LowerFixedLengthVECTOR_SHUFFLEToSVE(
18945     SDValue Op, SelectionDAG &DAG) const {
18946   EVT VT = Op.getValueType();
18947   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18948 
18949   auto *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
18950   auto ShuffleMask = SVN->getMask();
18951 
18952   SDLoc DL(Op);
18953   SDValue Op1 = Op.getOperand(0);
18954   SDValue Op2 = Op.getOperand(1);
18955 
18956   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18957   Op1 = convertToScalableVector(DAG, ContainerVT, Op1);
18958   Op2 = convertToScalableVector(DAG, ContainerVT, Op2);
18959 
18960   bool ReverseEXT = false;
18961   unsigned Imm;
18962   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm) &&
18963       Imm == VT.getVectorNumElements() - 1) {
18964     if (ReverseEXT)
18965       std::swap(Op1, Op2);
18966 
18967     EVT ScalarTy = VT.getVectorElementType();
18968     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
18969       ScalarTy = MVT::i32;
18970     SDValue Scalar = DAG.getNode(
18971         ISD::EXTRACT_VECTOR_ELT, DL, ScalarTy, Op1,
18972         DAG.getConstant(VT.getVectorNumElements() - 1, DL, MVT::i64));
18973     Op = DAG.getNode(AArch64ISD::INSR, DL, ContainerVT, Op2, Scalar);
18974     return convertFromScalableVector(DAG, VT, Op);
18975   }
18976 
18977   return SDValue();
18978 }
18979 
getSVESafeBitCast(EVT VT,SDValue Op,SelectionDAG & DAG) const18980 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
18981                                                  SelectionDAG &DAG) const {
18982   SDLoc DL(Op);
18983   EVT InVT = Op.getValueType();
18984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18985   (void)TLI;
18986 
18987   assert(VT.isScalableVector() && TLI.isTypeLegal(VT) &&
18988          InVT.isScalableVector() && TLI.isTypeLegal(InVT) &&
18989          "Only expect to cast between legal scalable vector types!");
18990   assert((VT.getVectorElementType() == MVT::i1) ==
18991              (InVT.getVectorElementType() == MVT::i1) &&
18992          "Cannot cast between data and predicate scalable vector types!");
18993 
18994   if (InVT == VT)
18995     return Op;
18996 
18997   if (VT.getVectorElementType() == MVT::i1)
18998     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
18999 
19000   EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
19001   EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
19002 
19003   // Pack input if required.
19004   if (InVT != PackedInVT)
19005     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
19006 
19007   Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
19008 
19009   // Unpack result if required.
19010   if (VT != PackedVT)
19011     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
19012 
19013   return Op;
19014 }
19015 
isAllActivePredicate(SDValue N) const19016 bool AArch64TargetLowering::isAllActivePredicate(SDValue N) const {
19017   return ::isAllActivePredicate(N);
19018 }
19019 
getPromotedVTForPredicate(EVT VT) const19020 EVT AArch64TargetLowering::getPromotedVTForPredicate(EVT VT) const {
19021   return ::getPromotedVTForPredicate(VT);
19022 }
19023 
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const19024 bool AArch64TargetLowering::SimplifyDemandedBitsForTargetNode(
19025     SDValue Op, const APInt &OriginalDemandedBits,
19026     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
19027     unsigned Depth) const {
19028 
19029   unsigned Opc = Op.getOpcode();
19030   switch (Opc) {
19031   case AArch64ISD::VSHL: {
19032     // Match (VSHL (VLSHR Val X) X)
19033     SDValue ShiftL = Op;
19034     SDValue ShiftR = Op->getOperand(0);
19035     if (ShiftR->getOpcode() != AArch64ISD::VLSHR)
19036       return false;
19037 
19038     if (!ShiftL.hasOneUse() || !ShiftR.hasOneUse())
19039       return false;
19040 
19041     unsigned ShiftLBits = ShiftL->getConstantOperandVal(1);
19042     unsigned ShiftRBits = ShiftR->getConstantOperandVal(1);
19043 
19044     // Other cases can be handled as well, but this is not
19045     // implemented.
19046     if (ShiftRBits != ShiftLBits)
19047       return false;
19048 
19049     unsigned ScalarSize = Op.getScalarValueSizeInBits();
19050     assert(ScalarSize > ShiftLBits && "Invalid shift imm");
19051 
19052     APInt ZeroBits = APInt::getLowBitsSet(ScalarSize, ShiftLBits);
19053     APInt UnusedBits = ~OriginalDemandedBits;
19054 
19055     if ((ZeroBits & UnusedBits) != ZeroBits)
19056       return false;
19057 
19058     // All bits that are zeroed by (VSHL (VLSHR Val X) X) are not
19059     // used - simplify to just Val.
19060     return TLO.CombineTo(Op, ShiftR->getOperand(0));
19061   }
19062   }
19063 
19064   return TargetLowering::SimplifyDemandedBitsForTargetNode(
19065       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
19066 }
19067 
isConstantUnsignedBitfieldExtactLegal(unsigned Opc,LLT Ty1,LLT Ty2) const19068 bool AArch64TargetLowering::isConstantUnsignedBitfieldExtactLegal(
19069     unsigned Opc, LLT Ty1, LLT Ty2) const {
19070   return Ty1 == Ty2 && (Ty1 == LLT::scalar(32) || Ty1 == LLT::scalar(64));
19071 }
19072