xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp (revision 0b37c1590418417c894529d371800dfac71ef887)
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64ISelLowering.h"
14 #include "AArch64CallingConvention.h"
15 #include "AArch64ExpandImm.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/TargetCallingConv.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/IntrinsicsAArch64.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/OperandTraits.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/MC/MCRegisterInfo.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CodeGen.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Target/TargetMachine.h"
80 #include "llvm/Target/TargetOptions.h"
81 #include <algorithm>
82 #include <bitset>
83 #include <cassert>
84 #include <cctype>
85 #include <cstdint>
86 #include <cstdlib>
87 #include <iterator>
88 #include <limits>
89 #include <tuple>
90 #include <utility>
91 #include <vector>
92 
93 using namespace llvm;
94 using namespace llvm::PatternMatch;
95 
96 #define DEBUG_TYPE "aarch64-lower"
97 
98 STATISTIC(NumTailCalls, "Number of tail calls");
99 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101 
102 static cl::opt<bool>
103 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
104                            cl::desc("Allow AArch64 SLI/SRI formation"),
105                            cl::init(false));
106 
107 // FIXME: The necessary dtprel relocations don't seem to be supported
108 // well in the GNU bfd and gold linkers at the moment. Therefore, by
109 // default, for now, fall back to GeneralDynamic code generation.
110 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
111     "aarch64-elf-ldtls-generation", cl::Hidden,
112     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
113     cl::init(false));
114 
115 static cl::opt<bool>
116 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
117                          cl::desc("Enable AArch64 logical imm instruction "
118                                   "optimization"),
119                          cl::init(true));
120 
121 /// Value type used for condition codes.
122 static const MVT MVT_CC = MVT::i32;
123 
124 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
125                                              const AArch64Subtarget &STI)
126     : TargetLowering(TM), Subtarget(&STI) {
127   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
128   // we have to make something up. Arbitrarily, choose ZeroOrOne.
129   setBooleanContents(ZeroOrOneBooleanContent);
130   // When comparing vectors the result sets the different elements in the
131   // vector to all-one or all-zero.
132   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
133 
134   // Set up the register classes.
135   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
136   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
137 
138   if (Subtarget->hasFPARMv8()) {
139     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
140     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
141     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
142     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
143   }
144 
145   if (Subtarget->hasNEON()) {
146     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
147     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
148     // Someone set us up the NEON.
149     addDRTypeForNEON(MVT::v2f32);
150     addDRTypeForNEON(MVT::v8i8);
151     addDRTypeForNEON(MVT::v4i16);
152     addDRTypeForNEON(MVT::v2i32);
153     addDRTypeForNEON(MVT::v1i64);
154     addDRTypeForNEON(MVT::v1f64);
155     addDRTypeForNEON(MVT::v4f16);
156 
157     addQRTypeForNEON(MVT::v4f32);
158     addQRTypeForNEON(MVT::v2f64);
159     addQRTypeForNEON(MVT::v16i8);
160     addQRTypeForNEON(MVT::v8i16);
161     addQRTypeForNEON(MVT::v4i32);
162     addQRTypeForNEON(MVT::v2i64);
163     addQRTypeForNEON(MVT::v8f16);
164   }
165 
166   if (Subtarget->hasSVE()) {
167     // Add legal sve predicate types
168     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
169     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
170     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
171     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
172 
173     // Add legal sve data types
174     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
175     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
176     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
177     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
178 
179     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
180     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
181     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
182     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
185 
186     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
187       setOperationAction(ISD::SADDSAT, VT, Legal);
188       setOperationAction(ISD::UADDSAT, VT, Legal);
189       setOperationAction(ISD::SSUBSAT, VT, Legal);
190       setOperationAction(ISD::USUBSAT, VT, Legal);
191       setOperationAction(ISD::SMAX, VT, Legal);
192       setOperationAction(ISD::UMAX, VT, Legal);
193       setOperationAction(ISD::SMIN, VT, Legal);
194       setOperationAction(ISD::UMIN, VT, Legal);
195     }
196 
197     for (auto VT :
198          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
199            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
200       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
201   }
202 
203   // Compute derived properties from the register classes
204   computeRegisterProperties(Subtarget->getRegisterInfo());
205 
206   // Provide all sorts of operation actions
207   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
209   setOperationAction(ISD::SETCC, MVT::i32, Custom);
210   setOperationAction(ISD::SETCC, MVT::i64, Custom);
211   setOperationAction(ISD::SETCC, MVT::f16, Custom);
212   setOperationAction(ISD::SETCC, MVT::f32, Custom);
213   setOperationAction(ISD::SETCC, MVT::f64, Custom);
214   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
215   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
216   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
217   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
218   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
219   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
220   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
221   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
222   setOperationAction(ISD::SELECT, MVT::i32, Custom);
223   setOperationAction(ISD::SELECT, MVT::i64, Custom);
224   setOperationAction(ISD::SELECT, MVT::f16, Custom);
225   setOperationAction(ISD::SELECT, MVT::f32, Custom);
226   setOperationAction(ISD::SELECT, MVT::f64, Custom);
227   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
228   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
229   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
230   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
231   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
232   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
233   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
234 
235   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
236   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
237   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
238 
239   setOperationAction(ISD::FREM, MVT::f32, Expand);
240   setOperationAction(ISD::FREM, MVT::f64, Expand);
241   setOperationAction(ISD::FREM, MVT::f80, Expand);
242 
243   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
244 
245   // Custom lowering hooks are needed for XOR
246   // to fold it into CSINC/CSINV.
247   setOperationAction(ISD::XOR, MVT::i32, Custom);
248   setOperationAction(ISD::XOR, MVT::i64, Custom);
249 
250   // Virtually no operation on f128 is legal, but LLVM can't expand them when
251   // there's a valid register class, so we need custom operations in most cases.
252   setOperationAction(ISD::FABS, MVT::f128, Expand);
253   setOperationAction(ISD::FADD, MVT::f128, Custom);
254   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
255   setOperationAction(ISD::FCOS, MVT::f128, Expand);
256   setOperationAction(ISD::FDIV, MVT::f128, Custom);
257   setOperationAction(ISD::FMA, MVT::f128, Expand);
258   setOperationAction(ISD::FMUL, MVT::f128, Custom);
259   setOperationAction(ISD::FNEG, MVT::f128, Expand);
260   setOperationAction(ISD::FPOW, MVT::f128, Expand);
261   setOperationAction(ISD::FREM, MVT::f128, Expand);
262   setOperationAction(ISD::FRINT, MVT::f128, Expand);
263   setOperationAction(ISD::FSIN, MVT::f128, Expand);
264   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
265   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
266   setOperationAction(ISD::FSUB, MVT::f128, Custom);
267   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
268   setOperationAction(ISD::SETCC, MVT::f128, Custom);
269   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
270   setOperationAction(ISD::SELECT, MVT::f128, Custom);
271   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
272   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
273 
274   // Lowering for many of the conversions is actually specified by the non-f128
275   // type. The LowerXXX function will be trivial when f128 isn't involved.
276   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
277   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
278   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
279   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
280   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
281   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
282   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
283   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
284   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
285   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
286   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
287   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
288   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
289   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
290 
291   // Variable arguments.
292   setOperationAction(ISD::VASTART, MVT::Other, Custom);
293   setOperationAction(ISD::VAARG, MVT::Other, Custom);
294   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
295   setOperationAction(ISD::VAEND, MVT::Other, Expand);
296 
297   // Variable-sized objects.
298   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
299   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
300 
301   if (Subtarget->isTargetWindows())
302     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
303   else
304     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
305 
306   // Constant pool entries
307   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
308 
309   // BlockAddress
310   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
311 
312   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
313   setOperationAction(ISD::ADDC, MVT::i32, Custom);
314   setOperationAction(ISD::ADDE, MVT::i32, Custom);
315   setOperationAction(ISD::SUBC, MVT::i32, Custom);
316   setOperationAction(ISD::SUBE, MVT::i32, Custom);
317   setOperationAction(ISD::ADDC, MVT::i64, Custom);
318   setOperationAction(ISD::ADDE, MVT::i64, Custom);
319   setOperationAction(ISD::SUBC, MVT::i64, Custom);
320   setOperationAction(ISD::SUBE, MVT::i64, Custom);
321 
322   // AArch64 lacks both left-rotate and popcount instructions.
323   setOperationAction(ISD::ROTL, MVT::i32, Expand);
324   setOperationAction(ISD::ROTL, MVT::i64, Expand);
325   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
326     setOperationAction(ISD::ROTL, VT, Expand);
327     setOperationAction(ISD::ROTR, VT, Expand);
328   }
329 
330   // AArch64 doesn't have {U|S}MUL_LOHI.
331   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
332   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
333 
334   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
335   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
336 
337   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
338   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
339   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
340     setOperationAction(ISD::SDIVREM, VT, Expand);
341     setOperationAction(ISD::UDIVREM, VT, Expand);
342   }
343   setOperationAction(ISD::SREM, MVT::i32, Expand);
344   setOperationAction(ISD::SREM, MVT::i64, Expand);
345   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
346   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
347   setOperationAction(ISD::UREM, MVT::i32, Expand);
348   setOperationAction(ISD::UREM, MVT::i64, Expand);
349 
350   // Custom lower Add/Sub/Mul with overflow.
351   setOperationAction(ISD::SADDO, MVT::i32, Custom);
352   setOperationAction(ISD::SADDO, MVT::i64, Custom);
353   setOperationAction(ISD::UADDO, MVT::i32, Custom);
354   setOperationAction(ISD::UADDO, MVT::i64, Custom);
355   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
356   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
357   setOperationAction(ISD::USUBO, MVT::i32, Custom);
358   setOperationAction(ISD::USUBO, MVT::i64, Custom);
359   setOperationAction(ISD::SMULO, MVT::i32, Custom);
360   setOperationAction(ISD::SMULO, MVT::i64, Custom);
361   setOperationAction(ISD::UMULO, MVT::i32, Custom);
362   setOperationAction(ISD::UMULO, MVT::i64, Custom);
363 
364   setOperationAction(ISD::FSIN, MVT::f32, Expand);
365   setOperationAction(ISD::FSIN, MVT::f64, Expand);
366   setOperationAction(ISD::FCOS, MVT::f32, Expand);
367   setOperationAction(ISD::FCOS, MVT::f64, Expand);
368   setOperationAction(ISD::FPOW, MVT::f32, Expand);
369   setOperationAction(ISD::FPOW, MVT::f64, Expand);
370   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
371   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
372   if (Subtarget->hasFullFP16())
373     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
374   else
375     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
376 
377   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
378   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
379   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
380   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
381   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
382   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
383   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
384   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
385   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
386   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
387   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
388   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
389   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
390   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
391   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
392   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
393   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
394   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
395   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
396   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
397   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
398   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
399   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
400   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
401   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
402   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
403   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
404   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
405   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
406   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
407   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
408   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
409   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
410 
411   if (!Subtarget->hasFullFP16()) {
412     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
413     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
414     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
415     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
416     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
417     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
418     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
419     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
420     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
421     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
422     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
423     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
424     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
425     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
426     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
427     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
428     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
429     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
430     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
431     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
432     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
433     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
434 
435     // promote v4f16 to v4f32 when that is known to be safe.
436     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
437     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
438     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
439     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
440     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
441     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
442     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
443     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
444 
445     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
446     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
447     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
448     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
449     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
450     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
451     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
452     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
453     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
454     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
455     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
456     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
457     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
458     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
459     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
460 
461     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
462     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
463     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
464     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
465     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
466     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
467     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
468     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
469     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
470     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
471     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
472     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
473     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
474     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
475     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
476     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
477     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
478     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
479     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
480     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
481   }
482 
483   // AArch64 has implementations of a lot of rounding-like FP operations.
484   for (MVT Ty : {MVT::f32, MVT::f64}) {
485     setOperationAction(ISD::FFLOOR, Ty, Legal);
486     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
487     setOperationAction(ISD::FCEIL, Ty, Legal);
488     setOperationAction(ISD::FRINT, Ty, Legal);
489     setOperationAction(ISD::FTRUNC, Ty, Legal);
490     setOperationAction(ISD::FROUND, Ty, Legal);
491     setOperationAction(ISD::FMINNUM, Ty, Legal);
492     setOperationAction(ISD::FMAXNUM, Ty, Legal);
493     setOperationAction(ISD::FMINIMUM, Ty, Legal);
494     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
495     setOperationAction(ISD::LROUND, Ty, Legal);
496     setOperationAction(ISD::LLROUND, Ty, Legal);
497     setOperationAction(ISD::LRINT, Ty, Legal);
498     setOperationAction(ISD::LLRINT, Ty, Legal);
499   }
500 
501   if (Subtarget->hasFullFP16()) {
502     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
503     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
504     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
505     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
506     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
507     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
508     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
509     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
510     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
511     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
512   }
513 
514   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
515 
516   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
517 
518   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
519   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
520   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
521   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
522   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
523 
524   // 128-bit loads and stores can be done without expanding
525   setOperationAction(ISD::LOAD, MVT::i128, Custom);
526   setOperationAction(ISD::STORE, MVT::i128, Custom);
527 
528   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
529   // This requires the Performance Monitors extension.
530   if (Subtarget->hasPerfMon())
531     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
532 
533   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
534       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
535     // Issue __sincos_stret if available.
536     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
537     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
538   } else {
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
541   }
542 
543   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
544     // MSVCRT doesn't have powi; fall back to pow
545     setLibcallName(RTLIB::POWI_F32, nullptr);
546     setLibcallName(RTLIB::POWI_F64, nullptr);
547   }
548 
549   // Make floating-point constants legal for the large code model, so they don't
550   // become loads from the constant pool.
551   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
552     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
553     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
554   }
555 
556   // AArch64 does not have floating-point extending loads, i1 sign-extending
557   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
558   for (MVT VT : MVT::fp_valuetypes()) {
559     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
560     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
561     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
562     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
563   }
564   for (MVT VT : MVT::integer_valuetypes())
565     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
566 
567   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
568   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
569   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
570   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
571   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
572   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
573   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
574 
575   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
576   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
577 
578   // Indexed loads and stores are supported.
579   for (unsigned im = (unsigned)ISD::PRE_INC;
580        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
581     setIndexedLoadAction(im, MVT::i8, Legal);
582     setIndexedLoadAction(im, MVT::i16, Legal);
583     setIndexedLoadAction(im, MVT::i32, Legal);
584     setIndexedLoadAction(im, MVT::i64, Legal);
585     setIndexedLoadAction(im, MVT::f64, Legal);
586     setIndexedLoadAction(im, MVT::f32, Legal);
587     setIndexedLoadAction(im, MVT::f16, Legal);
588     setIndexedStoreAction(im, MVT::i8, Legal);
589     setIndexedStoreAction(im, MVT::i16, Legal);
590     setIndexedStoreAction(im, MVT::i32, Legal);
591     setIndexedStoreAction(im, MVT::i64, Legal);
592     setIndexedStoreAction(im, MVT::f64, Legal);
593     setIndexedStoreAction(im, MVT::f32, Legal);
594     setIndexedStoreAction(im, MVT::f16, Legal);
595   }
596 
597   // Trap.
598   setOperationAction(ISD::TRAP, MVT::Other, Legal);
599   if (Subtarget->isTargetWindows())
600     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
601 
602   // We combine OR nodes for bitfield operations.
603   setTargetDAGCombine(ISD::OR);
604   // Try to create BICs for vector ANDs.
605   setTargetDAGCombine(ISD::AND);
606 
607   // Vector add and sub nodes may conceal a high-half opportunity.
608   // Also, try to fold ADD into CSINC/CSINV..
609   setTargetDAGCombine(ISD::ADD);
610   setTargetDAGCombine(ISD::SUB);
611   setTargetDAGCombine(ISD::SRL);
612   setTargetDAGCombine(ISD::XOR);
613   setTargetDAGCombine(ISD::SINT_TO_FP);
614   setTargetDAGCombine(ISD::UINT_TO_FP);
615 
616   setTargetDAGCombine(ISD::FP_TO_SINT);
617   setTargetDAGCombine(ISD::FP_TO_UINT);
618   setTargetDAGCombine(ISD::FDIV);
619 
620   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
621 
622   setTargetDAGCombine(ISD::ANY_EXTEND);
623   setTargetDAGCombine(ISD::ZERO_EXTEND);
624   setTargetDAGCombine(ISD::SIGN_EXTEND);
625   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
626   setTargetDAGCombine(ISD::CONCAT_VECTORS);
627   setTargetDAGCombine(ISD::STORE);
628   if (Subtarget->supportsAddressTopByteIgnored())
629     setTargetDAGCombine(ISD::LOAD);
630 
631   setTargetDAGCombine(ISD::MUL);
632 
633   setTargetDAGCombine(ISD::SELECT);
634   setTargetDAGCombine(ISD::VSELECT);
635 
636   setTargetDAGCombine(ISD::INTRINSIC_VOID);
637   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
638   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
639 
640   setTargetDAGCombine(ISD::GlobalAddress);
641 
642   // In case of strict alignment, avoid an excessive number of byte wide stores.
643   MaxStoresPerMemsetOptSize = 8;
644   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
645                        ? MaxStoresPerMemsetOptSize : 32;
646 
647   MaxGluedStoresPerMemcpy = 4;
648   MaxStoresPerMemcpyOptSize = 4;
649   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
650                        ? MaxStoresPerMemcpyOptSize : 16;
651 
652   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
653 
654   MaxLoadsPerMemcmpOptSize = 4;
655   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
656                       ? MaxLoadsPerMemcmpOptSize : 8;
657 
658   setStackPointerRegisterToSaveRestore(AArch64::SP);
659 
660   setSchedulingPreference(Sched::Hybrid);
661 
662   EnableExtLdPromotion = true;
663 
664   // Set required alignment.
665   setMinFunctionAlignment(Align(4));
666   // Set preferred alignments.
667   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
668   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
669 
670   // Only change the limit for entries in a jump table if specified by
671   // the sub target, but not at the command line.
672   unsigned MaxJT = STI.getMaximumJumpTableSize();
673   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
674     setMaximumJumpTableSize(MaxJT);
675 
676   setHasExtractBitsInsn(true);
677 
678   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
679 
680   if (Subtarget->hasNEON()) {
681     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
682     // silliness like this:
683     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
684     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
685     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
687     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
688     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
689     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
690     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
691     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
692     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
693     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
694     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
695     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
696     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
697     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
698     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
700     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
701     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
702     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
703     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
704     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
705     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
706     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
707     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
708 
709     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
710     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
711     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
712     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
713     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
714 
715     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
716 
717     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
718     // elements smaller than i32, so promote the input to i32 first.
719     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
720     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
721     // i8 vector elements also need promotion to i32 for v8i8
722     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
723     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
724     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
725     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
726     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
727     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
728     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
729     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
730     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
731     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
732     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
733 
734     if (Subtarget->hasFullFP16()) {
735       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
736       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
737       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
738       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
739     } else {
740       // when AArch64 doesn't have fullfp16 support, promote the input
741       // to i32 first.
742       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
743       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
744       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
745       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
746     }
747 
748     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
749     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
750 
751     // AArch64 doesn't have MUL.2d:
752     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
753     // Custom handling for some quad-vector types to detect MULL.
754     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
755     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
756     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
757 
758     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
759                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
760       // Vector reductions
761       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
762       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
763       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
764       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
765       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
766 
767       // Saturates
768       setOperationAction(ISD::SADDSAT, VT, Legal);
769       setOperationAction(ISD::UADDSAT, VT, Legal);
770       setOperationAction(ISD::SSUBSAT, VT, Legal);
771       setOperationAction(ISD::USUBSAT, VT, Legal);
772     }
773     for (MVT VT : { MVT::v4f16, MVT::v2f32,
774                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
775       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
776       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
777     }
778 
779     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
780     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
781     // Likewise, narrowing and extending vector loads/stores aren't handled
782     // directly.
783     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
784       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
785 
786       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
787         setOperationAction(ISD::MULHS, VT, Legal);
788         setOperationAction(ISD::MULHU, VT, Legal);
789       } else {
790         setOperationAction(ISD::MULHS, VT, Expand);
791         setOperationAction(ISD::MULHU, VT, Expand);
792       }
793       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
794       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
795 
796       setOperationAction(ISD::BSWAP, VT, Expand);
797       setOperationAction(ISD::CTTZ, VT, Expand);
798 
799       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
800         setTruncStoreAction(VT, InnerVT, Expand);
801         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
802         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
803         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
804       }
805     }
806 
807     // AArch64 has implementations of a lot of rounding-like FP operations.
808     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
809       setOperationAction(ISD::FFLOOR, Ty, Legal);
810       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
811       setOperationAction(ISD::FCEIL, Ty, Legal);
812       setOperationAction(ISD::FRINT, Ty, Legal);
813       setOperationAction(ISD::FTRUNC, Ty, Legal);
814       setOperationAction(ISD::FROUND, Ty, Legal);
815     }
816 
817     if (Subtarget->hasFullFP16()) {
818       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
819         setOperationAction(ISD::FFLOOR, Ty, Legal);
820         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
821         setOperationAction(ISD::FCEIL, Ty, Legal);
822         setOperationAction(ISD::FRINT, Ty, Legal);
823         setOperationAction(ISD::FTRUNC, Ty, Legal);
824         setOperationAction(ISD::FROUND, Ty, Legal);
825       }
826     }
827 
828     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
829   }
830 
831   if (Subtarget->hasSVE()) {
832     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
833     // splat of 0 or undef) once vector selects supported in SVE codegen. See
834     // D68877 for more details.
835     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
836       if (isTypeLegal(VT))
837         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
838     }
839     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
840     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
841   }
842 
843   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
844 }
845 
846 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
847   assert(VT.isVector() && "VT should be a vector type");
848 
849   if (VT.isFloatingPoint()) {
850     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
851     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
852     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
853   }
854 
855   // Mark vector float intrinsics as expand.
856   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
857     setOperationAction(ISD::FSIN, VT, Expand);
858     setOperationAction(ISD::FCOS, VT, Expand);
859     setOperationAction(ISD::FPOW, VT, Expand);
860     setOperationAction(ISD::FLOG, VT, Expand);
861     setOperationAction(ISD::FLOG2, VT, Expand);
862     setOperationAction(ISD::FLOG10, VT, Expand);
863     setOperationAction(ISD::FEXP, VT, Expand);
864     setOperationAction(ISD::FEXP2, VT, Expand);
865 
866     // But we do support custom-lowering for FCOPYSIGN.
867     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
868   }
869 
870   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
871   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
872   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
873   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
874   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
875   setOperationAction(ISD::SRA, VT, Custom);
876   setOperationAction(ISD::SRL, VT, Custom);
877   setOperationAction(ISD::SHL, VT, Custom);
878   setOperationAction(ISD::OR, VT, Custom);
879   setOperationAction(ISD::SETCC, VT, Custom);
880   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
881 
882   setOperationAction(ISD::SELECT, VT, Expand);
883   setOperationAction(ISD::SELECT_CC, VT, Expand);
884   setOperationAction(ISD::VSELECT, VT, Expand);
885   for (MVT InnerVT : MVT::all_valuetypes())
886     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
887 
888   // CNT supports only B element sizes, then use UADDLP to widen.
889   if (VT != MVT::v8i8 && VT != MVT::v16i8)
890     setOperationAction(ISD::CTPOP, VT, Custom);
891 
892   setOperationAction(ISD::UDIV, VT, Expand);
893   setOperationAction(ISD::SDIV, VT, Expand);
894   setOperationAction(ISD::UREM, VT, Expand);
895   setOperationAction(ISD::SREM, VT, Expand);
896   setOperationAction(ISD::FREM, VT, Expand);
897 
898   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
899   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
900 
901   if (!VT.isFloatingPoint())
902     setOperationAction(ISD::ABS, VT, Legal);
903 
904   // [SU][MIN|MAX] are available for all NEON types apart from i64.
905   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
906     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
907       setOperationAction(Opcode, VT, Legal);
908 
909   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
910   if (VT.isFloatingPoint() &&
911       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
912     for (unsigned Opcode :
913          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
914       setOperationAction(Opcode, VT, Legal);
915 
916   if (Subtarget->isLittleEndian()) {
917     for (unsigned im = (unsigned)ISD::PRE_INC;
918          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
919       setIndexedLoadAction(im, VT, Legal);
920       setIndexedStoreAction(im, VT, Legal);
921     }
922   }
923 }
924 
925 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
926   addRegisterClass(VT, &AArch64::FPR64RegClass);
927   addTypeForNEON(VT, MVT::v2i32);
928 }
929 
930 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
931   addRegisterClass(VT, &AArch64::FPR128RegClass);
932   addTypeForNEON(VT, MVT::v4i32);
933 }
934 
935 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
936                                               EVT VT) const {
937   if (!VT.isVector())
938     return MVT::i32;
939   return VT.changeVectorElementTypeToInteger();
940 }
941 
942 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
943                                const APInt &Demanded,
944                                TargetLowering::TargetLoweringOpt &TLO,
945                                unsigned NewOpc) {
946   uint64_t OldImm = Imm, NewImm, Enc;
947   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
948 
949   // Return if the immediate is already all zeros, all ones, a bimm32 or a
950   // bimm64.
951   if (Imm == 0 || Imm == Mask ||
952       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
953     return false;
954 
955   unsigned EltSize = Size;
956   uint64_t DemandedBits = Demanded.getZExtValue();
957 
958   // Clear bits that are not demanded.
959   Imm &= DemandedBits;
960 
961   while (true) {
962     // The goal here is to set the non-demanded bits in a way that minimizes
963     // the number of switching between 0 and 1. In order to achieve this goal,
964     // we set the non-demanded bits to the value of the preceding demanded bits.
965     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
966     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
967     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
968     // The final result is 0b11000011.
969     uint64_t NonDemandedBits = ~DemandedBits;
970     uint64_t InvertedImm = ~Imm & DemandedBits;
971     uint64_t RotatedImm =
972         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
973         NonDemandedBits;
974     uint64_t Sum = RotatedImm + NonDemandedBits;
975     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
976     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
977     NewImm = (Imm | Ones) & Mask;
978 
979     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
980     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
981     // we halve the element size and continue the search.
982     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
983       break;
984 
985     // We cannot shrink the element size any further if it is 2-bits.
986     if (EltSize == 2)
987       return false;
988 
989     EltSize /= 2;
990     Mask >>= EltSize;
991     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
992 
993     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
994     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
995       return false;
996 
997     // Merge the upper and lower halves of Imm and DemandedBits.
998     Imm |= Hi;
999     DemandedBits |= DemandedBitsHi;
1000   }
1001 
1002   ++NumOptimizedImms;
1003 
1004   // Replicate the element across the register width.
1005   while (EltSize < Size) {
1006     NewImm |= NewImm << EltSize;
1007     EltSize *= 2;
1008   }
1009 
1010   (void)OldImm;
1011   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1012          "demanded bits should never be altered");
1013   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1014 
1015   // Create the new constant immediate node.
1016   EVT VT = Op.getValueType();
1017   SDLoc DL(Op);
1018   SDValue New;
1019 
1020   // If the new constant immediate is all-zeros or all-ones, let the target
1021   // independent DAG combine optimize this node.
1022   if (NewImm == 0 || NewImm == OrigMask) {
1023     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1024                           TLO.DAG.getConstant(NewImm, DL, VT));
1025   // Otherwise, create a machine node so that target independent DAG combine
1026   // doesn't undo this optimization.
1027   } else {
1028     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1029     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1030     New = SDValue(
1031         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1032   }
1033 
1034   return TLO.CombineTo(Op, New);
1035 }
1036 
1037 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1038     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1039   // Delay this optimization to as late as possible.
1040   if (!TLO.LegalOps)
1041     return false;
1042 
1043   if (!EnableOptimizeLogicalImm)
1044     return false;
1045 
1046   EVT VT = Op.getValueType();
1047   if (VT.isVector())
1048     return false;
1049 
1050   unsigned Size = VT.getSizeInBits();
1051   assert((Size == 32 || Size == 64) &&
1052          "i32 or i64 is expected after legalization.");
1053 
1054   // Exit early if we demand all bits.
1055   if (Demanded.countPopulation() == Size)
1056     return false;
1057 
1058   unsigned NewOpc;
1059   switch (Op.getOpcode()) {
1060   default:
1061     return false;
1062   case ISD::AND:
1063     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1064     break;
1065   case ISD::OR:
1066     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1067     break;
1068   case ISD::XOR:
1069     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1070     break;
1071   }
1072   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1073   if (!C)
1074     return false;
1075   uint64_t Imm = C->getZExtValue();
1076   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1077 }
1078 
1079 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1080 /// Mask are known to be either zero or one and return them Known.
1081 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1082     const SDValue Op, KnownBits &Known,
1083     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1084   switch (Op.getOpcode()) {
1085   default:
1086     break;
1087   case AArch64ISD::CSEL: {
1088     KnownBits Known2;
1089     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1090     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1091     Known.Zero &= Known2.Zero;
1092     Known.One &= Known2.One;
1093     break;
1094   }
1095   case AArch64ISD::LOADgot:
1096   case AArch64ISD::ADDlow: {
1097     if (!Subtarget->isTargetILP32())
1098       break;
1099     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1100     Known.Zero = APInt::getHighBitsSet(64, 32);
1101     break;
1102   }
1103   case ISD::INTRINSIC_W_CHAIN: {
1104     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1105     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1106     switch (IntID) {
1107     default: return;
1108     case Intrinsic::aarch64_ldaxr:
1109     case Intrinsic::aarch64_ldxr: {
1110       unsigned BitWidth = Known.getBitWidth();
1111       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1112       unsigned MemBits = VT.getScalarSizeInBits();
1113       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1114       return;
1115     }
1116     }
1117     break;
1118   }
1119   case ISD::INTRINSIC_WO_CHAIN:
1120   case ISD::INTRINSIC_VOID: {
1121     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1122     switch (IntNo) {
1123     default:
1124       break;
1125     case Intrinsic::aarch64_neon_umaxv:
1126     case Intrinsic::aarch64_neon_uminv: {
1127       // Figure out the datatype of the vector operand. The UMINV instruction
1128       // will zero extend the result, so we can mark as known zero all the
1129       // bits larger than the element datatype. 32-bit or larget doesn't need
1130       // this as those are legal types and will be handled by isel directly.
1131       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1132       unsigned BitWidth = Known.getBitWidth();
1133       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1134         assert(BitWidth >= 8 && "Unexpected width!");
1135         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1136         Known.Zero |= Mask;
1137       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1138         assert(BitWidth >= 16 && "Unexpected width!");
1139         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1140         Known.Zero |= Mask;
1141       }
1142       break;
1143     } break;
1144     }
1145   }
1146   }
1147 }
1148 
1149 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1150                                                   EVT) const {
1151   return MVT::i64;
1152 }
1153 
1154 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1155     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1156     bool *Fast) const {
1157   if (Subtarget->requiresStrictAlign())
1158     return false;
1159 
1160   if (Fast) {
1161     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1162     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1163             // See comments in performSTORECombine() for more details about
1164             // these conditions.
1165 
1166             // Code that uses clang vector extensions can mark that it
1167             // wants unaligned accesses to be treated as fast by
1168             // underspecifying alignment to be 1 or 2.
1169             Align <= 2 ||
1170 
1171             // Disregard v2i64. Memcpy lowering produces those and splitting
1172             // them regresses performance on micro-benchmarks and olden/bh.
1173             VT == MVT::v2i64;
1174   }
1175   return true;
1176 }
1177 
1178 // Same as above but handling LLTs instead.
1179 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1180     LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1181     bool *Fast) const {
1182   if (Subtarget->requiresStrictAlign())
1183     return false;
1184 
1185   if (Fast) {
1186     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1187     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1188             Ty.getSizeInBytes() != 16 ||
1189             // See comments in performSTORECombine() for more details about
1190             // these conditions.
1191 
1192             // Code that uses clang vector extensions can mark that it
1193             // wants unaligned accesses to be treated as fast by
1194             // underspecifying alignment to be 1 or 2.
1195             Align <= 2 ||
1196 
1197             // Disregard v2i64. Memcpy lowering produces those and splitting
1198             // them regresses performance on micro-benchmarks and olden/bh.
1199             Ty == LLT::vector(2, 64);
1200   }
1201   return true;
1202 }
1203 
1204 FastISel *
1205 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1206                                       const TargetLibraryInfo *libInfo) const {
1207   return AArch64::createFastISel(funcInfo, libInfo);
1208 }
1209 
1210 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1211   switch ((AArch64ISD::NodeType)Opcode) {
1212   case AArch64ISD::FIRST_NUMBER:      break;
1213   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1214   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1215   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1216   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1217   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1218   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1219   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1220   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1221   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1222   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1223   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1224   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1225   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1226   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1227   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1228   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1229   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1230   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1231   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1232   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1233   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1234   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1235   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1236   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1237   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1238   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1239   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1240   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1241   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1242   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1243   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1244   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1245   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1246   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1247   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1248   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1249   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1250   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1251   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1252   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1253   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1254   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1255   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1256   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1257   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1258   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1259   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1260   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1261   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1262   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1263   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1264   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1265   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1266   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1267   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1268   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1269   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1270   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1271   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1272   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1273   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1274   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1275   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1276   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1277   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1278   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1279   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1280   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1281   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1282   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1283   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1284   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1285   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1286   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1287   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1288   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1289   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1290   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1291   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1292   case AArch64ISD::SMAXV_PRED:        return "AArch64ISD::SMAXV_PRED";
1293   case AArch64ISD::UMAXV_PRED:        return "AArch64ISD::UMAXV_PRED";
1294   case AArch64ISD::SMINV_PRED:        return "AArch64ISD::SMINV_PRED";
1295   case AArch64ISD::UMINV_PRED:        return "AArch64ISD::UMINV_PRED";
1296   case AArch64ISD::ORV_PRED:          return "AArch64ISD::ORV_PRED";
1297   case AArch64ISD::EORV_PRED:         return "AArch64ISD::EORV_PRED";
1298   case AArch64ISD::ANDV_PRED:         return "AArch64ISD::ANDV_PRED";
1299   case AArch64ISD::CLASTA_N:          return "AArch64ISD::CLASTA_N";
1300   case AArch64ISD::CLASTB_N:          return "AArch64ISD::CLASTB_N";
1301   case AArch64ISD::LASTA:             return "AArch64ISD::LASTA";
1302   case AArch64ISD::LASTB:             return "AArch64ISD::LASTB";
1303   case AArch64ISD::REV:               return "AArch64ISD::REV";
1304   case AArch64ISD::TBL:               return "AArch64ISD::TBL";
1305   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1306   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1307   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1308   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1309   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1310   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1311   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1312   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1313   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1314   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1315   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1316   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1317   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1318   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1319   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1320   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1321   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1322   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1323   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1324   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1325   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1326   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1327   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1328   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1329   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1330   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1331   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1332   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1333   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1334   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1335   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1336   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1337   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1338   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1339   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1340   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1341   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1342   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1343   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1344   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1345   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1346   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1347   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1348   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1349   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1350   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1351   case AArch64ISD::STG:               return "AArch64ISD::STG";
1352   case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1353   case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1354   case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1355   case AArch64ISD::SUNPKHI:           return "AArch64ISD::SUNPKHI";
1356   case AArch64ISD::SUNPKLO:           return "AArch64ISD::SUNPKLO";
1357   case AArch64ISD::UUNPKHI:           return "AArch64ISD::UUNPKHI";
1358   case AArch64ISD::UUNPKLO:           return "AArch64ISD::UUNPKLO";
1359   case AArch64ISD::INSR:              return "AArch64ISD::INSR";
1360   case AArch64ISD::PTEST:             return "AArch64ISD::PTEST";
1361   case AArch64ISD::PTRUE:             return "AArch64ISD::PTRUE";
1362   case AArch64ISD::GLD1:              return "AArch64ISD::GLD1";
1363   case AArch64ISD::GLD1_SCALED:       return "AArch64ISD::GLD1_SCALED";
1364   case AArch64ISD::GLD1_SXTW:         return "AArch64ISD::GLD1_SXTW";
1365   case AArch64ISD::GLD1_UXTW:         return "AArch64ISD::GLD1_UXTW";
1366   case AArch64ISD::GLD1_SXTW_SCALED:  return "AArch64ISD::GLD1_SXTW_SCALED";
1367   case AArch64ISD::GLD1_UXTW_SCALED:  return "AArch64ISD::GLD1_UXTW_SCALED";
1368   case AArch64ISD::GLD1_IMM:          return "AArch64ISD::GLD1_IMM";
1369   case AArch64ISD::GLD1S:             return "AArch64ISD::GLD1S";
1370   case AArch64ISD::GLD1S_SCALED:      return "AArch64ISD::GLD1S_SCALED";
1371   case AArch64ISD::GLD1S_SXTW:        return "AArch64ISD::GLD1S_SXTW";
1372   case AArch64ISD::GLD1S_UXTW:        return "AArch64ISD::GLD1S_UXTW";
1373   case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED";
1374   case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED";
1375   case AArch64ISD::GLD1S_IMM:         return "AArch64ISD::GLD1S_IMM";
1376   case AArch64ISD::SST1:              return "AArch64ISD::SST1";
1377   case AArch64ISD::SST1_SCALED:       return "AArch64ISD::SST1_SCALED";
1378   case AArch64ISD::SST1_SXTW:         return "AArch64ISD::SST1_SXTW";
1379   case AArch64ISD::SST1_UXTW:         return "AArch64ISD::SST1_UXTW";
1380   case AArch64ISD::SST1_SXTW_SCALED:  return "AArch64ISD::SST1_SXTW_SCALED";
1381   case AArch64ISD::SST1_UXTW_SCALED:  return "AArch64ISD::SST1_UXTW_SCALED";
1382   case AArch64ISD::SST1_IMM:          return "AArch64ISD::SST1_IMM";
1383   case AArch64ISD::LDP:               return "AArch64ISD::LDP";
1384   case AArch64ISD::STP:               return "AArch64ISD::STP";
1385   }
1386   return nullptr;
1387 }
1388 
1389 MachineBasicBlock *
1390 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1391                                     MachineBasicBlock *MBB) const {
1392   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1393   // phi node:
1394 
1395   // OrigBB:
1396   //     [... previous instrs leading to comparison ...]
1397   //     b.ne TrueBB
1398   //     b EndBB
1399   // TrueBB:
1400   //     ; Fallthrough
1401   // EndBB:
1402   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1403 
1404   MachineFunction *MF = MBB->getParent();
1405   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1406   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1407   DebugLoc DL = MI.getDebugLoc();
1408   MachineFunction::iterator It = ++MBB->getIterator();
1409 
1410   Register DestReg = MI.getOperand(0).getReg();
1411   Register IfTrueReg = MI.getOperand(1).getReg();
1412   Register IfFalseReg = MI.getOperand(2).getReg();
1413   unsigned CondCode = MI.getOperand(3).getImm();
1414   bool NZCVKilled = MI.getOperand(4).isKill();
1415 
1416   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1417   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1418   MF->insert(It, TrueBB);
1419   MF->insert(It, EndBB);
1420 
1421   // Transfer rest of current basic-block to EndBB
1422   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1423                 MBB->end());
1424   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1425 
1426   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1427   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1428   MBB->addSuccessor(TrueBB);
1429   MBB->addSuccessor(EndBB);
1430 
1431   // TrueBB falls through to the end.
1432   TrueBB->addSuccessor(EndBB);
1433 
1434   if (!NZCVKilled) {
1435     TrueBB->addLiveIn(AArch64::NZCV);
1436     EndBB->addLiveIn(AArch64::NZCV);
1437   }
1438 
1439   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1440       .addReg(IfTrueReg)
1441       .addMBB(TrueBB)
1442       .addReg(IfFalseReg)
1443       .addMBB(MBB);
1444 
1445   MI.eraseFromParent();
1446   return EndBB;
1447 }
1448 
1449 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1450        MachineInstr &MI, MachineBasicBlock *BB) const {
1451   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1452              BB->getParent()->getFunction().getPersonalityFn())) &&
1453          "SEH does not use catchret!");
1454   return BB;
1455 }
1456 
1457 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1458      MachineInstr &MI, MachineBasicBlock *BB) const {
1459   MI.eraseFromParent();
1460   return BB;
1461 }
1462 
1463 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1464     MachineInstr &MI, MachineBasicBlock *BB) const {
1465   switch (MI.getOpcode()) {
1466   default:
1467 #ifndef NDEBUG
1468     MI.dump();
1469 #endif
1470     llvm_unreachable("Unexpected instruction for custom inserter!");
1471 
1472   case AArch64::F128CSEL:
1473     return EmitF128CSEL(MI, BB);
1474 
1475   case TargetOpcode::STACKMAP:
1476   case TargetOpcode::PATCHPOINT:
1477     return emitPatchPoint(MI, BB);
1478 
1479   case AArch64::CATCHRET:
1480     return EmitLoweredCatchRet(MI, BB);
1481   case AArch64::CATCHPAD:
1482     return EmitLoweredCatchPad(MI, BB);
1483   }
1484 }
1485 
1486 //===----------------------------------------------------------------------===//
1487 // AArch64 Lowering private implementation.
1488 //===----------------------------------------------------------------------===//
1489 
1490 //===----------------------------------------------------------------------===//
1491 // Lowering Code
1492 //===----------------------------------------------------------------------===//
1493 
1494 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1495 /// CC
1496 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1497   switch (CC) {
1498   default:
1499     llvm_unreachable("Unknown condition code!");
1500   case ISD::SETNE:
1501     return AArch64CC::NE;
1502   case ISD::SETEQ:
1503     return AArch64CC::EQ;
1504   case ISD::SETGT:
1505     return AArch64CC::GT;
1506   case ISD::SETGE:
1507     return AArch64CC::GE;
1508   case ISD::SETLT:
1509     return AArch64CC::LT;
1510   case ISD::SETLE:
1511     return AArch64CC::LE;
1512   case ISD::SETUGT:
1513     return AArch64CC::HI;
1514   case ISD::SETUGE:
1515     return AArch64CC::HS;
1516   case ISD::SETULT:
1517     return AArch64CC::LO;
1518   case ISD::SETULE:
1519     return AArch64CC::LS;
1520   }
1521 }
1522 
1523 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1524 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1525                                   AArch64CC::CondCode &CondCode,
1526                                   AArch64CC::CondCode &CondCode2) {
1527   CondCode2 = AArch64CC::AL;
1528   switch (CC) {
1529   default:
1530     llvm_unreachable("Unknown FP condition!");
1531   case ISD::SETEQ:
1532   case ISD::SETOEQ:
1533     CondCode = AArch64CC::EQ;
1534     break;
1535   case ISD::SETGT:
1536   case ISD::SETOGT:
1537     CondCode = AArch64CC::GT;
1538     break;
1539   case ISD::SETGE:
1540   case ISD::SETOGE:
1541     CondCode = AArch64CC::GE;
1542     break;
1543   case ISD::SETOLT:
1544     CondCode = AArch64CC::MI;
1545     break;
1546   case ISD::SETOLE:
1547     CondCode = AArch64CC::LS;
1548     break;
1549   case ISD::SETONE:
1550     CondCode = AArch64CC::MI;
1551     CondCode2 = AArch64CC::GT;
1552     break;
1553   case ISD::SETO:
1554     CondCode = AArch64CC::VC;
1555     break;
1556   case ISD::SETUO:
1557     CondCode = AArch64CC::VS;
1558     break;
1559   case ISD::SETUEQ:
1560     CondCode = AArch64CC::EQ;
1561     CondCode2 = AArch64CC::VS;
1562     break;
1563   case ISD::SETUGT:
1564     CondCode = AArch64CC::HI;
1565     break;
1566   case ISD::SETUGE:
1567     CondCode = AArch64CC::PL;
1568     break;
1569   case ISD::SETLT:
1570   case ISD::SETULT:
1571     CondCode = AArch64CC::LT;
1572     break;
1573   case ISD::SETLE:
1574   case ISD::SETULE:
1575     CondCode = AArch64CC::LE;
1576     break;
1577   case ISD::SETNE:
1578   case ISD::SETUNE:
1579     CondCode = AArch64CC::NE;
1580     break;
1581   }
1582 }
1583 
1584 /// Convert a DAG fp condition code to an AArch64 CC.
1585 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1586 /// should be AND'ed instead of OR'ed.
1587 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1588                                      AArch64CC::CondCode &CondCode,
1589                                      AArch64CC::CondCode &CondCode2) {
1590   CondCode2 = AArch64CC::AL;
1591   switch (CC) {
1592   default:
1593     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1594     assert(CondCode2 == AArch64CC::AL);
1595     break;
1596   case ISD::SETONE:
1597     // (a one b)
1598     // == ((a olt b) || (a ogt b))
1599     // == ((a ord b) && (a une b))
1600     CondCode = AArch64CC::VC;
1601     CondCode2 = AArch64CC::NE;
1602     break;
1603   case ISD::SETUEQ:
1604     // (a ueq b)
1605     // == ((a uno b) || (a oeq b))
1606     // == ((a ule b) && (a uge b))
1607     CondCode = AArch64CC::PL;
1608     CondCode2 = AArch64CC::LE;
1609     break;
1610   }
1611 }
1612 
1613 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1614 /// CC usable with the vector instructions. Fewer operations are available
1615 /// without a real NZCV register, so we have to use less efficient combinations
1616 /// to get the same effect.
1617 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1618                                         AArch64CC::CondCode &CondCode,
1619                                         AArch64CC::CondCode &CondCode2,
1620                                         bool &Invert) {
1621   Invert = false;
1622   switch (CC) {
1623   default:
1624     // Mostly the scalar mappings work fine.
1625     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1626     break;
1627   case ISD::SETUO:
1628     Invert = true;
1629     LLVM_FALLTHROUGH;
1630   case ISD::SETO:
1631     CondCode = AArch64CC::MI;
1632     CondCode2 = AArch64CC::GE;
1633     break;
1634   case ISD::SETUEQ:
1635   case ISD::SETULT:
1636   case ISD::SETULE:
1637   case ISD::SETUGT:
1638   case ISD::SETUGE:
1639     // All of the compare-mask comparisons are ordered, but we can switch
1640     // between the two by a double inversion. E.g. ULE == !OGT.
1641     Invert = true;
1642     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1643                           CondCode, CondCode2);
1644     break;
1645   }
1646 }
1647 
1648 static bool isLegalArithImmed(uint64_t C) {
1649   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1650   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1651   LLVM_DEBUG(dbgs() << "Is imm " << C
1652                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1653   return IsLegal;
1654 }
1655 
1656 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1657 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1658 // can be set differently by this operation. It comes down to whether
1659 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1660 // everything is fine. If not then the optimization is wrong. Thus general
1661 // comparisons are only valid if op2 != 0.
1662 //
1663 // So, finally, the only LLVM-native comparisons that don't mention C and V
1664 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1665 // the absence of information about op2.
1666 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1667   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1668          (CC == ISD::SETEQ || CC == ISD::SETNE);
1669 }
1670 
1671 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1672                               const SDLoc &dl, SelectionDAG &DAG) {
1673   EVT VT = LHS.getValueType();
1674   const bool FullFP16 =
1675     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1676 
1677   if (VT.isFloatingPoint()) {
1678     assert(VT != MVT::f128);
1679     if (VT == MVT::f16 && !FullFP16) {
1680       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1681       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1682       VT = MVT::f32;
1683     }
1684     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1685   }
1686 
1687   // The CMP instruction is just an alias for SUBS, and representing it as
1688   // SUBS means that it's possible to get CSE with subtract operations.
1689   // A later phase can perform the optimization of setting the destination
1690   // register to WZR/XZR if it ends up being unused.
1691   unsigned Opcode = AArch64ISD::SUBS;
1692 
1693   if (isCMN(RHS, CC)) {
1694     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1695     Opcode = AArch64ISD::ADDS;
1696     RHS = RHS.getOperand(1);
1697   } else if (isCMN(LHS, CC)) {
1698     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1699     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1700     Opcode = AArch64ISD::ADDS;
1701     LHS = LHS.getOperand(1);
1702   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1703              !isUnsignedIntSetCC(CC)) {
1704     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1705     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1706     // of the signed comparisons.
1707     Opcode = AArch64ISD::ANDS;
1708     RHS = LHS.getOperand(1);
1709     LHS = LHS.getOperand(0);
1710   }
1711 
1712   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1713       .getValue(1);
1714 }
1715 
1716 /// \defgroup AArch64CCMP CMP;CCMP matching
1717 ///
1718 /// These functions deal with the formation of CMP;CCMP;... sequences.
1719 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1720 /// a comparison. They set the NZCV flags to a predefined value if their
1721 /// predicate is false. This allows to express arbitrary conjunctions, for
1722 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1723 /// expressed as:
1724 ///   cmp A
1725 ///   ccmp B, inv(CB), CA
1726 ///   check for CB flags
1727 ///
1728 /// This naturally lets us implement chains of AND operations with SETCC
1729 /// operands. And we can even implement some other situations by transforming
1730 /// them:
1731 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1732 ///     negating the flags used in a CCMP/FCCMP operations.
1733 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1734 ///     by negating the flags we test for afterwards. i.e.
1735 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1736 ///   - Note that we can only ever negate all previously processed results.
1737 ///     What we can not implement by flipping the flags to test is a negation
1738 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1739 ///     far, so the 2nd sub-tree we emit would also affect the first).
1740 /// With those tools we can implement some OR operations:
1741 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1742 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1743 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1744 ///     elimination rules from earlier to implement the whole thing as a
1745 ///     CCMP/FCCMP chain.
1746 ///
1747 /// As complete example:
1748 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1749 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1750 /// can be reassociated to:
1751 ///     or (and (setCC (cmp C)) setCD (cmp D))
1752 //         (or (setCA (cmp A)) (setCB (cmp B)))
1753 /// can be transformed to:
1754 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1755 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1756 /// which can be implemented as:
1757 ///   cmp C
1758 ///   ccmp D, inv(CD), CC
1759 ///   ccmp A, CA, inv(CD)
1760 ///   ccmp B, CB, inv(CA)
1761 ///   check for CB flags
1762 ///
1763 /// A counterexample is "or (and A B) (and C D)" which translates to
1764 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1765 /// can only implement 1 of the inner (not) operations, but not both!
1766 /// @{
1767 
1768 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1769 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1770                                          ISD::CondCode CC, SDValue CCOp,
1771                                          AArch64CC::CondCode Predicate,
1772                                          AArch64CC::CondCode OutCC,
1773                                          const SDLoc &DL, SelectionDAG &DAG) {
1774   unsigned Opcode = 0;
1775   const bool FullFP16 =
1776     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1777 
1778   if (LHS.getValueType().isFloatingPoint()) {
1779     assert(LHS.getValueType() != MVT::f128);
1780     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1781       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1782       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1783     }
1784     Opcode = AArch64ISD::FCCMP;
1785   } else if (RHS.getOpcode() == ISD::SUB) {
1786     SDValue SubOp0 = RHS.getOperand(0);
1787     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1788       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1789       Opcode = AArch64ISD::CCMN;
1790       RHS = RHS.getOperand(1);
1791     }
1792   }
1793   if (Opcode == 0)
1794     Opcode = AArch64ISD::CCMP;
1795 
1796   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1797   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1798   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1799   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1800   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1801 }
1802 
1803 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1804 /// expressed as a conjunction. See \ref AArch64CCMP.
1805 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1806 ///                     changing the conditions on the SETCC tests.
1807 ///                     (this means we can call emitConjunctionRec() with
1808 ///                      Negate==true on this sub-tree)
1809 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1810 ///                     cannot do the negation naturally. We are required to
1811 ///                     emit the subtree first in this case.
1812 /// \param WillNegate   Is true if are called when the result of this
1813 ///                     subexpression must be negated. This happens when the
1814 ///                     outer expression is an OR. We can use this fact to know
1815 ///                     that we have a double negation (or (or ...) ...) that
1816 ///                     can be implemented for free.
1817 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1818                                bool &MustBeFirst, bool WillNegate,
1819                                unsigned Depth = 0) {
1820   if (!Val.hasOneUse())
1821     return false;
1822   unsigned Opcode = Val->getOpcode();
1823   if (Opcode == ISD::SETCC) {
1824     if (Val->getOperand(0).getValueType() == MVT::f128)
1825       return false;
1826     CanNegate = true;
1827     MustBeFirst = false;
1828     return true;
1829   }
1830   // Protect against exponential runtime and stack overflow.
1831   if (Depth > 6)
1832     return false;
1833   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1834     bool IsOR = Opcode == ISD::OR;
1835     SDValue O0 = Val->getOperand(0);
1836     SDValue O1 = Val->getOperand(1);
1837     bool CanNegateL;
1838     bool MustBeFirstL;
1839     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1840       return false;
1841     bool CanNegateR;
1842     bool MustBeFirstR;
1843     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1844       return false;
1845 
1846     if (MustBeFirstL && MustBeFirstR)
1847       return false;
1848 
1849     if (IsOR) {
1850       // For an OR expression we need to be able to naturally negate at least
1851       // one side or we cannot do the transformation at all.
1852       if (!CanNegateL && !CanNegateR)
1853         return false;
1854       // If we the result of the OR will be negated and we can naturally negate
1855       // the leafs, then this sub-tree as a whole negates naturally.
1856       CanNegate = WillNegate && CanNegateL && CanNegateR;
1857       // If we cannot naturally negate the whole sub-tree, then this must be
1858       // emitted first.
1859       MustBeFirst = !CanNegate;
1860     } else {
1861       assert(Opcode == ISD::AND && "Must be OR or AND");
1862       // We cannot naturally negate an AND operation.
1863       CanNegate = false;
1864       MustBeFirst = MustBeFirstL || MustBeFirstR;
1865     }
1866     return true;
1867   }
1868   return false;
1869 }
1870 
1871 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1872 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1873 /// Tries to transform the given i1 producing node @p Val to a series compare
1874 /// and conditional compare operations. @returns an NZCV flags producing node
1875 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1876 /// transformation was not possible.
1877 /// \p Negate is true if we want this sub-tree being negated just by changing
1878 /// SETCC conditions.
1879 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1880     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1881     AArch64CC::CondCode Predicate) {
1882   // We're at a tree leaf, produce a conditional comparison operation.
1883   unsigned Opcode = Val->getOpcode();
1884   if (Opcode == ISD::SETCC) {
1885     SDValue LHS = Val->getOperand(0);
1886     SDValue RHS = Val->getOperand(1);
1887     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1888     bool isInteger = LHS.getValueType().isInteger();
1889     if (Negate)
1890       CC = getSetCCInverse(CC, LHS.getValueType());
1891     SDLoc DL(Val);
1892     // Determine OutCC and handle FP special case.
1893     if (isInteger) {
1894       OutCC = changeIntCCToAArch64CC(CC);
1895     } else {
1896       assert(LHS.getValueType().isFloatingPoint());
1897       AArch64CC::CondCode ExtraCC;
1898       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1899       // Some floating point conditions can't be tested with a single condition
1900       // code. Construct an additional comparison in this case.
1901       if (ExtraCC != AArch64CC::AL) {
1902         SDValue ExtraCmp;
1903         if (!CCOp.getNode())
1904           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1905         else
1906           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1907                                                ExtraCC, DL, DAG);
1908         CCOp = ExtraCmp;
1909         Predicate = ExtraCC;
1910       }
1911     }
1912 
1913     // Produce a normal comparison if we are first in the chain
1914     if (!CCOp)
1915       return emitComparison(LHS, RHS, CC, DL, DAG);
1916     // Otherwise produce a ccmp.
1917     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1918                                      DAG);
1919   }
1920   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1921 
1922   bool IsOR = Opcode == ISD::OR;
1923 
1924   SDValue LHS = Val->getOperand(0);
1925   bool CanNegateL;
1926   bool MustBeFirstL;
1927   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1928   assert(ValidL && "Valid conjunction/disjunction tree");
1929   (void)ValidL;
1930 
1931   SDValue RHS = Val->getOperand(1);
1932   bool CanNegateR;
1933   bool MustBeFirstR;
1934   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1935   assert(ValidR && "Valid conjunction/disjunction tree");
1936   (void)ValidR;
1937 
1938   // Swap sub-tree that must come first to the right side.
1939   if (MustBeFirstL) {
1940     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1941     std::swap(LHS, RHS);
1942     std::swap(CanNegateL, CanNegateR);
1943     std::swap(MustBeFirstL, MustBeFirstR);
1944   }
1945 
1946   bool NegateR;
1947   bool NegateAfterR;
1948   bool NegateL;
1949   bool NegateAfterAll;
1950   if (Opcode == ISD::OR) {
1951     // Swap the sub-tree that we can negate naturally to the left.
1952     if (!CanNegateL) {
1953       assert(CanNegateR && "at least one side must be negatable");
1954       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1955       assert(!Negate);
1956       std::swap(LHS, RHS);
1957       NegateR = false;
1958       NegateAfterR = true;
1959     } else {
1960       // Negate the left sub-tree if possible, otherwise negate the result.
1961       NegateR = CanNegateR;
1962       NegateAfterR = !CanNegateR;
1963     }
1964     NegateL = true;
1965     NegateAfterAll = !Negate;
1966   } else {
1967     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1968     assert(!Negate && "Valid conjunction/disjunction tree");
1969 
1970     NegateL = false;
1971     NegateR = false;
1972     NegateAfterR = false;
1973     NegateAfterAll = false;
1974   }
1975 
1976   // Emit sub-trees.
1977   AArch64CC::CondCode RHSCC;
1978   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1979   if (NegateAfterR)
1980     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1981   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1982   if (NegateAfterAll)
1983     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1984   return CmpL;
1985 }
1986 
1987 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1988 /// In some cases this is even possible with OR operations in the expression.
1989 /// See \ref AArch64CCMP.
1990 /// \see emitConjunctionRec().
1991 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1992                                AArch64CC::CondCode &OutCC) {
1993   bool DummyCanNegate;
1994   bool DummyMustBeFirst;
1995   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
1996     return SDValue();
1997 
1998   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1999 }
2000 
2001 /// @}
2002 
2003 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2004 /// extension operations.
2005 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2006   auto isSupportedExtend = [&](SDValue V) {
2007     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2008       return true;
2009 
2010     if (V.getOpcode() == ISD::AND)
2011       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2012         uint64_t Mask = MaskCst->getZExtValue();
2013         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2014       }
2015 
2016     return false;
2017   };
2018 
2019   if (!Op.hasOneUse())
2020     return 0;
2021 
2022   if (isSupportedExtend(Op))
2023     return 1;
2024 
2025   unsigned Opc = Op.getOpcode();
2026   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2027     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2028       uint64_t Shift = ShiftCst->getZExtValue();
2029       if (isSupportedExtend(Op.getOperand(0)))
2030         return (Shift <= 4) ? 2 : 1;
2031       EVT VT = Op.getValueType();
2032       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2033         return 1;
2034     }
2035 
2036   return 0;
2037 }
2038 
2039 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2040                              SDValue &AArch64cc, SelectionDAG &DAG,
2041                              const SDLoc &dl) {
2042   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2043     EVT VT = RHS.getValueType();
2044     uint64_t C = RHSC->getZExtValue();
2045     if (!isLegalArithImmed(C)) {
2046       // Constant does not fit, try adjusting it by one?
2047       switch (CC) {
2048       default:
2049         break;
2050       case ISD::SETLT:
2051       case ISD::SETGE:
2052         if ((VT == MVT::i32 && C != 0x80000000 &&
2053              isLegalArithImmed((uint32_t)(C - 1))) ||
2054             (VT == MVT::i64 && C != 0x80000000ULL &&
2055              isLegalArithImmed(C - 1ULL))) {
2056           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2057           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2058           RHS = DAG.getConstant(C, dl, VT);
2059         }
2060         break;
2061       case ISD::SETULT:
2062       case ISD::SETUGE:
2063         if ((VT == MVT::i32 && C != 0 &&
2064              isLegalArithImmed((uint32_t)(C - 1))) ||
2065             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2066           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2067           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2068           RHS = DAG.getConstant(C, dl, VT);
2069         }
2070         break;
2071       case ISD::SETLE:
2072       case ISD::SETGT:
2073         if ((VT == MVT::i32 && C != INT32_MAX &&
2074              isLegalArithImmed((uint32_t)(C + 1))) ||
2075             (VT == MVT::i64 && C != INT64_MAX &&
2076              isLegalArithImmed(C + 1ULL))) {
2077           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2078           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2079           RHS = DAG.getConstant(C, dl, VT);
2080         }
2081         break;
2082       case ISD::SETULE:
2083       case ISD::SETUGT:
2084         if ((VT == MVT::i32 && C != UINT32_MAX &&
2085              isLegalArithImmed((uint32_t)(C + 1))) ||
2086             (VT == MVT::i64 && C != UINT64_MAX &&
2087              isLegalArithImmed(C + 1ULL))) {
2088           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2089           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2090           RHS = DAG.getConstant(C, dl, VT);
2091         }
2092         break;
2093       }
2094     }
2095   }
2096 
2097   // Comparisons are canonicalized so that the RHS operand is simpler than the
2098   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2099   // can fold some shift+extend operations on the RHS operand, so swap the
2100   // operands if that can be done.
2101   //
2102   // For example:
2103   //    lsl     w13, w11, #1
2104   //    cmp     w13, w12
2105   // can be turned into:
2106   //    cmp     w12, w11, lsl #1
2107   if (!isa<ConstantSDNode>(RHS) ||
2108       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2109     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2110 
2111     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2112       std::swap(LHS, RHS);
2113       CC = ISD::getSetCCSwappedOperands(CC);
2114     }
2115   }
2116 
2117   SDValue Cmp;
2118   AArch64CC::CondCode AArch64CC;
2119   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2120     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2121 
2122     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2123     // For the i8 operand, the largest immediate is 255, so this can be easily
2124     // encoded in the compare instruction. For the i16 operand, however, the
2125     // largest immediate cannot be encoded in the compare.
2126     // Therefore, use a sign extending load and cmn to avoid materializing the
2127     // -1 constant. For example,
2128     // movz w1, #65535
2129     // ldrh w0, [x0, #0]
2130     // cmp w0, w1
2131     // >
2132     // ldrsh w0, [x0, #0]
2133     // cmn w0, #1
2134     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2135     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2136     // ensure both the LHS and RHS are truly zero extended and to make sure the
2137     // transformation is profitable.
2138     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2139         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2140         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2141         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2142       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2143       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2144         SDValue SExt =
2145             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2146                         DAG.getValueType(MVT::i16));
2147         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2148                                                    RHS.getValueType()),
2149                              CC, dl, DAG);
2150         AArch64CC = changeIntCCToAArch64CC(CC);
2151       }
2152     }
2153 
2154     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2155       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2156         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2157           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2158       }
2159     }
2160   }
2161 
2162   if (!Cmp) {
2163     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2164     AArch64CC = changeIntCCToAArch64CC(CC);
2165   }
2166   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2167   return Cmp;
2168 }
2169 
2170 static std::pair<SDValue, SDValue>
2171 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2172   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2173          "Unsupported value type");
2174   SDValue Value, Overflow;
2175   SDLoc DL(Op);
2176   SDValue LHS = Op.getOperand(0);
2177   SDValue RHS = Op.getOperand(1);
2178   unsigned Opc = 0;
2179   switch (Op.getOpcode()) {
2180   default:
2181     llvm_unreachable("Unknown overflow instruction!");
2182   case ISD::SADDO:
2183     Opc = AArch64ISD::ADDS;
2184     CC = AArch64CC::VS;
2185     break;
2186   case ISD::UADDO:
2187     Opc = AArch64ISD::ADDS;
2188     CC = AArch64CC::HS;
2189     break;
2190   case ISD::SSUBO:
2191     Opc = AArch64ISD::SUBS;
2192     CC = AArch64CC::VS;
2193     break;
2194   case ISD::USUBO:
2195     Opc = AArch64ISD::SUBS;
2196     CC = AArch64CC::LO;
2197     break;
2198   // Multiply needs a little bit extra work.
2199   case ISD::SMULO:
2200   case ISD::UMULO: {
2201     CC = AArch64CC::NE;
2202     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2203     if (Op.getValueType() == MVT::i32) {
2204       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2205       // For a 32 bit multiply with overflow check we want the instruction
2206       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2207       // need to generate the following pattern:
2208       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2209       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2210       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2211       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2212       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2213                                 DAG.getConstant(0, DL, MVT::i64));
2214       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2215       // operation. We need to clear out the upper 32 bits, because we used a
2216       // widening multiply that wrote all 64 bits. In the end this should be a
2217       // noop.
2218       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2219       if (IsSigned) {
2220         // The signed overflow check requires more than just a simple check for
2221         // any bit set in the upper 32 bits of the result. These bits could be
2222         // just the sign bits of a negative number. To perform the overflow
2223         // check we have to arithmetic shift right the 32nd bit of the result by
2224         // 31 bits. Then we compare the result to the upper 32 bits.
2225         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2226                                         DAG.getConstant(32, DL, MVT::i64));
2227         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2228         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2229                                         DAG.getConstant(31, DL, MVT::i64));
2230         // It is important that LowerBits is last, otherwise the arithmetic
2231         // shift will not be folded into the compare (SUBS).
2232         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2233         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2234                        .getValue(1);
2235       } else {
2236         // The overflow check for unsigned multiply is easy. We only need to
2237         // check if any of the upper 32 bits are set. This can be done with a
2238         // CMP (shifted register). For that we need to generate the following
2239         // pattern:
2240         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2241         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2242                                         DAG.getConstant(32, DL, MVT::i64));
2243         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2244         Overflow =
2245             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2246                         DAG.getConstant(0, DL, MVT::i64),
2247                         UpperBits).getValue(1);
2248       }
2249       break;
2250     }
2251     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2252     // For the 64 bit multiply
2253     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2254     if (IsSigned) {
2255       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2256       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2257                                       DAG.getConstant(63, DL, MVT::i64));
2258       // It is important that LowerBits is last, otherwise the arithmetic
2259       // shift will not be folded into the compare (SUBS).
2260       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2261       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2262                      .getValue(1);
2263     } else {
2264       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2265       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2266       Overflow =
2267           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2268                       DAG.getConstant(0, DL, MVT::i64),
2269                       UpperBits).getValue(1);
2270     }
2271     break;
2272   }
2273   } // switch (...)
2274 
2275   if (Opc) {
2276     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2277 
2278     // Emit the AArch64 operation with overflow check.
2279     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2280     Overflow = Value.getValue(1);
2281   }
2282   return std::make_pair(Value, Overflow);
2283 }
2284 
2285 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2286                                              RTLIB::Libcall Call) const {
2287   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2288   MakeLibCallOptions CallOptions;
2289   return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first;
2290 }
2291 
2292 // Returns true if the given Op is the overflow flag result of an overflow
2293 // intrinsic operation.
2294 static bool isOverflowIntrOpRes(SDValue Op) {
2295   unsigned Opc = Op.getOpcode();
2296   return (Op.getResNo() == 1 &&
2297           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2298            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2299 }
2300 
2301 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2302   SDValue Sel = Op.getOperand(0);
2303   SDValue Other = Op.getOperand(1);
2304   SDLoc dl(Sel);
2305 
2306   // If the operand is an overflow checking operation, invert the condition
2307   // code and kill the Not operation. I.e., transform:
2308   // (xor (overflow_op_bool, 1))
2309   //   -->
2310   // (csel 1, 0, invert(cc), overflow_op_bool)
2311   // ... which later gets transformed to just a cset instruction with an
2312   // inverted condition code, rather than a cset + eor sequence.
2313   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2314     // Only lower legal XALUO ops.
2315     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2316       return SDValue();
2317 
2318     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2319     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2320     AArch64CC::CondCode CC;
2321     SDValue Value, Overflow;
2322     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2323     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2324     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2325                        CCVal, Overflow);
2326   }
2327   // If neither operand is a SELECT_CC, give up.
2328   if (Sel.getOpcode() != ISD::SELECT_CC)
2329     std::swap(Sel, Other);
2330   if (Sel.getOpcode() != ISD::SELECT_CC)
2331     return Op;
2332 
2333   // The folding we want to perform is:
2334   // (xor x, (select_cc a, b, cc, 0, -1) )
2335   //   -->
2336   // (csel x, (xor x, -1), cc ...)
2337   //
2338   // The latter will get matched to a CSINV instruction.
2339 
2340   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2341   SDValue LHS = Sel.getOperand(0);
2342   SDValue RHS = Sel.getOperand(1);
2343   SDValue TVal = Sel.getOperand(2);
2344   SDValue FVal = Sel.getOperand(3);
2345 
2346   // FIXME: This could be generalized to non-integer comparisons.
2347   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2348     return Op;
2349 
2350   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2351   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2352 
2353   // The values aren't constants, this isn't the pattern we're looking for.
2354   if (!CFVal || !CTVal)
2355     return Op;
2356 
2357   // We can commute the SELECT_CC by inverting the condition.  This
2358   // might be needed to make this fit into a CSINV pattern.
2359   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2360     std::swap(TVal, FVal);
2361     std::swap(CTVal, CFVal);
2362     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2363   }
2364 
2365   // If the constants line up, perform the transform!
2366   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2367     SDValue CCVal;
2368     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2369 
2370     FVal = Other;
2371     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2372                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2373 
2374     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2375                        CCVal, Cmp);
2376   }
2377 
2378   return Op;
2379 }
2380 
2381 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2382   EVT VT = Op.getValueType();
2383 
2384   // Let legalize expand this if it isn't a legal type yet.
2385   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2386     return SDValue();
2387 
2388   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2389 
2390   unsigned Opc;
2391   bool ExtraOp = false;
2392   switch (Op.getOpcode()) {
2393   default:
2394     llvm_unreachable("Invalid code");
2395   case ISD::ADDC:
2396     Opc = AArch64ISD::ADDS;
2397     break;
2398   case ISD::SUBC:
2399     Opc = AArch64ISD::SUBS;
2400     break;
2401   case ISD::ADDE:
2402     Opc = AArch64ISD::ADCS;
2403     ExtraOp = true;
2404     break;
2405   case ISD::SUBE:
2406     Opc = AArch64ISD::SBCS;
2407     ExtraOp = true;
2408     break;
2409   }
2410 
2411   if (!ExtraOp)
2412     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2413   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2414                      Op.getOperand(2));
2415 }
2416 
2417 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2418   // Let legalize expand this if it isn't a legal type yet.
2419   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2420     return SDValue();
2421 
2422   SDLoc dl(Op);
2423   AArch64CC::CondCode CC;
2424   // The actual operation that sets the overflow or carry flag.
2425   SDValue Value, Overflow;
2426   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2427 
2428   // We use 0 and 1 as false and true values.
2429   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2430   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2431 
2432   // We use an inverted condition, because the conditional select is inverted
2433   // too. This will allow it to be selected to a single instruction:
2434   // CSINC Wd, WZR, WZR, invert(cond).
2435   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2436   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2437                          CCVal, Overflow);
2438 
2439   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2440   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2441 }
2442 
2443 // Prefetch operands are:
2444 // 1: Address to prefetch
2445 // 2: bool isWrite
2446 // 3: int locality (0 = no locality ... 3 = extreme locality)
2447 // 4: bool isDataCache
2448 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2449   SDLoc DL(Op);
2450   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2451   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2452   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2453 
2454   bool IsStream = !Locality;
2455   // When the locality number is set
2456   if (Locality) {
2457     // The front-end should have filtered out the out-of-range values
2458     assert(Locality <= 3 && "Prefetch locality out-of-range");
2459     // The locality degree is the opposite of the cache speed.
2460     // Put the number the other way around.
2461     // The encoding starts at 0 for level 1
2462     Locality = 3 - Locality;
2463   }
2464 
2465   // built the mask value encoding the expected behavior.
2466   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2467                    (!IsData << 3) |     // IsDataCache bit
2468                    (Locality << 1) |    // Cache level bits
2469                    (unsigned)IsStream;  // Stream bit
2470   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2471                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2472 }
2473 
2474 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2475                                               SelectionDAG &DAG) const {
2476   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2477 
2478   RTLIB::Libcall LC;
2479   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2480 
2481   return LowerF128Call(Op, DAG, LC);
2482 }
2483 
2484 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2485                                              SelectionDAG &DAG) const {
2486   if (Op.getOperand(0).getValueType() != MVT::f128) {
2487     // It's legal except when f128 is involved
2488     return Op;
2489   }
2490 
2491   RTLIB::Libcall LC;
2492   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2493 
2494   // FP_ROUND node has a second operand indicating whether it is known to be
2495   // precise. That doesn't take part in the LibCall so we can't directly use
2496   // LowerF128Call.
2497   SDValue SrcVal = Op.getOperand(0);
2498   MakeLibCallOptions CallOptions;
2499   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions,
2500                      SDLoc(Op)).first;
2501 }
2502 
2503 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2504                                                     SelectionDAG &DAG) const {
2505   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2506   // Any additional optimization in this function should be recorded
2507   // in the cost tables.
2508   EVT InVT = Op.getOperand(0).getValueType();
2509   EVT VT = Op.getValueType();
2510   unsigned NumElts = InVT.getVectorNumElements();
2511 
2512   // f16 conversions are promoted to f32 when full fp16 is not supported.
2513   if (InVT.getVectorElementType() == MVT::f16 &&
2514       !Subtarget->hasFullFP16()) {
2515     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2516     SDLoc dl(Op);
2517     return DAG.getNode(
2518         Op.getOpcode(), dl, Op.getValueType(),
2519         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2520   }
2521 
2522   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2523     SDLoc dl(Op);
2524     SDValue Cv =
2525         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2526                     Op.getOperand(0));
2527     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2528   }
2529 
2530   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2531     SDLoc dl(Op);
2532     MVT ExtVT =
2533         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2534                          VT.getVectorNumElements());
2535     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2536     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2537   }
2538 
2539   // Type changing conversions are illegal.
2540   return Op;
2541 }
2542 
2543 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2544                                               SelectionDAG &DAG) const {
2545   if (Op.getOperand(0).getValueType().isVector())
2546     return LowerVectorFP_TO_INT(Op, DAG);
2547 
2548   // f16 conversions are promoted to f32 when full fp16 is not supported.
2549   if (Op.getOperand(0).getValueType() == MVT::f16 &&
2550       !Subtarget->hasFullFP16()) {
2551     SDLoc dl(Op);
2552     return DAG.getNode(
2553         Op.getOpcode(), dl, Op.getValueType(),
2554         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2555   }
2556 
2557   if (Op.getOperand(0).getValueType() != MVT::f128) {
2558     // It's legal except when f128 is involved
2559     return Op;
2560   }
2561 
2562   RTLIB::Libcall LC;
2563   if (Op.getOpcode() == ISD::FP_TO_SINT)
2564     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2565   else
2566     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2567 
2568   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2569   MakeLibCallOptions CallOptions;
2570   return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first;
2571 }
2572 
2573 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2574   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2575   // Any additional optimization in this function should be recorded
2576   // in the cost tables.
2577   EVT VT = Op.getValueType();
2578   SDLoc dl(Op);
2579   SDValue In = Op.getOperand(0);
2580   EVT InVT = In.getValueType();
2581 
2582   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2583     MVT CastVT =
2584         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2585                          InVT.getVectorNumElements());
2586     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2587     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2588   }
2589 
2590   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2591     unsigned CastOpc =
2592         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2593     EVT CastVT = VT.changeVectorElementTypeToInteger();
2594     In = DAG.getNode(CastOpc, dl, CastVT, In);
2595     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2596   }
2597 
2598   return Op;
2599 }
2600 
2601 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2602                                             SelectionDAG &DAG) const {
2603   if (Op.getValueType().isVector())
2604     return LowerVectorINT_TO_FP(Op, DAG);
2605 
2606   // f16 conversions are promoted to f32 when full fp16 is not supported.
2607   if (Op.getValueType() == MVT::f16 &&
2608       !Subtarget->hasFullFP16()) {
2609     SDLoc dl(Op);
2610     return DAG.getNode(
2611         ISD::FP_ROUND, dl, MVT::f16,
2612         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2613         DAG.getIntPtrConstant(0, dl));
2614   }
2615 
2616   // i128 conversions are libcalls.
2617   if (Op.getOperand(0).getValueType() == MVT::i128)
2618     return SDValue();
2619 
2620   // Other conversions are legal, unless it's to the completely software-based
2621   // fp128.
2622   if (Op.getValueType() != MVT::f128)
2623     return Op;
2624 
2625   RTLIB::Libcall LC;
2626   if (Op.getOpcode() == ISD::SINT_TO_FP)
2627     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2628   else
2629     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2630 
2631   return LowerF128Call(Op, DAG, LC);
2632 }
2633 
2634 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2635                                             SelectionDAG &DAG) const {
2636   // For iOS, we want to call an alternative entry point: __sincos_stret,
2637   // which returns the values in two S / D registers.
2638   SDLoc dl(Op);
2639   SDValue Arg = Op.getOperand(0);
2640   EVT ArgVT = Arg.getValueType();
2641   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2642 
2643   ArgListTy Args;
2644   ArgListEntry Entry;
2645 
2646   Entry.Node = Arg;
2647   Entry.Ty = ArgTy;
2648   Entry.IsSExt = false;
2649   Entry.IsZExt = false;
2650   Args.push_back(Entry);
2651 
2652   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2653                                         : RTLIB::SINCOS_STRET_F32;
2654   const char *LibcallName = getLibcallName(LC);
2655   SDValue Callee =
2656       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2657 
2658   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2659   TargetLowering::CallLoweringInfo CLI(DAG);
2660   CLI.setDebugLoc(dl)
2661       .setChain(DAG.getEntryNode())
2662       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2663 
2664   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2665   return CallResult.first;
2666 }
2667 
2668 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2669   if (Op.getValueType() != MVT::f16)
2670     return SDValue();
2671 
2672   assert(Op.getOperand(0).getValueType() == MVT::i16);
2673   SDLoc DL(Op);
2674 
2675   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2676   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2677   return SDValue(
2678       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2679                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2680       0);
2681 }
2682 
2683 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2684   if (OrigVT.getSizeInBits() >= 64)
2685     return OrigVT;
2686 
2687   assert(OrigVT.isSimple() && "Expecting a simple value type");
2688 
2689   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2690   switch (OrigSimpleTy) {
2691   default: llvm_unreachable("Unexpected Vector Type");
2692   case MVT::v2i8:
2693   case MVT::v2i16:
2694      return MVT::v2i32;
2695   case MVT::v4i8:
2696     return  MVT::v4i16;
2697   }
2698 }
2699 
2700 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2701                                                  const EVT &OrigTy,
2702                                                  const EVT &ExtTy,
2703                                                  unsigned ExtOpcode) {
2704   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2705   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2706   // 64-bits we need to insert a new extension so that it will be 64-bits.
2707   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2708   if (OrigTy.getSizeInBits() >= 64)
2709     return N;
2710 
2711   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2712   EVT NewVT = getExtensionTo64Bits(OrigTy);
2713 
2714   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2715 }
2716 
2717 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2718                                    bool isSigned) {
2719   EVT VT = N->getValueType(0);
2720 
2721   if (N->getOpcode() != ISD::BUILD_VECTOR)
2722     return false;
2723 
2724   for (const SDValue &Elt : N->op_values()) {
2725     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2726       unsigned EltSize = VT.getScalarSizeInBits();
2727       unsigned HalfSize = EltSize / 2;
2728       if (isSigned) {
2729         if (!isIntN(HalfSize, C->getSExtValue()))
2730           return false;
2731       } else {
2732         if (!isUIntN(HalfSize, C->getZExtValue()))
2733           return false;
2734       }
2735       continue;
2736     }
2737     return false;
2738   }
2739 
2740   return true;
2741 }
2742 
2743 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2744   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2745     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2746                                              N->getOperand(0)->getValueType(0),
2747                                              N->getValueType(0),
2748                                              N->getOpcode());
2749 
2750   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2751   EVT VT = N->getValueType(0);
2752   SDLoc dl(N);
2753   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2754   unsigned NumElts = VT.getVectorNumElements();
2755   MVT TruncVT = MVT::getIntegerVT(EltSize);
2756   SmallVector<SDValue, 8> Ops;
2757   for (unsigned i = 0; i != NumElts; ++i) {
2758     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2759     const APInt &CInt = C->getAPIntValue();
2760     // Element types smaller than 32 bits are not legal, so use i32 elements.
2761     // The values are implicitly truncated so sext vs. zext doesn't matter.
2762     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2763   }
2764   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2765 }
2766 
2767 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2768   return N->getOpcode() == ISD::SIGN_EXTEND ||
2769          isExtendedBUILD_VECTOR(N, DAG, true);
2770 }
2771 
2772 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2773   return N->getOpcode() == ISD::ZERO_EXTEND ||
2774          isExtendedBUILD_VECTOR(N, DAG, false);
2775 }
2776 
2777 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2778   unsigned Opcode = N->getOpcode();
2779   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2780     SDNode *N0 = N->getOperand(0).getNode();
2781     SDNode *N1 = N->getOperand(1).getNode();
2782     return N0->hasOneUse() && N1->hasOneUse() &&
2783       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2784   }
2785   return false;
2786 }
2787 
2788 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2789   unsigned Opcode = N->getOpcode();
2790   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2791     SDNode *N0 = N->getOperand(0).getNode();
2792     SDNode *N1 = N->getOperand(1).getNode();
2793     return N0->hasOneUse() && N1->hasOneUse() &&
2794       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2795   }
2796   return false;
2797 }
2798 
2799 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2800                                                 SelectionDAG &DAG) const {
2801   // The rounding mode is in bits 23:22 of the FPSCR.
2802   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2803   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2804   // so that the shift + and get folded into a bitfield extract.
2805   SDLoc dl(Op);
2806 
2807   SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2808                                 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2809                                                 MVT::i64));
2810   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2811   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2812                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2813   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2814                               DAG.getConstant(22, dl, MVT::i32));
2815   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2816                      DAG.getConstant(3, dl, MVT::i32));
2817 }
2818 
2819 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2820   // Multiplications are only custom-lowered for 128-bit vectors so that
2821   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2822   EVT VT = Op.getValueType();
2823   assert(VT.is128BitVector() && VT.isInteger() &&
2824          "unexpected type for custom-lowering ISD::MUL");
2825   SDNode *N0 = Op.getOperand(0).getNode();
2826   SDNode *N1 = Op.getOperand(1).getNode();
2827   unsigned NewOpc = 0;
2828   bool isMLA = false;
2829   bool isN0SExt = isSignExtended(N0, DAG);
2830   bool isN1SExt = isSignExtended(N1, DAG);
2831   if (isN0SExt && isN1SExt)
2832     NewOpc = AArch64ISD::SMULL;
2833   else {
2834     bool isN0ZExt = isZeroExtended(N0, DAG);
2835     bool isN1ZExt = isZeroExtended(N1, DAG);
2836     if (isN0ZExt && isN1ZExt)
2837       NewOpc = AArch64ISD::UMULL;
2838     else if (isN1SExt || isN1ZExt) {
2839       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2840       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2841       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2842         NewOpc = AArch64ISD::SMULL;
2843         isMLA = true;
2844       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2845         NewOpc =  AArch64ISD::UMULL;
2846         isMLA = true;
2847       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2848         std::swap(N0, N1);
2849         NewOpc =  AArch64ISD::UMULL;
2850         isMLA = true;
2851       }
2852     }
2853 
2854     if (!NewOpc) {
2855       if (VT == MVT::v2i64)
2856         // Fall through to expand this.  It is not legal.
2857         return SDValue();
2858       else
2859         // Other vector multiplications are legal.
2860         return Op;
2861     }
2862   }
2863 
2864   // Legalize to a S/UMULL instruction
2865   SDLoc DL(Op);
2866   SDValue Op0;
2867   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2868   if (!isMLA) {
2869     Op0 = skipExtensionForVectorMULL(N0, DAG);
2870     assert(Op0.getValueType().is64BitVector() &&
2871            Op1.getValueType().is64BitVector() &&
2872            "unexpected types for extended operands to VMULL");
2873     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2874   }
2875   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2876   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2877   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2878   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2879   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2880   EVT Op1VT = Op1.getValueType();
2881   return DAG.getNode(N0->getOpcode(), DL, VT,
2882                      DAG.getNode(NewOpc, DL, VT,
2883                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2884                      DAG.getNode(NewOpc, DL, VT,
2885                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2886 }
2887 
2888 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2889                                                      SelectionDAG &DAG) const {
2890   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2891   SDLoc dl(Op);
2892   switch (IntNo) {
2893   default: return SDValue();    // Don't custom lower most intrinsics.
2894   case Intrinsic::thread_pointer: {
2895     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2896     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2897   }
2898   case Intrinsic::aarch64_neon_abs: {
2899     EVT Ty = Op.getValueType();
2900     if (Ty == MVT::i64) {
2901       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2902                                    Op.getOperand(1));
2903       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2904       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2905     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2906       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2907     } else {
2908       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2909     }
2910   }
2911   case Intrinsic::aarch64_neon_smax:
2912     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2913                        Op.getOperand(1), Op.getOperand(2));
2914   case Intrinsic::aarch64_neon_umax:
2915     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2916                        Op.getOperand(1), Op.getOperand(2));
2917   case Intrinsic::aarch64_neon_smin:
2918     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2919                        Op.getOperand(1), Op.getOperand(2));
2920   case Intrinsic::aarch64_neon_umin:
2921     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2922                        Op.getOperand(1), Op.getOperand(2));
2923 
2924   case Intrinsic::aarch64_sve_sunpkhi:
2925     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
2926                        Op.getOperand(1));
2927   case Intrinsic::aarch64_sve_sunpklo:
2928     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
2929                        Op.getOperand(1));
2930   case Intrinsic::aarch64_sve_uunpkhi:
2931     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
2932                        Op.getOperand(1));
2933   case Intrinsic::aarch64_sve_uunpklo:
2934     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
2935                        Op.getOperand(1));
2936   case Intrinsic::aarch64_sve_clasta_n:
2937     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
2938                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2939   case Intrinsic::aarch64_sve_clastb_n:
2940     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
2941                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2942   case Intrinsic::aarch64_sve_lasta:
2943     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
2944                        Op.getOperand(1), Op.getOperand(2));
2945   case Intrinsic::aarch64_sve_lastb:
2946     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
2947                        Op.getOperand(1), Op.getOperand(2));
2948   case Intrinsic::aarch64_sve_rev:
2949     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
2950                        Op.getOperand(1));
2951   case Intrinsic::aarch64_sve_tbl:
2952     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
2953                        Op.getOperand(1), Op.getOperand(2));
2954   case Intrinsic::aarch64_sve_trn1:
2955     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
2956                        Op.getOperand(1), Op.getOperand(2));
2957   case Intrinsic::aarch64_sve_trn2:
2958     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
2959                        Op.getOperand(1), Op.getOperand(2));
2960   case Intrinsic::aarch64_sve_uzp1:
2961     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
2962                        Op.getOperand(1), Op.getOperand(2));
2963   case Intrinsic::aarch64_sve_uzp2:
2964     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
2965                        Op.getOperand(1), Op.getOperand(2));
2966   case Intrinsic::aarch64_sve_zip1:
2967     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
2968                        Op.getOperand(1), Op.getOperand(2));
2969   case Intrinsic::aarch64_sve_zip2:
2970     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
2971                        Op.getOperand(1), Op.getOperand(2));
2972   case Intrinsic::aarch64_sve_ptrue:
2973     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
2974                        Op.getOperand(1));
2975 
2976   case Intrinsic::aarch64_sve_insr: {
2977     SDValue Scalar = Op.getOperand(2);
2978     EVT ScalarTy = Scalar.getValueType();
2979     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
2980       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
2981 
2982     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
2983                        Op.getOperand(1), Scalar);
2984   }
2985 
2986   case Intrinsic::localaddress: {
2987     const auto &MF = DAG.getMachineFunction();
2988     const auto *RegInfo = Subtarget->getRegisterInfo();
2989     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
2990     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2991                               Op.getSimpleValueType());
2992   }
2993 
2994   case Intrinsic::eh_recoverfp: {
2995     // FIXME: This needs to be implemented to correctly handle highly aligned
2996     // stack objects. For now we simply return the incoming FP. Refer D53541
2997     // for more details.
2998     SDValue FnOp = Op.getOperand(1);
2999     SDValue IncomingFPOp = Op.getOperand(2);
3000     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3001     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3002     if (!Fn)
3003       report_fatal_error(
3004           "llvm.eh.recoverfp must take a function as the first argument");
3005     return IncomingFPOp;
3006   }
3007   }
3008 }
3009 
3010 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3011   return ExtVal.getValueType().isScalableVector();
3012 }
3013 
3014 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3015 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3016                                         EVT VT, EVT MemVT,
3017                                         SelectionDAG &DAG) {
3018   assert(VT.isVector() && "VT should be a vector type");
3019   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3020 
3021   SDValue Value = ST->getValue();
3022 
3023   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3024   // the word lane which represent the v4i8 subvector.  It optimizes the store
3025   // to:
3026   //
3027   //   xtn  v0.8b, v0.8h
3028   //   str  s0, [x0]
3029 
3030   SDValue Undef = DAG.getUNDEF(MVT::i16);
3031   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3032                                         {Undef, Undef, Undef, Undef});
3033 
3034   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3035                                  Value, UndefVec);
3036   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3037 
3038   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3039   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3040                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3041 
3042   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3043                       ST->getBasePtr(), ST->getMemOperand());
3044 }
3045 
3046 // Custom lowering for any store, vector or scalar and/or default or with
3047 // a truncate operations.  Currently only custom lower truncate operation
3048 // from vector v4i16 to v4i8 or volatile stores of i128.
3049 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3050                                           SelectionDAG &DAG) const {
3051   SDLoc Dl(Op);
3052   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3053   assert (StoreNode && "Can only custom lower store nodes");
3054 
3055   SDValue Value = StoreNode->getValue();
3056 
3057   EVT VT = Value.getValueType();
3058   EVT MemVT = StoreNode->getMemoryVT();
3059 
3060   if (VT.isVector()) {
3061     unsigned AS = StoreNode->getAddressSpace();
3062     unsigned Align = StoreNode->getAlignment();
3063     if (Align < MemVT.getStoreSize() &&
3064         !allowsMisalignedMemoryAccesses(MemVT, AS, Align,
3065                                         StoreNode->getMemOperand()->getFlags(),
3066                                         nullptr)) {
3067       return scalarizeVectorStore(StoreNode, DAG);
3068     }
3069 
3070     if (StoreNode->isTruncatingStore()) {
3071       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3072     }
3073   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3074     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3075     SDValue Lo =
3076         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3077                     DAG.getConstant(0, Dl, MVT::i64));
3078     SDValue Hi =
3079         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3080                     DAG.getConstant(1, Dl, MVT::i64));
3081     SDValue Result = DAG.getMemIntrinsicNode(
3082         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3083         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3084         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3085     return Result;
3086   }
3087 
3088   return SDValue();
3089 }
3090 
3091 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3092                                               SelectionDAG &DAG) const {
3093   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3094   LLVM_DEBUG(Op.dump());
3095 
3096   switch (Op.getOpcode()) {
3097   default:
3098     llvm_unreachable("unimplemented operand");
3099     return SDValue();
3100   case ISD::BITCAST:
3101     return LowerBITCAST(Op, DAG);
3102   case ISD::GlobalAddress:
3103     return LowerGlobalAddress(Op, DAG);
3104   case ISD::GlobalTLSAddress:
3105     return LowerGlobalTLSAddress(Op, DAG);
3106   case ISD::SETCC:
3107     return LowerSETCC(Op, DAG);
3108   case ISD::BR_CC:
3109     return LowerBR_CC(Op, DAG);
3110   case ISD::SELECT:
3111     return LowerSELECT(Op, DAG);
3112   case ISD::SELECT_CC:
3113     return LowerSELECT_CC(Op, DAG);
3114   case ISD::JumpTable:
3115     return LowerJumpTable(Op, DAG);
3116   case ISD::BR_JT:
3117     return LowerBR_JT(Op, DAG);
3118   case ISD::ConstantPool:
3119     return LowerConstantPool(Op, DAG);
3120   case ISD::BlockAddress:
3121     return LowerBlockAddress(Op, DAG);
3122   case ISD::VASTART:
3123     return LowerVASTART(Op, DAG);
3124   case ISD::VACOPY:
3125     return LowerVACOPY(Op, DAG);
3126   case ISD::VAARG:
3127     return LowerVAARG(Op, DAG);
3128   case ISD::ADDC:
3129   case ISD::ADDE:
3130   case ISD::SUBC:
3131   case ISD::SUBE:
3132     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3133   case ISD::SADDO:
3134   case ISD::UADDO:
3135   case ISD::SSUBO:
3136   case ISD::USUBO:
3137   case ISD::SMULO:
3138   case ISD::UMULO:
3139     return LowerXALUO(Op, DAG);
3140   case ISD::FADD:
3141     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3142   case ISD::FSUB:
3143     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3144   case ISD::FMUL:
3145     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3146   case ISD::FDIV:
3147     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3148   case ISD::FP_ROUND:
3149     return LowerFP_ROUND(Op, DAG);
3150   case ISD::FP_EXTEND:
3151     return LowerFP_EXTEND(Op, DAG);
3152   case ISD::FRAMEADDR:
3153     return LowerFRAMEADDR(Op, DAG);
3154   case ISD::SPONENTRY:
3155     return LowerSPONENTRY(Op, DAG);
3156   case ISD::RETURNADDR:
3157     return LowerRETURNADDR(Op, DAG);
3158   case ISD::ADDROFRETURNADDR:
3159     return LowerADDROFRETURNADDR(Op, DAG);
3160   case ISD::INSERT_VECTOR_ELT:
3161     return LowerINSERT_VECTOR_ELT(Op, DAG);
3162   case ISD::EXTRACT_VECTOR_ELT:
3163     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3164   case ISD::BUILD_VECTOR:
3165     return LowerBUILD_VECTOR(Op, DAG);
3166   case ISD::VECTOR_SHUFFLE:
3167     return LowerVECTOR_SHUFFLE(Op, DAG);
3168   case ISD::SPLAT_VECTOR:
3169     return LowerSPLAT_VECTOR(Op, DAG);
3170   case ISD::EXTRACT_SUBVECTOR:
3171     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3172   case ISD::SRA:
3173   case ISD::SRL:
3174   case ISD::SHL:
3175     return LowerVectorSRA_SRL_SHL(Op, DAG);
3176   case ISD::SHL_PARTS:
3177     return LowerShiftLeftParts(Op, DAG);
3178   case ISD::SRL_PARTS:
3179   case ISD::SRA_PARTS:
3180     return LowerShiftRightParts(Op, DAG);
3181   case ISD::CTPOP:
3182     return LowerCTPOP(Op, DAG);
3183   case ISD::FCOPYSIGN:
3184     return LowerFCOPYSIGN(Op, DAG);
3185   case ISD::OR:
3186     return LowerVectorOR(Op, DAG);
3187   case ISD::XOR:
3188     return LowerXOR(Op, DAG);
3189   case ISD::PREFETCH:
3190     return LowerPREFETCH(Op, DAG);
3191   case ISD::SINT_TO_FP:
3192   case ISD::UINT_TO_FP:
3193     return LowerINT_TO_FP(Op, DAG);
3194   case ISD::FP_TO_SINT:
3195   case ISD::FP_TO_UINT:
3196     return LowerFP_TO_INT(Op, DAG);
3197   case ISD::FSINCOS:
3198     return LowerFSINCOS(Op, DAG);
3199   case ISD::FLT_ROUNDS_:
3200     return LowerFLT_ROUNDS_(Op, DAG);
3201   case ISD::MUL:
3202     return LowerMUL(Op, DAG);
3203   case ISD::INTRINSIC_WO_CHAIN:
3204     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3205   case ISD::STORE:
3206     return LowerSTORE(Op, DAG);
3207   case ISD::VECREDUCE_ADD:
3208   case ISD::VECREDUCE_SMAX:
3209   case ISD::VECREDUCE_SMIN:
3210   case ISD::VECREDUCE_UMAX:
3211   case ISD::VECREDUCE_UMIN:
3212   case ISD::VECREDUCE_FMAX:
3213   case ISD::VECREDUCE_FMIN:
3214     return LowerVECREDUCE(Op, DAG);
3215   case ISD::ATOMIC_LOAD_SUB:
3216     return LowerATOMIC_LOAD_SUB(Op, DAG);
3217   case ISD::ATOMIC_LOAD_AND:
3218     return LowerATOMIC_LOAD_AND(Op, DAG);
3219   case ISD::DYNAMIC_STACKALLOC:
3220     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3221   }
3222 }
3223 
3224 //===----------------------------------------------------------------------===//
3225 //                      Calling Convention Implementation
3226 //===----------------------------------------------------------------------===//
3227 
3228 /// Selects the correct CCAssignFn for a given CallingConvention value.
3229 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3230                                                      bool IsVarArg) const {
3231   switch (CC) {
3232   default:
3233     report_fatal_error("Unsupported calling convention.");
3234   case CallingConv::AArch64_SVE_VectorCall:
3235     // Calling SVE functions is currently not yet supported.
3236     report_fatal_error("Unsupported calling convention.");
3237   case CallingConv::WebKit_JS:
3238     return CC_AArch64_WebKit_JS;
3239   case CallingConv::GHC:
3240     return CC_AArch64_GHC;
3241   case CallingConv::C:
3242   case CallingConv::Fast:
3243   case CallingConv::PreserveMost:
3244   case CallingConv::CXX_FAST_TLS:
3245   case CallingConv::Swift:
3246     if (Subtarget->isTargetWindows() && IsVarArg)
3247       return CC_AArch64_Win64_VarArg;
3248     if (!Subtarget->isTargetDarwin())
3249       return CC_AArch64_AAPCS;
3250     if (!IsVarArg)
3251       return CC_AArch64_DarwinPCS;
3252     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3253                                       : CC_AArch64_DarwinPCS_VarArg;
3254    case CallingConv::Win64:
3255     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3256    case CallingConv::CFGuard_Check:
3257      return CC_AArch64_Win64_CFGuard_Check;
3258    case CallingConv::AArch64_VectorCall:
3259      return CC_AArch64_AAPCS;
3260   }
3261 }
3262 
3263 CCAssignFn *
3264 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3265   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3266                                       : RetCC_AArch64_AAPCS;
3267 }
3268 
3269 SDValue AArch64TargetLowering::LowerFormalArguments(
3270     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3271     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3272     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3273   MachineFunction &MF = DAG.getMachineFunction();
3274   MachineFrameInfo &MFI = MF.getFrameInfo();
3275   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3276 
3277   // Assign locations to all of the incoming arguments.
3278   SmallVector<CCValAssign, 16> ArgLocs;
3279   DenseMap<unsigned, SDValue> CopiedRegs;
3280   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3281                  *DAG.getContext());
3282 
3283   // At this point, Ins[].VT may already be promoted to i32. To correctly
3284   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3285   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3286   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3287   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3288   // LocVT.
3289   unsigned NumArgs = Ins.size();
3290   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3291   unsigned CurArgIdx = 0;
3292   for (unsigned i = 0; i != NumArgs; ++i) {
3293     MVT ValVT = Ins[i].VT;
3294     if (Ins[i].isOrigArg()) {
3295       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3296       CurArgIdx = Ins[i].getOrigArgIndex();
3297 
3298       // Get type of the original argument.
3299       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3300                                   /*AllowUnknown*/ true);
3301       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3302       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3303       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3304         ValVT = MVT::i8;
3305       else if (ActualMVT == MVT::i16)
3306         ValVT = MVT::i16;
3307     }
3308     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3309     bool Res =
3310         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3311     assert(!Res && "Call operand has unhandled type");
3312     (void)Res;
3313   }
3314   assert(ArgLocs.size() == Ins.size());
3315   SmallVector<SDValue, 16> ArgValues;
3316   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3317     CCValAssign &VA = ArgLocs[i];
3318 
3319     if (Ins[i].Flags.isByVal()) {
3320       // Byval is used for HFAs in the PCS, but the system should work in a
3321       // non-compliant manner for larger structs.
3322       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3323       int Size = Ins[i].Flags.getByValSize();
3324       unsigned NumRegs = (Size + 7) / 8;
3325 
3326       // FIXME: This works on big-endian for composite byvals, which are the common
3327       // case. It should also work for fundamental types too.
3328       unsigned FrameIdx =
3329         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3330       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3331       InVals.push_back(FrameIdxN);
3332 
3333       continue;
3334     }
3335 
3336     SDValue ArgValue;
3337     if (VA.isRegLoc()) {
3338       // Arguments stored in registers.
3339       EVT RegVT = VA.getLocVT();
3340       const TargetRegisterClass *RC;
3341 
3342       if (RegVT == MVT::i32)
3343         RC = &AArch64::GPR32RegClass;
3344       else if (RegVT == MVT::i64)
3345         RC = &AArch64::GPR64RegClass;
3346       else if (RegVT == MVT::f16)
3347         RC = &AArch64::FPR16RegClass;
3348       else if (RegVT == MVT::f32)
3349         RC = &AArch64::FPR32RegClass;
3350       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3351         RC = &AArch64::FPR64RegClass;
3352       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3353         RC = &AArch64::FPR128RegClass;
3354       else if (RegVT.isScalableVector() &&
3355                RegVT.getVectorElementType() == MVT::i1)
3356         RC = &AArch64::PPRRegClass;
3357       else if (RegVT.isScalableVector())
3358         RC = &AArch64::ZPRRegClass;
3359       else
3360         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3361 
3362       // Transform the arguments in physical registers into virtual ones.
3363       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3364       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3365 
3366       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3367       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3368       // truncate to the right size.
3369       switch (VA.getLocInfo()) {
3370       default:
3371         llvm_unreachable("Unknown loc info!");
3372       case CCValAssign::Full:
3373         break;
3374       case CCValAssign::Indirect:
3375         assert(VA.getValVT().isScalableVector() &&
3376                "Only scalable vectors can be passed indirectly");
3377         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3378       case CCValAssign::BCvt:
3379         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3380         break;
3381       case CCValAssign::AExt:
3382       case CCValAssign::SExt:
3383       case CCValAssign::ZExt:
3384         break;
3385       case CCValAssign::AExtUpper:
3386         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3387                                DAG.getConstant(32, DL, RegVT));
3388         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3389         break;
3390       }
3391     } else { // VA.isRegLoc()
3392       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3393       unsigned ArgOffset = VA.getLocMemOffset();
3394       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3395 
3396       uint32_t BEAlign = 0;
3397       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3398           !Ins[i].Flags.isInConsecutiveRegs())
3399         BEAlign = 8 - ArgSize;
3400 
3401       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3402 
3403       // Create load nodes to retrieve arguments from the stack.
3404       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3405 
3406       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3407       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3408       MVT MemVT = VA.getValVT();
3409 
3410       switch (VA.getLocInfo()) {
3411       default:
3412         break;
3413       case CCValAssign::Trunc:
3414       case CCValAssign::BCvt:
3415         MemVT = VA.getLocVT();
3416         break;
3417       case CCValAssign::Indirect:
3418         assert(VA.getValVT().isScalableVector() &&
3419                "Only scalable vectors can be passed indirectly");
3420         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3421       case CCValAssign::SExt:
3422         ExtType = ISD::SEXTLOAD;
3423         break;
3424       case CCValAssign::ZExt:
3425         ExtType = ISD::ZEXTLOAD;
3426         break;
3427       case CCValAssign::AExt:
3428         ExtType = ISD::EXTLOAD;
3429         break;
3430       }
3431 
3432       ArgValue = DAG.getExtLoad(
3433           ExtType, DL, VA.getLocVT(), Chain, FIN,
3434           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3435           MemVT);
3436 
3437     }
3438     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3439       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3440                              ArgValue, DAG.getValueType(MVT::i32));
3441     InVals.push_back(ArgValue);
3442   }
3443 
3444   // varargs
3445   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3446   if (isVarArg) {
3447     if (!Subtarget->isTargetDarwin() || IsWin64) {
3448       // The AAPCS variadic function ABI is identical to the non-variadic
3449       // one. As a result there may be more arguments in registers and we should
3450       // save them for future reference.
3451       // Win64 variadic functions also pass arguments in registers, but all float
3452       // arguments are passed in integer registers.
3453       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3454     }
3455 
3456     // This will point to the next argument passed via stack.
3457     unsigned StackOffset = CCInfo.getNextStackOffset();
3458     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3459     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3460     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3461 
3462     if (MFI.hasMustTailInVarArgFunc()) {
3463       SmallVector<MVT, 2> RegParmTypes;
3464       RegParmTypes.push_back(MVT::i64);
3465       RegParmTypes.push_back(MVT::f128);
3466       // Compute the set of forwarded registers. The rest are scratch.
3467       SmallVectorImpl<ForwardedRegister> &Forwards =
3468                                        FuncInfo->getForwardedMustTailRegParms();
3469       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3470                                                CC_AArch64_AAPCS);
3471 
3472       // Conservatively forward X8, since it might be used for aggregate return.
3473       if (!CCInfo.isAllocated(AArch64::X8)) {
3474         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3475         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3476       }
3477     }
3478   }
3479 
3480   // On Windows, InReg pointers must be returned, so record the pointer in a
3481   // virtual register at the start of the function so it can be returned in the
3482   // epilogue.
3483   if (IsWin64) {
3484     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3485       if (Ins[I].Flags.isInReg()) {
3486         assert(!FuncInfo->getSRetReturnReg());
3487 
3488         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3489         Register Reg =
3490             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3491         FuncInfo->setSRetReturnReg(Reg);
3492 
3493         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3494         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3495         break;
3496       }
3497     }
3498   }
3499 
3500   unsigned StackArgSize = CCInfo.getNextStackOffset();
3501   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3502   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3503     // This is a non-standard ABI so by fiat I say we're allowed to make full
3504     // use of the stack area to be popped, which must be aligned to 16 bytes in
3505     // any case:
3506     StackArgSize = alignTo(StackArgSize, 16);
3507 
3508     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3509     // a multiple of 16.
3510     FuncInfo->setArgumentStackToRestore(StackArgSize);
3511 
3512     // This realignment carries over to the available bytes below. Our own
3513     // callers will guarantee the space is free by giving an aligned value to
3514     // CALLSEQ_START.
3515   }
3516   // Even if we're not expected to free up the space, it's useful to know how
3517   // much is there while considering tail calls (because we can reuse it).
3518   FuncInfo->setBytesInStackArgArea(StackArgSize);
3519 
3520   if (Subtarget->hasCustomCallingConv())
3521     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3522 
3523   return Chain;
3524 }
3525 
3526 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3527                                                 SelectionDAG &DAG,
3528                                                 const SDLoc &DL,
3529                                                 SDValue &Chain) const {
3530   MachineFunction &MF = DAG.getMachineFunction();
3531   MachineFrameInfo &MFI = MF.getFrameInfo();
3532   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3533   auto PtrVT = getPointerTy(DAG.getDataLayout());
3534   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3535 
3536   SmallVector<SDValue, 8> MemOps;
3537 
3538   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3539                                           AArch64::X3, AArch64::X4, AArch64::X5,
3540                                           AArch64::X6, AArch64::X7 };
3541   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3542   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3543 
3544   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3545   int GPRIdx = 0;
3546   if (GPRSaveSize != 0) {
3547     if (IsWin64) {
3548       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3549       if (GPRSaveSize & 15)
3550         // The extra size here, if triggered, will always be 8.
3551         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3552     } else
3553       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3554 
3555     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3556 
3557     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3558       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3559       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3560       SDValue Store = DAG.getStore(
3561           Val.getValue(1), DL, Val, FIN,
3562           IsWin64
3563               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3564                                                   GPRIdx,
3565                                                   (i - FirstVariadicGPR) * 8)
3566               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3567       MemOps.push_back(Store);
3568       FIN =
3569           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3570     }
3571   }
3572   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3573   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3574 
3575   if (Subtarget->hasFPARMv8() && !IsWin64) {
3576     static const MCPhysReg FPRArgRegs[] = {
3577         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3578         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3579     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3580     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3581 
3582     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3583     int FPRIdx = 0;
3584     if (FPRSaveSize != 0) {
3585       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3586 
3587       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3588 
3589       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3590         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3591         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3592 
3593         SDValue Store = DAG.getStore(
3594             Val.getValue(1), DL, Val, FIN,
3595             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3596         MemOps.push_back(Store);
3597         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3598                           DAG.getConstant(16, DL, PtrVT));
3599       }
3600     }
3601     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3602     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3603   }
3604 
3605   if (!MemOps.empty()) {
3606     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3607   }
3608 }
3609 
3610 /// LowerCallResult - Lower the result values of a call into the
3611 /// appropriate copies out of appropriate physical registers.
3612 SDValue AArch64TargetLowering::LowerCallResult(
3613     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3614     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3615     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3616     SDValue ThisVal) const {
3617   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3618                           ? RetCC_AArch64_WebKit_JS
3619                           : RetCC_AArch64_AAPCS;
3620   // Assign locations to each value returned by this call.
3621   SmallVector<CCValAssign, 16> RVLocs;
3622   DenseMap<unsigned, SDValue> CopiedRegs;
3623   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3624                  *DAG.getContext());
3625   CCInfo.AnalyzeCallResult(Ins, RetCC);
3626 
3627   // Copy all of the result registers out of their specified physreg.
3628   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3629     CCValAssign VA = RVLocs[i];
3630 
3631     // Pass 'this' value directly from the argument to return value, to avoid
3632     // reg unit interference
3633     if (i == 0 && isThisReturn) {
3634       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3635              "unexpected return calling convention register assignment");
3636       InVals.push_back(ThisVal);
3637       continue;
3638     }
3639 
3640     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3641     // allows one use of a physreg per block.
3642     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3643     if (!Val) {
3644       Val =
3645           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3646       Chain = Val.getValue(1);
3647       InFlag = Val.getValue(2);
3648       CopiedRegs[VA.getLocReg()] = Val;
3649     }
3650 
3651     switch (VA.getLocInfo()) {
3652     default:
3653       llvm_unreachable("Unknown loc info!");
3654     case CCValAssign::Full:
3655       break;
3656     case CCValAssign::BCvt:
3657       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3658       break;
3659     case CCValAssign::AExtUpper:
3660       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3661                         DAG.getConstant(32, DL, VA.getLocVT()));
3662       LLVM_FALLTHROUGH;
3663     case CCValAssign::AExt:
3664       LLVM_FALLTHROUGH;
3665     case CCValAssign::ZExt:
3666       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3667       break;
3668     }
3669 
3670     InVals.push_back(Val);
3671   }
3672 
3673   return Chain;
3674 }
3675 
3676 /// Return true if the calling convention is one that we can guarantee TCO for.
3677 static bool canGuaranteeTCO(CallingConv::ID CC) {
3678   return CC == CallingConv::Fast;
3679 }
3680 
3681 /// Return true if we might ever do TCO for calls with this calling convention.
3682 static bool mayTailCallThisCC(CallingConv::ID CC) {
3683   switch (CC) {
3684   case CallingConv::C:
3685   case CallingConv::PreserveMost:
3686   case CallingConv::Swift:
3687     return true;
3688   default:
3689     return canGuaranteeTCO(CC);
3690   }
3691 }
3692 
3693 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3694     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3695     const SmallVectorImpl<ISD::OutputArg> &Outs,
3696     const SmallVectorImpl<SDValue> &OutVals,
3697     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3698   if (!mayTailCallThisCC(CalleeCC))
3699     return false;
3700 
3701   MachineFunction &MF = DAG.getMachineFunction();
3702   const Function &CallerF = MF.getFunction();
3703   CallingConv::ID CallerCC = CallerF.getCallingConv();
3704   bool CCMatch = CallerCC == CalleeCC;
3705 
3706   // Byval parameters hand the function a pointer directly into the stack area
3707   // we want to reuse during a tail call. Working around this *is* possible (see
3708   // X86) but less efficient and uglier in LowerCall.
3709   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3710                                     e = CallerF.arg_end();
3711        i != e; ++i) {
3712     if (i->hasByValAttr())
3713       return false;
3714 
3715     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3716     // In this case, it is necessary to save/restore X0 in the callee. Tail
3717     // call opt interferes with this. So we disable tail call opt when the
3718     // caller has an argument with "inreg" attribute.
3719 
3720     // FIXME: Check whether the callee also has an "inreg" argument.
3721     if (i->hasInRegAttr())
3722       return false;
3723   }
3724 
3725   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3726     return canGuaranteeTCO(CalleeCC) && CCMatch;
3727 
3728   // Externally-defined functions with weak linkage should not be
3729   // tail-called on AArch64 when the OS does not support dynamic
3730   // pre-emption of symbols, as the AAELF spec requires normal calls
3731   // to undefined weak functions to be replaced with a NOP or jump to the
3732   // next instruction. The behaviour of branch instructions in this
3733   // situation (as used for tail calls) is implementation-defined, so we
3734   // cannot rely on the linker replacing the tail call with a return.
3735   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3736     const GlobalValue *GV = G->getGlobal();
3737     const Triple &TT = getTargetMachine().getTargetTriple();
3738     if (GV->hasExternalWeakLinkage() &&
3739         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3740       return false;
3741   }
3742 
3743   // Now we search for cases where we can use a tail call without changing the
3744   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3745   // concept.
3746 
3747   // I want anyone implementing a new calling convention to think long and hard
3748   // about this assert.
3749   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3750          "Unexpected variadic calling convention");
3751 
3752   LLVMContext &C = *DAG.getContext();
3753   if (isVarArg && !Outs.empty()) {
3754     // At least two cases here: if caller is fastcc then we can't have any
3755     // memory arguments (we'd be expected to clean up the stack afterwards). If
3756     // caller is C then we could potentially use its argument area.
3757 
3758     // FIXME: for now we take the most conservative of these in both cases:
3759     // disallow all variadic memory operands.
3760     SmallVector<CCValAssign, 16> ArgLocs;
3761     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3762 
3763     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3764     for (const CCValAssign &ArgLoc : ArgLocs)
3765       if (!ArgLoc.isRegLoc())
3766         return false;
3767   }
3768 
3769   // Check that the call results are passed in the same way.
3770   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3771                                   CCAssignFnForCall(CalleeCC, isVarArg),
3772                                   CCAssignFnForCall(CallerCC, isVarArg)))
3773     return false;
3774   // The callee has to preserve all registers the caller needs to preserve.
3775   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3776   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3777   if (!CCMatch) {
3778     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3779     if (Subtarget->hasCustomCallingConv()) {
3780       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3781       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3782     }
3783     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3784       return false;
3785   }
3786 
3787   // Nothing more to check if the callee is taking no arguments
3788   if (Outs.empty())
3789     return true;
3790 
3791   SmallVector<CCValAssign, 16> ArgLocs;
3792   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3793 
3794   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3795 
3796   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3797 
3798   // If the stack arguments for this call do not fit into our own save area then
3799   // the call cannot be made tail.
3800   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3801     return false;
3802 
3803   const MachineRegisterInfo &MRI = MF.getRegInfo();
3804   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3805     return false;
3806 
3807   return true;
3808 }
3809 
3810 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3811                                                    SelectionDAG &DAG,
3812                                                    MachineFrameInfo &MFI,
3813                                                    int ClobberedFI) const {
3814   SmallVector<SDValue, 8> ArgChains;
3815   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3816   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3817 
3818   // Include the original chain at the beginning of the list. When this is
3819   // used by target LowerCall hooks, this helps legalize find the
3820   // CALLSEQ_BEGIN node.
3821   ArgChains.push_back(Chain);
3822 
3823   // Add a chain value for each stack argument corresponding
3824   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3825                             UE = DAG.getEntryNode().getNode()->use_end();
3826        U != UE; ++U)
3827     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3828       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3829         if (FI->getIndex() < 0) {
3830           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3831           int64_t InLastByte = InFirstByte;
3832           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3833 
3834           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3835               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3836             ArgChains.push_back(SDValue(L, 1));
3837         }
3838 
3839   // Build a tokenfactor for all the chains.
3840   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3841 }
3842 
3843 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3844                                                    bool TailCallOpt) const {
3845   return CallCC == CallingConv::Fast && TailCallOpt;
3846 }
3847 
3848 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3849 /// and add input and output parameter nodes.
3850 SDValue
3851 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3852                                  SmallVectorImpl<SDValue> &InVals) const {
3853   SelectionDAG &DAG = CLI.DAG;
3854   SDLoc &DL = CLI.DL;
3855   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3856   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3857   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3858   SDValue Chain = CLI.Chain;
3859   SDValue Callee = CLI.Callee;
3860   bool &IsTailCall = CLI.IsTailCall;
3861   CallingConv::ID CallConv = CLI.CallConv;
3862   bool IsVarArg = CLI.IsVarArg;
3863 
3864   MachineFunction &MF = DAG.getMachineFunction();
3865   MachineFunction::CallSiteInfo CSInfo;
3866   bool IsThisReturn = false;
3867 
3868   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3869   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3870   bool IsSibCall = false;
3871 
3872   if (IsTailCall) {
3873     // Check if it's really possible to do a tail call.
3874     IsTailCall = isEligibleForTailCallOptimization(
3875         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3876     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3877       report_fatal_error("failed to perform tail call elimination on a call "
3878                          "site marked musttail");
3879 
3880     // A sibling call is one where we're under the usual C ABI and not planning
3881     // to change that but can still do a tail call:
3882     if (!TailCallOpt && IsTailCall)
3883       IsSibCall = true;
3884 
3885     if (IsTailCall)
3886       ++NumTailCalls;
3887   }
3888 
3889   // Analyze operands of the call, assigning locations to each operand.
3890   SmallVector<CCValAssign, 16> ArgLocs;
3891   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3892                  *DAG.getContext());
3893 
3894   if (IsVarArg) {
3895     // Handle fixed and variable vector arguments differently.
3896     // Variable vector arguments always go into memory.
3897     unsigned NumArgs = Outs.size();
3898 
3899     for (unsigned i = 0; i != NumArgs; ++i) {
3900       MVT ArgVT = Outs[i].VT;
3901       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3902       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3903                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3904       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3905       assert(!Res && "Call operand has unhandled type");
3906       (void)Res;
3907     }
3908   } else {
3909     // At this point, Outs[].VT may already be promoted to i32. To correctly
3910     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3911     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3912     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3913     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3914     // LocVT.
3915     unsigned NumArgs = Outs.size();
3916     for (unsigned i = 0; i != NumArgs; ++i) {
3917       MVT ValVT = Outs[i].VT;
3918       // Get type of the original argument.
3919       EVT ActualVT = getValueType(DAG.getDataLayout(),
3920                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3921                                   /*AllowUnknown*/ true);
3922       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3923       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3924       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3925       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3926         ValVT = MVT::i8;
3927       else if (ActualMVT == MVT::i16)
3928         ValVT = MVT::i16;
3929 
3930       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3931       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3932       assert(!Res && "Call operand has unhandled type");
3933       (void)Res;
3934     }
3935   }
3936 
3937   // Get a count of how many bytes are to be pushed on the stack.
3938   unsigned NumBytes = CCInfo.getNextStackOffset();
3939 
3940   if (IsSibCall) {
3941     // Since we're not changing the ABI to make this a tail call, the memory
3942     // operands are already available in the caller's incoming argument space.
3943     NumBytes = 0;
3944   }
3945 
3946   // FPDiff is the byte offset of the call's argument area from the callee's.
3947   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3948   // by this amount for a tail call. In a sibling call it must be 0 because the
3949   // caller will deallocate the entire stack and the callee still expects its
3950   // arguments to begin at SP+0. Completely unused for non-tail calls.
3951   int FPDiff = 0;
3952 
3953   if (IsTailCall && !IsSibCall) {
3954     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3955 
3956     // Since callee will pop argument stack as a tail call, we must keep the
3957     // popped size 16-byte aligned.
3958     NumBytes = alignTo(NumBytes, 16);
3959 
3960     // FPDiff will be negative if this tail call requires more space than we
3961     // would automatically have in our incoming argument space. Positive if we
3962     // can actually shrink the stack.
3963     FPDiff = NumReusableBytes - NumBytes;
3964 
3965     // The stack pointer must be 16-byte aligned at all times it's used for a
3966     // memory operation, which in practice means at *all* times and in
3967     // particular across call boundaries. Therefore our own arguments started at
3968     // a 16-byte aligned SP and the delta applied for the tail call should
3969     // satisfy the same constraint.
3970     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3971   }
3972 
3973   // Adjust the stack pointer for the new arguments...
3974   // These operations are automatically eliminated by the prolog/epilog pass
3975   if (!IsSibCall)
3976     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3977 
3978   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3979                                         getPointerTy(DAG.getDataLayout()));
3980 
3981   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3982   SmallSet<unsigned, 8> RegsUsed;
3983   SmallVector<SDValue, 8> MemOpChains;
3984   auto PtrVT = getPointerTy(DAG.getDataLayout());
3985 
3986   if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3987     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3988     for (const auto &F : Forwards) {
3989       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3990        RegsToPass.emplace_back(F.PReg, Val);
3991     }
3992   }
3993 
3994   // Walk the register/memloc assignments, inserting copies/loads.
3995   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3996     CCValAssign &VA = ArgLocs[i];
3997     SDValue Arg = OutVals[i];
3998     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3999 
4000     // Promote the value if needed.
4001     switch (VA.getLocInfo()) {
4002     default:
4003       llvm_unreachable("Unknown loc info!");
4004     case CCValAssign::Full:
4005       break;
4006     case CCValAssign::SExt:
4007       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4008       break;
4009     case CCValAssign::ZExt:
4010       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4011       break;
4012     case CCValAssign::AExt:
4013       if (Outs[i].ArgVT == MVT::i1) {
4014         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4015         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4016         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4017       }
4018       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4019       break;
4020     case CCValAssign::AExtUpper:
4021       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4022       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4023       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4024                         DAG.getConstant(32, DL, VA.getLocVT()));
4025       break;
4026     case CCValAssign::BCvt:
4027       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4028       break;
4029     case CCValAssign::Trunc:
4030       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4031       break;
4032     case CCValAssign::FPExt:
4033       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4034       break;
4035     case CCValAssign::Indirect:
4036       assert(VA.getValVT().isScalableVector() &&
4037              "Only scalable vectors can be passed indirectly");
4038       llvm_unreachable("Spilling of SVE vectors not yet implemented");
4039     }
4040 
4041     if (VA.isRegLoc()) {
4042       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4043           Outs[0].VT == MVT::i64) {
4044         assert(VA.getLocVT() == MVT::i64 &&
4045                "unexpected calling convention register assignment");
4046         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4047                "unexpected use of 'returned'");
4048         IsThisReturn = true;
4049       }
4050       if (RegsUsed.count(VA.getLocReg())) {
4051         // If this register has already been used then we're trying to pack
4052         // parts of an [N x i32] into an X-register. The extension type will
4053         // take care of putting the two halves in the right place but we have to
4054         // combine them.
4055         SDValue &Bits =
4056             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4057                          [=](const std::pair<unsigned, SDValue> &Elt) {
4058                            return Elt.first == VA.getLocReg();
4059                          })
4060                 ->second;
4061         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4062         // Call site info is used for function's parameter entry value
4063         // tracking. For now we track only simple cases when parameter
4064         // is transferred through whole register.
4065         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4066                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4067                                       return ArgReg.Reg == VA.getLocReg();
4068                                     }),
4069                      CSInfo.end());
4070       } else {
4071         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4072         RegsUsed.insert(VA.getLocReg());
4073         const TargetOptions &Options = DAG.getTarget().Options;
4074         if (Options.EnableDebugEntryValues)
4075           CSInfo.emplace_back(VA.getLocReg(), i);
4076       }
4077     } else {
4078       assert(VA.isMemLoc());
4079 
4080       SDValue DstAddr;
4081       MachinePointerInfo DstInfo;
4082 
4083       // FIXME: This works on big-endian for composite byvals, which are the
4084       // common case. It should also work for fundamental types too.
4085       uint32_t BEAlign = 0;
4086       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4087                                         : VA.getValVT().getSizeInBits();
4088       OpSize = (OpSize + 7) / 8;
4089       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4090           !Flags.isInConsecutiveRegs()) {
4091         if (OpSize < 8)
4092           BEAlign = 8 - OpSize;
4093       }
4094       unsigned LocMemOffset = VA.getLocMemOffset();
4095       int32_t Offset = LocMemOffset + BEAlign;
4096       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4097       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4098 
4099       if (IsTailCall) {
4100         Offset = Offset + FPDiff;
4101         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4102 
4103         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4104         DstInfo =
4105             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4106 
4107         // Make sure any stack arguments overlapping with where we're storing
4108         // are loaded before this eventual operation. Otherwise they'll be
4109         // clobbered.
4110         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4111       } else {
4112         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4113 
4114         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4115         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4116                                                LocMemOffset);
4117       }
4118 
4119       if (Outs[i].Flags.isByVal()) {
4120         SDValue SizeNode =
4121             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4122         SDValue Cpy = DAG.getMemcpy(
4123             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
4124             /*isVol = */ false, /*AlwaysInline = */ false,
4125             /*isTailCall = */ false,
4126             DstInfo, MachinePointerInfo());
4127 
4128         MemOpChains.push_back(Cpy);
4129       } else {
4130         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4131         // promoted to a legal register type i32, we should truncate Arg back to
4132         // i1/i8/i16.
4133         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4134             VA.getValVT() == MVT::i16)
4135           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4136 
4137         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4138         MemOpChains.push_back(Store);
4139       }
4140     }
4141   }
4142 
4143   if (!MemOpChains.empty())
4144     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4145 
4146   // Build a sequence of copy-to-reg nodes chained together with token chain
4147   // and flag operands which copy the outgoing args into the appropriate regs.
4148   SDValue InFlag;
4149   for (auto &RegToPass : RegsToPass) {
4150     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4151                              RegToPass.second, InFlag);
4152     InFlag = Chain.getValue(1);
4153   }
4154 
4155   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4156   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4157   // node so that legalize doesn't hack it.
4158   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4159     auto GV = G->getGlobal();
4160     unsigned OpFlags =
4161         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4162     if (OpFlags & AArch64II::MO_GOT) {
4163       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4164       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4165     } else {
4166       const GlobalValue *GV = G->getGlobal();
4167       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4168     }
4169   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4170     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4171         Subtarget->isTargetMachO()) {
4172       const char *Sym = S->getSymbol();
4173       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4174       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4175     } else {
4176       const char *Sym = S->getSymbol();
4177       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4178     }
4179   }
4180 
4181   // We don't usually want to end the call-sequence here because we would tidy
4182   // the frame up *after* the call, however in the ABI-changing tail-call case
4183   // we've carefully laid out the parameters so that when sp is reset they'll be
4184   // in the correct location.
4185   if (IsTailCall && !IsSibCall) {
4186     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4187                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4188     InFlag = Chain.getValue(1);
4189   }
4190 
4191   std::vector<SDValue> Ops;
4192   Ops.push_back(Chain);
4193   Ops.push_back(Callee);
4194 
4195   if (IsTailCall) {
4196     // Each tail call may have to adjust the stack by a different amount, so
4197     // this information must travel along with the operation for eventual
4198     // consumption by emitEpilogue.
4199     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4200   }
4201 
4202   // Add argument registers to the end of the list so that they are known live
4203   // into the call.
4204   for (auto &RegToPass : RegsToPass)
4205     Ops.push_back(DAG.getRegister(RegToPass.first,
4206                                   RegToPass.second.getValueType()));
4207 
4208   // Check callee args/returns for SVE registers and set calling convention
4209   // accordingly.
4210   if (CallConv == CallingConv::C) {
4211     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4212       return Out.VT.isScalableVector();
4213     });
4214     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4215       return In.VT.isScalableVector();
4216     });
4217 
4218     if (CalleeInSVE || CalleeOutSVE)
4219       CallConv = CallingConv::AArch64_SVE_VectorCall;
4220   }
4221 
4222   // Add a register mask operand representing the call-preserved registers.
4223   const uint32_t *Mask;
4224   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4225   if (IsThisReturn) {
4226     // For 'this' returns, use the X0-preserving mask if applicable
4227     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4228     if (!Mask) {
4229       IsThisReturn = false;
4230       Mask = TRI->getCallPreservedMask(MF, CallConv);
4231     }
4232   } else
4233     Mask = TRI->getCallPreservedMask(MF, CallConv);
4234 
4235   if (Subtarget->hasCustomCallingConv())
4236     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4237 
4238   if (TRI->isAnyArgRegReserved(MF))
4239     TRI->emitReservedArgRegCallError(MF);
4240 
4241   assert(Mask && "Missing call preserved mask for calling convention");
4242   Ops.push_back(DAG.getRegisterMask(Mask));
4243 
4244   if (InFlag.getNode())
4245     Ops.push_back(InFlag);
4246 
4247   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4248 
4249   // If we're doing a tall call, use a TC_RETURN here rather than an
4250   // actual call instruction.
4251   if (IsTailCall) {
4252     MF.getFrameInfo().setHasTailCall();
4253     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4254     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4255     return Ret;
4256   }
4257 
4258   // Returns a chain and a flag for retval copy to use.
4259   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4260   InFlag = Chain.getValue(1);
4261   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4262 
4263   uint64_t CalleePopBytes =
4264       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4265 
4266   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4267                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4268                              InFlag, DL);
4269   if (!Ins.empty())
4270     InFlag = Chain.getValue(1);
4271 
4272   // Handle result values, copying them out of physregs into vregs that we
4273   // return.
4274   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4275                          InVals, IsThisReturn,
4276                          IsThisReturn ? OutVals[0] : SDValue());
4277 }
4278 
4279 bool AArch64TargetLowering::CanLowerReturn(
4280     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4281     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4282   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4283                           ? RetCC_AArch64_WebKit_JS
4284                           : RetCC_AArch64_AAPCS;
4285   SmallVector<CCValAssign, 16> RVLocs;
4286   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4287   return CCInfo.CheckReturn(Outs, RetCC);
4288 }
4289 
4290 SDValue
4291 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4292                                    bool isVarArg,
4293                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4294                                    const SmallVectorImpl<SDValue> &OutVals,
4295                                    const SDLoc &DL, SelectionDAG &DAG) const {
4296   auto &MF = DAG.getMachineFunction();
4297   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4298 
4299   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4300                           ? RetCC_AArch64_WebKit_JS
4301                           : RetCC_AArch64_AAPCS;
4302   SmallVector<CCValAssign, 16> RVLocs;
4303   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4304                  *DAG.getContext());
4305   CCInfo.AnalyzeReturn(Outs, RetCC);
4306 
4307   // Copy the result values into the output registers.
4308   SDValue Flag;
4309   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4310   SmallSet<unsigned, 4> RegsUsed;
4311   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4312        ++i, ++realRVLocIdx) {
4313     CCValAssign &VA = RVLocs[i];
4314     assert(VA.isRegLoc() && "Can only return in registers!");
4315     SDValue Arg = OutVals[realRVLocIdx];
4316 
4317     switch (VA.getLocInfo()) {
4318     default:
4319       llvm_unreachable("Unknown loc info!");
4320     case CCValAssign::Full:
4321       if (Outs[i].ArgVT == MVT::i1) {
4322         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4323         // value. This is strictly redundant on Darwin (which uses "zeroext
4324         // i1"), but will be optimised out before ISel.
4325         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4326         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4327       }
4328       break;
4329     case CCValAssign::BCvt:
4330       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4331       break;
4332     case CCValAssign::AExt:
4333     case CCValAssign::ZExt:
4334       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4335       break;
4336     case CCValAssign::AExtUpper:
4337       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4338       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4339       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4340                         DAG.getConstant(32, DL, VA.getLocVT()));
4341       break;
4342     }
4343 
4344     if (RegsUsed.count(VA.getLocReg())) {
4345       SDValue &Bits =
4346           std::find_if(RetVals.begin(), RetVals.end(),
4347                        [=](const std::pair<unsigned, SDValue> &Elt) {
4348                          return Elt.first == VA.getLocReg();
4349                        })
4350               ->second;
4351       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4352     } else {
4353       RetVals.emplace_back(VA.getLocReg(), Arg);
4354       RegsUsed.insert(VA.getLocReg());
4355     }
4356   }
4357 
4358   SmallVector<SDValue, 4> RetOps(1, Chain);
4359   for (auto &RetVal : RetVals) {
4360     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4361     Flag = Chain.getValue(1);
4362     RetOps.push_back(
4363         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4364   }
4365 
4366   // Windows AArch64 ABIs require that for returning structs by value we copy
4367   // the sret argument into X0 for the return.
4368   // We saved the argument into a virtual register in the entry block,
4369   // so now we copy the value out and into X0.
4370   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4371     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4372                                      getPointerTy(MF.getDataLayout()));
4373 
4374     unsigned RetValReg = AArch64::X0;
4375     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4376     Flag = Chain.getValue(1);
4377 
4378     RetOps.push_back(
4379       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4380   }
4381 
4382   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4383   const MCPhysReg *I =
4384       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4385   if (I) {
4386     for (; *I; ++I) {
4387       if (AArch64::GPR64RegClass.contains(*I))
4388         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4389       else if (AArch64::FPR64RegClass.contains(*I))
4390         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4391       else
4392         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4393     }
4394   }
4395 
4396   RetOps[0] = Chain; // Update chain.
4397 
4398   // Add the flag if we have it.
4399   if (Flag.getNode())
4400     RetOps.push_back(Flag);
4401 
4402   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4403 }
4404 
4405 //===----------------------------------------------------------------------===//
4406 //  Other Lowering Code
4407 //===----------------------------------------------------------------------===//
4408 
4409 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4410                                              SelectionDAG &DAG,
4411                                              unsigned Flag) const {
4412   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4413                                     N->getOffset(), Flag);
4414 }
4415 
4416 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4417                                              SelectionDAG &DAG,
4418                                              unsigned Flag) const {
4419   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4420 }
4421 
4422 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4423                                              SelectionDAG &DAG,
4424                                              unsigned Flag) const {
4425   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4426                                    N->getOffset(), Flag);
4427 }
4428 
4429 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4430                                              SelectionDAG &DAG,
4431                                              unsigned Flag) const {
4432   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4433 }
4434 
4435 // (loadGOT sym)
4436 template <class NodeTy>
4437 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4438                                       unsigned Flags) const {
4439   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4440   SDLoc DL(N);
4441   EVT Ty = getPointerTy(DAG.getDataLayout());
4442   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4443   // FIXME: Once remat is capable of dealing with instructions with register
4444   // operands, expand this into two nodes instead of using a wrapper node.
4445   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4446 }
4447 
4448 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4449 template <class NodeTy>
4450 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4451                                             unsigned Flags) const {
4452   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4453   SDLoc DL(N);
4454   EVT Ty = getPointerTy(DAG.getDataLayout());
4455   const unsigned char MO_NC = AArch64II::MO_NC;
4456   return DAG.getNode(
4457       AArch64ISD::WrapperLarge, DL, Ty,
4458       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4459       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4460       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4461       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4462 }
4463 
4464 // (addlow (adrp %hi(sym)) %lo(sym))
4465 template <class NodeTy>
4466 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4467                                        unsigned Flags) const {
4468   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4469   SDLoc DL(N);
4470   EVT Ty = getPointerTy(DAG.getDataLayout());
4471   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4472   SDValue Lo = getTargetNode(N, Ty, DAG,
4473                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4474   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4475   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4476 }
4477 
4478 // (adr sym)
4479 template <class NodeTy>
4480 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4481                                            unsigned Flags) const {
4482   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4483   SDLoc DL(N);
4484   EVT Ty = getPointerTy(DAG.getDataLayout());
4485   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4486   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4487 }
4488 
4489 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4490                                                   SelectionDAG &DAG) const {
4491   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4492   const GlobalValue *GV = GN->getGlobal();
4493   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4494 
4495   if (OpFlags != AArch64II::MO_NO_FLAG)
4496     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4497            "unexpected offset in global node");
4498 
4499   // This also catches the large code model case for Darwin, and tiny code
4500   // model with got relocations.
4501   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4502     return getGOT(GN, DAG, OpFlags);
4503   }
4504 
4505   SDValue Result;
4506   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4507     Result = getAddrLarge(GN, DAG, OpFlags);
4508   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4509     Result = getAddrTiny(GN, DAG, OpFlags);
4510   } else {
4511     Result = getAddr(GN, DAG, OpFlags);
4512   }
4513   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4514   SDLoc DL(GN);
4515   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4516     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4517                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4518   return Result;
4519 }
4520 
4521 /// Convert a TLS address reference into the correct sequence of loads
4522 /// and calls to compute the variable's address (for Darwin, currently) and
4523 /// return an SDValue containing the final node.
4524 
4525 /// Darwin only has one TLS scheme which must be capable of dealing with the
4526 /// fully general situation, in the worst case. This means:
4527 ///     + "extern __thread" declaration.
4528 ///     + Defined in a possibly unknown dynamic library.
4529 ///
4530 /// The general system is that each __thread variable has a [3 x i64] descriptor
4531 /// which contains information used by the runtime to calculate the address. The
4532 /// only part of this the compiler needs to know about is the first xword, which
4533 /// contains a function pointer that must be called with the address of the
4534 /// entire descriptor in "x0".
4535 ///
4536 /// Since this descriptor may be in a different unit, in general even the
4537 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4538 /// is:
4539 ///     adrp x0, _var@TLVPPAGE
4540 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4541 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4542 ///                                      ; the function pointer
4543 ///     blr x1                           ; Uses descriptor address in x0
4544 ///     ; Address of _var is now in x0.
4545 ///
4546 /// If the address of _var's descriptor *is* known to the linker, then it can
4547 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4548 /// a slight efficiency gain.
4549 SDValue
4550 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4551                                                    SelectionDAG &DAG) const {
4552   assert(Subtarget->isTargetDarwin() &&
4553          "This function expects a Darwin target");
4554 
4555   SDLoc DL(Op);
4556   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4557   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4558   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4559 
4560   SDValue TLVPAddr =
4561       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4562   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4563 
4564   // The first entry in the descriptor is a function pointer that we must call
4565   // to obtain the address of the variable.
4566   SDValue Chain = DAG.getEntryNode();
4567   SDValue FuncTLVGet = DAG.getLoad(
4568       PtrMemVT, DL, Chain, DescAddr,
4569       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4570       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4571       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4572   Chain = FuncTLVGet.getValue(1);
4573 
4574   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4575   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4576 
4577   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4578   MFI.setAdjustsStack(true);
4579 
4580   // TLS calls preserve all registers except those that absolutely must be
4581   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4582   // silly).
4583   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4584   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4585   if (Subtarget->hasCustomCallingConv())
4586     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4587 
4588   // Finally, we can make the call. This is just a degenerate version of a
4589   // normal AArch64 call node: x0 takes the address of the descriptor, and
4590   // returns the address of the variable in this thread.
4591   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4592   Chain =
4593       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4594                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4595                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4596   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4597 }
4598 
4599 /// Convert a thread-local variable reference into a sequence of instructions to
4600 /// compute the variable's address for the local exec TLS model of ELF targets.
4601 /// The sequence depends on the maximum TLS area size.
4602 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
4603                                                     SDValue ThreadBase,
4604                                                     const SDLoc &DL,
4605                                                     SelectionDAG &DAG) const {
4606   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4607   SDValue TPOff, Addr;
4608 
4609   switch (DAG.getTarget().Options.TLSSize) {
4610   default:
4611     llvm_unreachable("Unexpected TLS size");
4612 
4613   case 12: {
4614     // mrs   x0, TPIDR_EL0
4615     // add   x0, x0, :tprel_lo12:a
4616     SDValue Var = DAG.getTargetGlobalAddress(
4617         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
4618     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4619                                       Var,
4620                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4621                    0);
4622   }
4623 
4624   case 24: {
4625     // mrs   x0, TPIDR_EL0
4626     // add   x0, x0, :tprel_hi12:a
4627     // add   x0, x0, :tprel_lo12_nc:a
4628     SDValue HiVar = DAG.getTargetGlobalAddress(
4629         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4630     SDValue LoVar = DAG.getTargetGlobalAddress(
4631         GV, DL, PtrVT, 0,
4632         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4633     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4634                                       HiVar,
4635                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4636                    0);
4637     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
4638                                       LoVar,
4639                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4640                    0);
4641   }
4642 
4643   case 32: {
4644     // mrs   x1, TPIDR_EL0
4645     // movz  x0, #:tprel_g1:a
4646     // movk  x0, #:tprel_g0_nc:a
4647     // add   x0, x1, x0
4648     SDValue HiVar = DAG.getTargetGlobalAddress(
4649         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
4650     SDValue LoVar = DAG.getTargetGlobalAddress(
4651         GV, DL, PtrVT, 0,
4652         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4653     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4654                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4655                     0);
4656     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4657                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4658                     0);
4659     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4660   }
4661 
4662   case 48: {
4663     // mrs   x1, TPIDR_EL0
4664     // movz  x0, #:tprel_g2:a
4665     // movk  x0, #:tprel_g1_nc:a
4666     // movk  x0, #:tprel_g0_nc:a
4667     // add   x0, x1, x0
4668     SDValue HiVar = DAG.getTargetGlobalAddress(
4669         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
4670     SDValue MiVar = DAG.getTargetGlobalAddress(
4671         GV, DL, PtrVT, 0,
4672         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
4673     SDValue LoVar = DAG.getTargetGlobalAddress(
4674         GV, DL, PtrVT, 0,
4675         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4676     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4677                                        DAG.getTargetConstant(32, DL, MVT::i32)),
4678                     0);
4679     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
4680                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4681                     0);
4682     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4683                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4684                     0);
4685     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4686   }
4687   }
4688 }
4689 
4690 /// When accessing thread-local variables under either the general-dynamic or
4691 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4692 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4693 /// is a function pointer to carry out the resolution.
4694 ///
4695 /// The sequence is:
4696 ///    adrp  x0, :tlsdesc:var
4697 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4698 ///    add   x0, x0, #:tlsdesc_lo12:var
4699 ///    .tlsdesccall var
4700 ///    blr   x1
4701 ///    (TPIDR_EL0 offset now in x0)
4702 ///
4703 ///  The above sequence must be produced unscheduled, to enable the linker to
4704 ///  optimize/relax this sequence.
4705 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4706 ///  above sequence, and expanded really late in the compilation flow, to ensure
4707 ///  the sequence is produced as per above.
4708 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4709                                                       const SDLoc &DL,
4710                                                       SelectionDAG &DAG) const {
4711   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4712 
4713   SDValue Chain = DAG.getEntryNode();
4714   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4715 
4716   Chain =
4717       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4718   SDValue Glue = Chain.getValue(1);
4719 
4720   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4721 }
4722 
4723 SDValue
4724 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4725                                                 SelectionDAG &DAG) const {
4726   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4727 
4728   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4729 
4730   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4731 
4732   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4733     if (Model == TLSModel::LocalDynamic)
4734       Model = TLSModel::GeneralDynamic;
4735   }
4736 
4737   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4738       Model != TLSModel::LocalExec)
4739     report_fatal_error("ELF TLS only supported in small memory model or "
4740                        "in local exec TLS model");
4741   // Different choices can be made for the maximum size of the TLS area for a
4742   // module. For the small address model, the default TLS size is 16MiB and the
4743   // maximum TLS size is 4GiB.
4744   // FIXME: add tiny and large code model support for TLS access models other
4745   // than local exec. We currently generate the same code as small for tiny,
4746   // which may be larger than needed.
4747 
4748   SDValue TPOff;
4749   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4750   SDLoc DL(Op);
4751   const GlobalValue *GV = GA->getGlobal();
4752 
4753   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4754 
4755   if (Model == TLSModel::LocalExec) {
4756     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
4757   } else if (Model == TLSModel::InitialExec) {
4758     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4759     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4760   } else if (Model == TLSModel::LocalDynamic) {
4761     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4762     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4763     // the beginning of the module's TLS region, followed by a DTPREL offset
4764     // calculation.
4765 
4766     // These accesses will need deduplicating if there's more than one.
4767     AArch64FunctionInfo *MFI =
4768         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4769     MFI->incNumLocalDynamicTLSAccesses();
4770 
4771     // The call needs a relocation too for linker relaxation. It doesn't make
4772     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4773     // the address.
4774     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4775                                                   AArch64II::MO_TLS);
4776 
4777     // Now we can calculate the offset from TPIDR_EL0 to this module's
4778     // thread-local area.
4779     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4780 
4781     // Now use :dtprel_whatever: operations to calculate this variable's offset
4782     // in its thread-storage area.
4783     SDValue HiVar = DAG.getTargetGlobalAddress(
4784         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4785     SDValue LoVar = DAG.getTargetGlobalAddress(
4786         GV, DL, MVT::i64, 0,
4787         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4788 
4789     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4790                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4791                     0);
4792     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4793                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4794                     0);
4795   } else if (Model == TLSModel::GeneralDynamic) {
4796     // The call needs a relocation too for linker relaxation. It doesn't make
4797     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4798     // the address.
4799     SDValue SymAddr =
4800         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4801 
4802     // Finally we can make a call to calculate the offset from tpidr_el0.
4803     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4804   } else
4805     llvm_unreachable("Unsupported ELF TLS access model");
4806 
4807   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4808 }
4809 
4810 SDValue
4811 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4812                                                     SelectionDAG &DAG) const {
4813   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4814 
4815   SDValue Chain = DAG.getEntryNode();
4816   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4817   SDLoc DL(Op);
4818 
4819   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4820 
4821   // Load the ThreadLocalStoragePointer from the TEB
4822   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4823   SDValue TLSArray =
4824       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4825   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4826   Chain = TLSArray.getValue(1);
4827 
4828   // Load the TLS index from the C runtime;
4829   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4830   // This also does the same as LOADgot, but using a generic i32 load,
4831   // while LOADgot only loads i64.
4832   SDValue TLSIndexHi =
4833       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4834   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4835       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4836   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4837   SDValue TLSIndex =
4838       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4839   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4840   Chain = TLSIndex.getValue(1);
4841 
4842   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4843   // offset into the TLSArray.
4844   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4845   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4846                              DAG.getConstant(3, DL, PtrVT));
4847   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4848                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4849                             MachinePointerInfo());
4850   Chain = TLS.getValue(1);
4851 
4852   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4853   const GlobalValue *GV = GA->getGlobal();
4854   SDValue TGAHi = DAG.getTargetGlobalAddress(
4855       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4856   SDValue TGALo = DAG.getTargetGlobalAddress(
4857       GV, DL, PtrVT, 0,
4858       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4859 
4860   // Add the offset from the start of the .tls section (section base).
4861   SDValue Addr =
4862       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4863                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4864               0);
4865   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4866   return Addr;
4867 }
4868 
4869 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4870                                                      SelectionDAG &DAG) const {
4871   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4872   if (DAG.getTarget().useEmulatedTLS())
4873     return LowerToTLSEmulatedModel(GA, DAG);
4874 
4875   if (Subtarget->isTargetDarwin())
4876     return LowerDarwinGlobalTLSAddress(Op, DAG);
4877   if (Subtarget->isTargetELF())
4878     return LowerELFGlobalTLSAddress(Op, DAG);
4879   if (Subtarget->isTargetWindows())
4880     return LowerWindowsGlobalTLSAddress(Op, DAG);
4881 
4882   llvm_unreachable("Unexpected platform trying to use TLS");
4883 }
4884 
4885 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4886   SDValue Chain = Op.getOperand(0);
4887   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4888   SDValue LHS = Op.getOperand(2);
4889   SDValue RHS = Op.getOperand(3);
4890   SDValue Dest = Op.getOperand(4);
4891   SDLoc dl(Op);
4892 
4893   MachineFunction &MF = DAG.getMachineFunction();
4894   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4895   // will not be produced, as they are conditional branch instructions that do
4896   // not set flags.
4897   bool ProduceNonFlagSettingCondBr =
4898       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4899 
4900   // Handle f128 first, since lowering it will result in comparing the return
4901   // value of a libcall against zero, which is just what the rest of LowerBR_CC
4902   // is expecting to deal with.
4903   if (LHS.getValueType() == MVT::f128) {
4904     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4905 
4906     // If softenSetCCOperands returned a scalar, we need to compare the result
4907     // against zero to select between true and false values.
4908     if (!RHS.getNode()) {
4909       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4910       CC = ISD::SETNE;
4911     }
4912   }
4913 
4914   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4915   // instruction.
4916   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4917       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4918     // Only lower legal XALUO ops.
4919     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4920       return SDValue();
4921 
4922     // The actual operation with overflow check.
4923     AArch64CC::CondCode OFCC;
4924     SDValue Value, Overflow;
4925     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4926 
4927     if (CC == ISD::SETNE)
4928       OFCC = getInvertedCondCode(OFCC);
4929     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4930 
4931     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4932                        Overflow);
4933   }
4934 
4935   if (LHS.getValueType().isInteger()) {
4936     assert((LHS.getValueType() == RHS.getValueType()) &&
4937            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4938 
4939     // If the RHS of the comparison is zero, we can potentially fold this
4940     // to a specialized branch.
4941     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4942     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4943       if (CC == ISD::SETEQ) {
4944         // See if we can use a TBZ to fold in an AND as well.
4945         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4946         // out of bounds, a late MI-layer pass rewrites branches.
4947         // 403.gcc is an example that hits this case.
4948         if (LHS.getOpcode() == ISD::AND &&
4949             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4950             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4951           SDValue Test = LHS.getOperand(0);
4952           uint64_t Mask = LHS.getConstantOperandVal(1);
4953           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4954                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4955                              Dest);
4956         }
4957 
4958         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4959       } else if (CC == ISD::SETNE) {
4960         // See if we can use a TBZ to fold in an AND as well.
4961         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4962         // out of bounds, a late MI-layer pass rewrites branches.
4963         // 403.gcc is an example that hits this case.
4964         if (LHS.getOpcode() == ISD::AND &&
4965             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4966             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4967           SDValue Test = LHS.getOperand(0);
4968           uint64_t Mask = LHS.getConstantOperandVal(1);
4969           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4970                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4971                              Dest);
4972         }
4973 
4974         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4975       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4976         // Don't combine AND since emitComparison converts the AND to an ANDS
4977         // (a.k.a. TST) and the test in the test bit and branch instruction
4978         // becomes redundant.  This would also increase register pressure.
4979         uint64_t Mask = LHS.getValueSizeInBits() - 1;
4980         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4981                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
4982       }
4983     }
4984     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4985         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4986       // Don't combine AND since emitComparison converts the AND to an ANDS
4987       // (a.k.a. TST) and the test in the test bit and branch instruction
4988       // becomes redundant.  This would also increase register pressure.
4989       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4990       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4991                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4992     }
4993 
4994     SDValue CCVal;
4995     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4996     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4997                        Cmp);
4998   }
4999 
5000   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5001          LHS.getValueType() == MVT::f64);
5002 
5003   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5004   // clean.  Some of them require two branches to implement.
5005   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5006   AArch64CC::CondCode CC1, CC2;
5007   changeFPCCToAArch64CC(CC, CC1, CC2);
5008   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5009   SDValue BR1 =
5010       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5011   if (CC2 != AArch64CC::AL) {
5012     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5013     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5014                        Cmp);
5015   }
5016 
5017   return BR1;
5018 }
5019 
5020 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5021                                               SelectionDAG &DAG) const {
5022   EVT VT = Op.getValueType();
5023   SDLoc DL(Op);
5024 
5025   SDValue In1 = Op.getOperand(0);
5026   SDValue In2 = Op.getOperand(1);
5027   EVT SrcVT = In2.getValueType();
5028 
5029   if (SrcVT.bitsLT(VT))
5030     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5031   else if (SrcVT.bitsGT(VT))
5032     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5033 
5034   EVT VecVT;
5035   uint64_t EltMask;
5036   SDValue VecVal1, VecVal2;
5037 
5038   auto setVecVal = [&] (int Idx) {
5039     if (!VT.isVector()) {
5040       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5041                                           DAG.getUNDEF(VecVT), In1);
5042       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5043                                           DAG.getUNDEF(VecVT), In2);
5044     } else {
5045       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5046       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5047     }
5048   };
5049 
5050   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5051     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5052     EltMask = 0x80000000ULL;
5053     setVecVal(AArch64::ssub);
5054   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5055     VecVT = MVT::v2i64;
5056 
5057     // We want to materialize a mask with the high bit set, but the AdvSIMD
5058     // immediate moves cannot materialize that in a single instruction for
5059     // 64-bit elements. Instead, materialize zero and then negate it.
5060     EltMask = 0;
5061 
5062     setVecVal(AArch64::dsub);
5063   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5064     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5065     EltMask = 0x8000ULL;
5066     setVecVal(AArch64::hsub);
5067   } else {
5068     llvm_unreachable("Invalid type for copysign!");
5069   }
5070 
5071   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5072 
5073   // If we couldn't materialize the mask above, then the mask vector will be
5074   // the zero vector, and we need to negate it here.
5075   if (VT == MVT::f64 || VT == MVT::v2f64) {
5076     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5077     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5078     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5079   }
5080 
5081   SDValue Sel =
5082       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5083 
5084   if (VT == MVT::f16)
5085     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5086   if (VT == MVT::f32)
5087     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5088   else if (VT == MVT::f64)
5089     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5090   else
5091     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5092 }
5093 
5094 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5095   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5096           Attribute::NoImplicitFloat))
5097     return SDValue();
5098 
5099   if (!Subtarget->hasNEON())
5100     return SDValue();
5101 
5102   // While there is no integer popcount instruction, it can
5103   // be more efficiently lowered to the following sequence that uses
5104   // AdvSIMD registers/instructions as long as the copies to/from
5105   // the AdvSIMD registers are cheap.
5106   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5107   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5108   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5109   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5110   SDValue Val = Op.getOperand(0);
5111   SDLoc DL(Op);
5112   EVT VT = Op.getValueType();
5113 
5114   if (VT == MVT::i32 || VT == MVT::i64) {
5115     if (VT == MVT::i32)
5116       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5117     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5118 
5119     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5120     SDValue UaddLV = DAG.getNode(
5121         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5122         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5123 
5124     if (VT == MVT::i64)
5125       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5126     return UaddLV;
5127   }
5128 
5129   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5130           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5131          "Unexpected type for custom ctpop lowering");
5132 
5133   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5134   Val = DAG.getBitcast(VT8Bit, Val);
5135   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5136 
5137   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5138   unsigned EltSize = 8;
5139   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5140   while (EltSize != VT.getScalarSizeInBits()) {
5141     EltSize *= 2;
5142     NumElts /= 2;
5143     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5144     Val = DAG.getNode(
5145         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5146         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5147   }
5148 
5149   return Val;
5150 }
5151 
5152 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5153 
5154   if (Op.getValueType().isVector())
5155     return LowerVSETCC(Op, DAG);
5156 
5157   SDValue LHS = Op.getOperand(0);
5158   SDValue RHS = Op.getOperand(1);
5159   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5160   SDLoc dl(Op);
5161 
5162   // We chose ZeroOrOneBooleanContents, so use zero and one.
5163   EVT VT = Op.getValueType();
5164   SDValue TVal = DAG.getConstant(1, dl, VT);
5165   SDValue FVal = DAG.getConstant(0, dl, VT);
5166 
5167   // Handle f128 first, since one possible outcome is a normal integer
5168   // comparison which gets picked up by the next if statement.
5169   if (LHS.getValueType() == MVT::f128) {
5170     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5171 
5172     // If softenSetCCOperands returned a scalar, use it.
5173     if (!RHS.getNode()) {
5174       assert(LHS.getValueType() == Op.getValueType() &&
5175              "Unexpected setcc expansion!");
5176       return LHS;
5177     }
5178   }
5179 
5180   if (LHS.getValueType().isInteger()) {
5181     SDValue CCVal;
5182     SDValue Cmp = getAArch64Cmp(
5183         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5184 
5185     // Note that we inverted the condition above, so we reverse the order of
5186     // the true and false operands here.  This will allow the setcc to be
5187     // matched to a single CSINC instruction.
5188     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5189   }
5190 
5191   // Now we know we're dealing with FP values.
5192   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5193          LHS.getValueType() == MVT::f64);
5194 
5195   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5196   // and do the comparison.
5197   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5198 
5199   AArch64CC::CondCode CC1, CC2;
5200   changeFPCCToAArch64CC(CC, CC1, CC2);
5201   if (CC2 == AArch64CC::AL) {
5202     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5203                           CC2);
5204     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5205 
5206     // Note that we inverted the condition above, so we reverse the order of
5207     // the true and false operands here.  This will allow the setcc to be
5208     // matched to a single CSINC instruction.
5209     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5210   } else {
5211     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5212     // totally clean.  Some of them require two CSELs to implement.  As is in
5213     // this case, we emit the first CSEL and then emit a second using the output
5214     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5215 
5216     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5217     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5218     SDValue CS1 =
5219         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5220 
5221     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5222     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5223   }
5224 }
5225 
5226 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5227                                               SDValue RHS, SDValue TVal,
5228                                               SDValue FVal, const SDLoc &dl,
5229                                               SelectionDAG &DAG) const {
5230   // Handle f128 first, because it will result in a comparison of some RTLIB
5231   // call result against zero.
5232   if (LHS.getValueType() == MVT::f128) {
5233     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5234 
5235     // If softenSetCCOperands returned a scalar, we need to compare the result
5236     // against zero to select between true and false values.
5237     if (!RHS.getNode()) {
5238       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5239       CC = ISD::SETNE;
5240     }
5241   }
5242 
5243   // Also handle f16, for which we need to do a f32 comparison.
5244   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5245     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5246     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5247   }
5248 
5249   // Next, handle integers.
5250   if (LHS.getValueType().isInteger()) {
5251     assert((LHS.getValueType() == RHS.getValueType()) &&
5252            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5253 
5254     unsigned Opcode = AArch64ISD::CSEL;
5255 
5256     // If both the TVal and the FVal are constants, see if we can swap them in
5257     // order to for a CSINV or CSINC out of them.
5258     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5259     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5260 
5261     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5262       std::swap(TVal, FVal);
5263       std::swap(CTVal, CFVal);
5264       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5265     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5266       std::swap(TVal, FVal);
5267       std::swap(CTVal, CFVal);
5268       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5269     } else if (TVal.getOpcode() == ISD::XOR) {
5270       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5271       // with a CSINV rather than a CSEL.
5272       if (isAllOnesConstant(TVal.getOperand(1))) {
5273         std::swap(TVal, FVal);
5274         std::swap(CTVal, CFVal);
5275         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5276       }
5277     } else if (TVal.getOpcode() == ISD::SUB) {
5278       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5279       // that we can match with a CSNEG rather than a CSEL.
5280       if (isNullConstant(TVal.getOperand(0))) {
5281         std::swap(TVal, FVal);
5282         std::swap(CTVal, CFVal);
5283         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5284       }
5285     } else if (CTVal && CFVal) {
5286       const int64_t TrueVal = CTVal->getSExtValue();
5287       const int64_t FalseVal = CFVal->getSExtValue();
5288       bool Swap = false;
5289 
5290       // If both TVal and FVal are constants, see if FVal is the
5291       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5292       // instead of a CSEL in that case.
5293       if (TrueVal == ~FalseVal) {
5294         Opcode = AArch64ISD::CSINV;
5295       } else if (TrueVal == -FalseVal) {
5296         Opcode = AArch64ISD::CSNEG;
5297       } else if (TVal.getValueType() == MVT::i32) {
5298         // If our operands are only 32-bit wide, make sure we use 32-bit
5299         // arithmetic for the check whether we can use CSINC. This ensures that
5300         // the addition in the check will wrap around properly in case there is
5301         // an overflow (which would not be the case if we do the check with
5302         // 64-bit arithmetic).
5303         const uint32_t TrueVal32 = CTVal->getZExtValue();
5304         const uint32_t FalseVal32 = CFVal->getZExtValue();
5305 
5306         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5307           Opcode = AArch64ISD::CSINC;
5308 
5309           if (TrueVal32 > FalseVal32) {
5310             Swap = true;
5311           }
5312         }
5313         // 64-bit check whether we can use CSINC.
5314       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5315         Opcode = AArch64ISD::CSINC;
5316 
5317         if (TrueVal > FalseVal) {
5318           Swap = true;
5319         }
5320       }
5321 
5322       // Swap TVal and FVal if necessary.
5323       if (Swap) {
5324         std::swap(TVal, FVal);
5325         std::swap(CTVal, CFVal);
5326         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5327       }
5328 
5329       if (Opcode != AArch64ISD::CSEL) {
5330         // Drop FVal since we can get its value by simply inverting/negating
5331         // TVal.
5332         FVal = TVal;
5333       }
5334     }
5335 
5336     // Avoid materializing a constant when possible by reusing a known value in
5337     // a register.  However, don't perform this optimization if the known value
5338     // is one, zero or negative one in the case of a CSEL.  We can always
5339     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5340     // FVal, respectively.
5341     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5342     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5343         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5344       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5345       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5346       // "a != C ? x : a" to avoid materializing C.
5347       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5348         TVal = LHS;
5349       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5350         FVal = LHS;
5351     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5352       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5353       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5354       // avoid materializing C.
5355       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5356       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5357         Opcode = AArch64ISD::CSINV;
5358         TVal = LHS;
5359         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5360       }
5361     }
5362 
5363     SDValue CCVal;
5364     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5365     EVT VT = TVal.getValueType();
5366     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5367   }
5368 
5369   // Now we know we're dealing with FP values.
5370   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5371          LHS.getValueType() == MVT::f64);
5372   assert(LHS.getValueType() == RHS.getValueType());
5373   EVT VT = TVal.getValueType();
5374   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5375 
5376   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5377   // clean.  Some of them require two CSELs to implement.
5378   AArch64CC::CondCode CC1, CC2;
5379   changeFPCCToAArch64CC(CC, CC1, CC2);
5380 
5381   if (DAG.getTarget().Options.UnsafeFPMath) {
5382     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5383     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5384     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5385     if (RHSVal && RHSVal->isZero()) {
5386       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5387       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5388 
5389       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5390           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5391         TVal = LHS;
5392       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5393                CFVal && CFVal->isZero() &&
5394                FVal.getValueType() == LHS.getValueType())
5395         FVal = LHS;
5396     }
5397   }
5398 
5399   // Emit first, and possibly only, CSEL.
5400   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5401   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5402 
5403   // If we need a second CSEL, emit it, using the output of the first as the
5404   // RHS.  We're effectively OR'ing the two CC's together.
5405   if (CC2 != AArch64CC::AL) {
5406     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5407     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5408   }
5409 
5410   // Otherwise, return the output of the first CSEL.
5411   return CS1;
5412 }
5413 
5414 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5415                                               SelectionDAG &DAG) const {
5416   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5417   SDValue LHS = Op.getOperand(0);
5418   SDValue RHS = Op.getOperand(1);
5419   SDValue TVal = Op.getOperand(2);
5420   SDValue FVal = Op.getOperand(3);
5421   SDLoc DL(Op);
5422   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5423 }
5424 
5425 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5426                                            SelectionDAG &DAG) const {
5427   SDValue CCVal = Op->getOperand(0);
5428   SDValue TVal = Op->getOperand(1);
5429   SDValue FVal = Op->getOperand(2);
5430   SDLoc DL(Op);
5431 
5432   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5433   // instruction.
5434   if (isOverflowIntrOpRes(CCVal)) {
5435     // Only lower legal XALUO ops.
5436     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5437       return SDValue();
5438 
5439     AArch64CC::CondCode OFCC;
5440     SDValue Value, Overflow;
5441     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5442     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5443 
5444     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5445                        CCVal, Overflow);
5446   }
5447 
5448   // Lower it the same way as we would lower a SELECT_CC node.
5449   ISD::CondCode CC;
5450   SDValue LHS, RHS;
5451   if (CCVal.getOpcode() == ISD::SETCC) {
5452     LHS = CCVal.getOperand(0);
5453     RHS = CCVal.getOperand(1);
5454     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5455   } else {
5456     LHS = CCVal;
5457     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5458     CC = ISD::SETNE;
5459   }
5460   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5461 }
5462 
5463 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5464                                               SelectionDAG &DAG) const {
5465   // Jump table entries as PC relative offsets. No additional tweaking
5466   // is necessary here. Just get the address of the jump table.
5467   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5468 
5469   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5470       !Subtarget->isTargetMachO()) {
5471     return getAddrLarge(JT, DAG);
5472   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5473     return getAddrTiny(JT, DAG);
5474   }
5475   return getAddr(JT, DAG);
5476 }
5477 
5478 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5479                                           SelectionDAG &DAG) const {
5480   // Jump table entries as PC relative offsets. No additional tweaking
5481   // is necessary here. Just get the address of the jump table.
5482   SDLoc DL(Op);
5483   SDValue JT = Op.getOperand(1);
5484   SDValue Entry = Op.getOperand(2);
5485   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5486 
5487   SDNode *Dest =
5488       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5489                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5490   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5491                      SDValue(Dest, 0));
5492 }
5493 
5494 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5495                                                  SelectionDAG &DAG) const {
5496   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5497 
5498   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5499     // Use the GOT for the large code model on iOS.
5500     if (Subtarget->isTargetMachO()) {
5501       return getGOT(CP, DAG);
5502     }
5503     return getAddrLarge(CP, DAG);
5504   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5505     return getAddrTiny(CP, DAG);
5506   } else {
5507     return getAddr(CP, DAG);
5508   }
5509 }
5510 
5511 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5512                                                SelectionDAG &DAG) const {
5513   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5514   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5515       !Subtarget->isTargetMachO()) {
5516     return getAddrLarge(BA, DAG);
5517   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5518     return getAddrTiny(BA, DAG);
5519   }
5520   return getAddr(BA, DAG);
5521 }
5522 
5523 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5524                                                  SelectionDAG &DAG) const {
5525   AArch64FunctionInfo *FuncInfo =
5526       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5527 
5528   SDLoc DL(Op);
5529   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5530                                  getPointerTy(DAG.getDataLayout()));
5531   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5532   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5533   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5534                       MachinePointerInfo(SV));
5535 }
5536 
5537 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5538                                                   SelectionDAG &DAG) const {
5539   AArch64FunctionInfo *FuncInfo =
5540       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5541 
5542   SDLoc DL(Op);
5543   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5544                                      ? FuncInfo->getVarArgsGPRIndex()
5545                                      : FuncInfo->getVarArgsStackIndex(),
5546                                  getPointerTy(DAG.getDataLayout()));
5547   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5548   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5549                       MachinePointerInfo(SV));
5550 }
5551 
5552 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5553                                                 SelectionDAG &DAG) const {
5554   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5555   // Standard, section B.3.
5556   MachineFunction &MF = DAG.getMachineFunction();
5557   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5558   auto PtrVT = getPointerTy(DAG.getDataLayout());
5559   SDLoc DL(Op);
5560 
5561   SDValue Chain = Op.getOperand(0);
5562   SDValue VAList = Op.getOperand(1);
5563   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5564   SmallVector<SDValue, 4> MemOps;
5565 
5566   // void *__stack at offset 0
5567   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5568   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5569                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5570 
5571   // void *__gr_top at offset 8
5572   int GPRSize = FuncInfo->getVarArgsGPRSize();
5573   if (GPRSize > 0) {
5574     SDValue GRTop, GRTopAddr;
5575 
5576     GRTopAddr =
5577         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5578 
5579     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5580     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5581                         DAG.getConstant(GPRSize, DL, PtrVT));
5582 
5583     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5584                                   MachinePointerInfo(SV, 8),
5585                                   /* Alignment = */ 8));
5586   }
5587 
5588   // void *__vr_top at offset 16
5589   int FPRSize = FuncInfo->getVarArgsFPRSize();
5590   if (FPRSize > 0) {
5591     SDValue VRTop, VRTopAddr;
5592     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5593                             DAG.getConstant(16, DL, PtrVT));
5594 
5595     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5596     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5597                         DAG.getConstant(FPRSize, DL, PtrVT));
5598 
5599     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5600                                   MachinePointerInfo(SV, 16),
5601                                   /* Alignment = */ 8));
5602   }
5603 
5604   // int __gr_offs at offset 24
5605   SDValue GROffsAddr =
5606       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5607   MemOps.push_back(DAG.getStore(
5608       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5609       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5610 
5611   // int __vr_offs at offset 28
5612   SDValue VROffsAddr =
5613       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5614   MemOps.push_back(DAG.getStore(
5615       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5616       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5617 
5618   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5619 }
5620 
5621 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5622                                             SelectionDAG &DAG) const {
5623   MachineFunction &MF = DAG.getMachineFunction();
5624 
5625   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5626     return LowerWin64_VASTART(Op, DAG);
5627   else if (Subtarget->isTargetDarwin())
5628     return LowerDarwin_VASTART(Op, DAG);
5629   else
5630     return LowerAAPCS_VASTART(Op, DAG);
5631 }
5632 
5633 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5634                                            SelectionDAG &DAG) const {
5635   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5636   // pointer.
5637   SDLoc DL(Op);
5638   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5639   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5640                          Subtarget->isTargetWindows()) ? PtrSize : 32;
5641   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5642   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5643 
5644   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5645                        DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize,
5646                        false, false, false, MachinePointerInfo(DestSV),
5647                        MachinePointerInfo(SrcSV));
5648 }
5649 
5650 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5651   assert(Subtarget->isTargetDarwin() &&
5652          "automatic va_arg instruction only works on Darwin");
5653 
5654   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5655   EVT VT = Op.getValueType();
5656   SDLoc DL(Op);
5657   SDValue Chain = Op.getOperand(0);
5658   SDValue Addr = Op.getOperand(1);
5659   unsigned Align = Op.getConstantOperandVal(3);
5660   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5661   auto PtrVT = getPointerTy(DAG.getDataLayout());
5662   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5663   SDValue VAList =
5664       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5665   Chain = VAList.getValue(1);
5666   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5667 
5668   if (Align > MinSlotSize) {
5669     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5670     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5671                          DAG.getConstant(Align - 1, DL, PtrVT));
5672     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5673                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5674   }
5675 
5676   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5677   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5678 
5679   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5680   // up to 64 bits.  At the very least, we have to increase the striding of the
5681   // vaargs list to match this, and for FP values we need to introduce
5682   // FP_ROUND nodes as well.
5683   if (VT.isInteger() && !VT.isVector())
5684     ArgSize = std::max(ArgSize, MinSlotSize);
5685   bool NeedFPTrunc = false;
5686   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5687     ArgSize = 8;
5688     NeedFPTrunc = true;
5689   }
5690 
5691   // Increment the pointer, VAList, to the next vaarg
5692   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5693                                DAG.getConstant(ArgSize, DL, PtrVT));
5694   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5695 
5696   // Store the incremented VAList to the legalized pointer
5697   SDValue APStore =
5698       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5699 
5700   // Load the actual argument out of the pointer VAList
5701   if (NeedFPTrunc) {
5702     // Load the value as an f64.
5703     SDValue WideFP =
5704         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5705     // Round the value down to an f32.
5706     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5707                                    DAG.getIntPtrConstant(1, DL));
5708     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5709     // Merge the rounded value with the chain output of the load.
5710     return DAG.getMergeValues(Ops, DL);
5711   }
5712 
5713   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5714 }
5715 
5716 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5717                                               SelectionDAG &DAG) const {
5718   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5719   MFI.setFrameAddressIsTaken(true);
5720 
5721   EVT VT = Op.getValueType();
5722   SDLoc DL(Op);
5723   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5724   SDValue FrameAddr =
5725       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5726   while (Depth--)
5727     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5728                             MachinePointerInfo());
5729 
5730   if (Subtarget->isTargetILP32())
5731     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5732                             DAG.getValueType(VT));
5733 
5734   return FrameAddr;
5735 }
5736 
5737 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5738                                               SelectionDAG &DAG) const {
5739   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5740 
5741   EVT VT = getPointerTy(DAG.getDataLayout());
5742   SDLoc DL(Op);
5743   int FI = MFI.CreateFixedObject(4, 0, false);
5744   return DAG.getFrameIndex(FI, VT);
5745 }
5746 
5747 #define GET_REGISTER_MATCHER
5748 #include "AArch64GenAsmMatcher.inc"
5749 
5750 // FIXME? Maybe this could be a TableGen attribute on some registers and
5751 // this table could be generated automatically from RegInfo.
5752 Register AArch64TargetLowering::
5753 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
5754   Register Reg = MatchRegisterName(RegName);
5755   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5756     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5757     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5758     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5759       Reg = 0;
5760   }
5761   if (Reg)
5762     return Reg;
5763   report_fatal_error(Twine("Invalid register name \""
5764                               + StringRef(RegName)  + "\"."));
5765 }
5766 
5767 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5768                                                      SelectionDAG &DAG) const {
5769   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5770 
5771   EVT VT = Op.getValueType();
5772   SDLoc DL(Op);
5773 
5774   SDValue FrameAddr =
5775       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5776   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5777 
5778   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5779 }
5780 
5781 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5782                                                SelectionDAG &DAG) const {
5783   MachineFunction &MF = DAG.getMachineFunction();
5784   MachineFrameInfo &MFI = MF.getFrameInfo();
5785   MFI.setReturnAddressIsTaken(true);
5786 
5787   EVT VT = Op.getValueType();
5788   SDLoc DL(Op);
5789   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5790   if (Depth) {
5791     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5792     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5793     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5794                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5795                        MachinePointerInfo());
5796   }
5797 
5798   // Return LR, which contains the return address. Mark it an implicit live-in.
5799   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5800   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5801 }
5802 
5803 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5804 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5805 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5806                                                     SelectionDAG &DAG) const {
5807   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5808   EVT VT = Op.getValueType();
5809   unsigned VTBits = VT.getSizeInBits();
5810   SDLoc dl(Op);
5811   SDValue ShOpLo = Op.getOperand(0);
5812   SDValue ShOpHi = Op.getOperand(1);
5813   SDValue ShAmt = Op.getOperand(2);
5814   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5815 
5816   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5817 
5818   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5819                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5820   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5821 
5822   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5823   // is "undef". We wanted 0, so CSEL it directly.
5824   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5825                                ISD::SETEQ, dl, DAG);
5826   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5827   HiBitsForLo =
5828       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5829                   HiBitsForLo, CCVal, Cmp);
5830 
5831   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5832                                    DAG.getConstant(VTBits, dl, MVT::i64));
5833 
5834   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5835   SDValue LoForNormalShift =
5836       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5837 
5838   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5839                        dl, DAG);
5840   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5841   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5842   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5843                            LoForNormalShift, CCVal, Cmp);
5844 
5845   // AArch64 shifts larger than the register width are wrapped rather than
5846   // clamped, so we can't just emit "hi >> x".
5847   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5848   SDValue HiForBigShift =
5849       Opc == ISD::SRA
5850           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5851                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5852           : DAG.getConstant(0, dl, VT);
5853   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5854                            HiForNormalShift, CCVal, Cmp);
5855 
5856   SDValue Ops[2] = { Lo, Hi };
5857   return DAG.getMergeValues(Ops, dl);
5858 }
5859 
5860 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5861 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5862 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5863                                                    SelectionDAG &DAG) const {
5864   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5865   EVT VT = Op.getValueType();
5866   unsigned VTBits = VT.getSizeInBits();
5867   SDLoc dl(Op);
5868   SDValue ShOpLo = Op.getOperand(0);
5869   SDValue ShOpHi = Op.getOperand(1);
5870   SDValue ShAmt = Op.getOperand(2);
5871 
5872   assert(Op.getOpcode() == ISD::SHL_PARTS);
5873   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5874                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5875   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5876 
5877   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5878   // is "undef". We wanted 0, so CSEL it directly.
5879   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5880                                ISD::SETEQ, dl, DAG);
5881   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5882   LoBitsForHi =
5883       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5884                   LoBitsForHi, CCVal, Cmp);
5885 
5886   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5887                                    DAG.getConstant(VTBits, dl, MVT::i64));
5888   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5889   SDValue HiForNormalShift =
5890       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5891 
5892   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5893 
5894   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5895                        dl, DAG);
5896   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5897   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5898                            HiForNormalShift, CCVal, Cmp);
5899 
5900   // AArch64 shifts of larger than register sizes are wrapped rather than
5901   // clamped, so we can't just emit "lo << a" if a is too big.
5902   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5903   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5904   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5905                            LoForNormalShift, CCVal, Cmp);
5906 
5907   SDValue Ops[2] = { Lo, Hi };
5908   return DAG.getMergeValues(Ops, dl);
5909 }
5910 
5911 bool AArch64TargetLowering::isOffsetFoldingLegal(
5912     const GlobalAddressSDNode *GA) const {
5913   // Offsets are folded in the DAG combine rather than here so that we can
5914   // intelligently choose an offset based on the uses.
5915   return false;
5916 }
5917 
5918 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5919                                          bool OptForSize) const {
5920   bool IsLegal = false;
5921   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5922   // 16-bit case when target has full fp16 support.
5923   // FIXME: We should be able to handle f128 as well with a clever lowering.
5924   const APInt ImmInt = Imm.bitcastToAPInt();
5925   if (VT == MVT::f64)
5926     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5927   else if (VT == MVT::f32)
5928     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5929   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5930     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5931   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5932   //       generate that fmov.
5933 
5934   // If we can not materialize in immediate field for fmov, check if the
5935   // value can be encoded as the immediate operand of a logical instruction.
5936   // The immediate value will be created with either MOVZ, MOVN, or ORR.
5937   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5938     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5939     // however the mov+fmov sequence is always better because of the reduced
5940     // cache pressure. The timings are still the same if you consider
5941     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5942     // movw+movk is fused). So we limit up to 2 instrdduction at most.
5943     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5944     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5945 			      Insn);
5946     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5947     IsLegal = Insn.size() <= Limit;
5948   }
5949 
5950   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5951                     << " imm value: "; Imm.dump(););
5952   return IsLegal;
5953 }
5954 
5955 //===----------------------------------------------------------------------===//
5956 //                          AArch64 Optimization Hooks
5957 //===----------------------------------------------------------------------===//
5958 
5959 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5960                            SDValue Operand, SelectionDAG &DAG,
5961                            int &ExtraSteps) {
5962   EVT VT = Operand.getValueType();
5963   if (ST->hasNEON() &&
5964       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5965        VT == MVT::f32 || VT == MVT::v1f32 ||
5966        VT == MVT::v2f32 || VT == MVT::v4f32)) {
5967     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5968       // For the reciprocal estimates, convergence is quadratic, so the number
5969       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
5970       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
5971       // the result for float (23 mantissa bits) is 2 and for double (52
5972       // mantissa bits) is 3.
5973       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5974 
5975     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5976   }
5977 
5978   return SDValue();
5979 }
5980 
5981 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5982                                                SelectionDAG &DAG, int Enabled,
5983                                                int &ExtraSteps,
5984                                                bool &UseOneConst,
5985                                                bool Reciprocal) const {
5986   if (Enabled == ReciprocalEstimate::Enabled ||
5987       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5988     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5989                                        DAG, ExtraSteps)) {
5990       SDLoc DL(Operand);
5991       EVT VT = Operand.getValueType();
5992 
5993       SDNodeFlags Flags;
5994       Flags.setAllowReassociation(true);
5995 
5996       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5997       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5998       for (int i = ExtraSteps; i > 0; --i) {
5999         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6000                                    Flags);
6001         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6002         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6003       }
6004       if (!Reciprocal) {
6005         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6006                                       VT);
6007         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6008         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6009 
6010         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6011         // Correct the result if the operand is 0.0.
6012         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6013                                VT, Eq, Operand, Estimate);
6014       }
6015 
6016       ExtraSteps = 0;
6017       return Estimate;
6018     }
6019 
6020   return SDValue();
6021 }
6022 
6023 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6024                                                 SelectionDAG &DAG, int Enabled,
6025                                                 int &ExtraSteps) const {
6026   if (Enabled == ReciprocalEstimate::Enabled)
6027     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6028                                        DAG, ExtraSteps)) {
6029       SDLoc DL(Operand);
6030       EVT VT = Operand.getValueType();
6031 
6032       SDNodeFlags Flags;
6033       Flags.setAllowReassociation(true);
6034 
6035       // Newton reciprocal iteration: E * (2 - X * E)
6036       // AArch64 reciprocal iteration instruction: (2 - M * N)
6037       for (int i = ExtraSteps; i > 0; --i) {
6038         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6039                                    Estimate, Flags);
6040         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6041       }
6042 
6043       ExtraSteps = 0;
6044       return Estimate;
6045     }
6046 
6047   return SDValue();
6048 }
6049 
6050 //===----------------------------------------------------------------------===//
6051 //                          AArch64 Inline Assembly Support
6052 //===----------------------------------------------------------------------===//
6053 
6054 // Table of Constraints
6055 // TODO: This is the current set of constraints supported by ARM for the
6056 // compiler, not all of them may make sense.
6057 //
6058 // r - A general register
6059 // w - An FP/SIMD register of some size in the range v0-v31
6060 // x - An FP/SIMD register of some size in the range v0-v15
6061 // I - Constant that can be used with an ADD instruction
6062 // J - Constant that can be used with a SUB instruction
6063 // K - Constant that can be used with a 32-bit logical instruction
6064 // L - Constant that can be used with a 64-bit logical instruction
6065 // M - Constant that can be used as a 32-bit MOV immediate
6066 // N - Constant that can be used as a 64-bit MOV immediate
6067 // Q - A memory reference with base register and no offset
6068 // S - A symbolic address
6069 // Y - Floating point constant zero
6070 // Z - Integer constant zero
6071 //
6072 //   Note that general register operands will be output using their 64-bit x
6073 // register name, whatever the size of the variable, unless the asm operand
6074 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6075 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6076 // %q modifier.
6077 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6078   // At this point, we have to lower this constraint to something else, so we
6079   // lower it to an "r" or "w". However, by doing this we will force the result
6080   // to be in register, while the X constraint is much more permissive.
6081   //
6082   // Although we are correct (we are free to emit anything, without
6083   // constraints), we might break use cases that would expect us to be more
6084   // efficient and emit something else.
6085   if (!Subtarget->hasFPARMv8())
6086     return "r";
6087 
6088   if (ConstraintVT.isFloatingPoint())
6089     return "w";
6090 
6091   if (ConstraintVT.isVector() &&
6092      (ConstraintVT.getSizeInBits() == 64 ||
6093       ConstraintVT.getSizeInBits() == 128))
6094     return "w";
6095 
6096   return "r";
6097 }
6098 
6099 enum PredicateConstraint {
6100   Upl,
6101   Upa,
6102   Invalid
6103 };
6104 
6105 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6106   PredicateConstraint P = PredicateConstraint::Invalid;
6107   if (Constraint == "Upa")
6108     P = PredicateConstraint::Upa;
6109   if (Constraint == "Upl")
6110     P = PredicateConstraint::Upl;
6111   return P;
6112 }
6113 
6114 /// getConstraintType - Given a constraint letter, return the type of
6115 /// constraint it is for this target.
6116 AArch64TargetLowering::ConstraintType
6117 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6118   if (Constraint.size() == 1) {
6119     switch (Constraint[0]) {
6120     default:
6121       break;
6122     case 'x':
6123     case 'w':
6124     case 'y':
6125       return C_RegisterClass;
6126     // An address with a single base register. Due to the way we
6127     // currently handle addresses it is the same as 'r'.
6128     case 'Q':
6129       return C_Memory;
6130     case 'I':
6131     case 'J':
6132     case 'K':
6133     case 'L':
6134     case 'M':
6135     case 'N':
6136     case 'Y':
6137     case 'Z':
6138       return C_Immediate;
6139     case 'z':
6140     case 'S': // A symbolic address
6141       return C_Other;
6142     }
6143   } else if (parsePredicateConstraint(Constraint) !=
6144              PredicateConstraint::Invalid)
6145       return C_RegisterClass;
6146   return TargetLowering::getConstraintType(Constraint);
6147 }
6148 
6149 /// Examine constraint type and operand type and determine a weight value.
6150 /// This object must already have been set up with the operand type
6151 /// and the current alternative constraint selected.
6152 TargetLowering::ConstraintWeight
6153 AArch64TargetLowering::getSingleConstraintMatchWeight(
6154     AsmOperandInfo &info, const char *constraint) const {
6155   ConstraintWeight weight = CW_Invalid;
6156   Value *CallOperandVal = info.CallOperandVal;
6157   // If we don't have a value, we can't do a match,
6158   // but allow it at the lowest weight.
6159   if (!CallOperandVal)
6160     return CW_Default;
6161   Type *type = CallOperandVal->getType();
6162   // Look at the constraint type.
6163   switch (*constraint) {
6164   default:
6165     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6166     break;
6167   case 'x':
6168   case 'w':
6169   case 'y':
6170     if (type->isFloatingPointTy() || type->isVectorTy())
6171       weight = CW_Register;
6172     break;
6173   case 'z':
6174     weight = CW_Constant;
6175     break;
6176   case 'U':
6177     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6178       weight = CW_Register;
6179     break;
6180   }
6181   return weight;
6182 }
6183 
6184 std::pair<unsigned, const TargetRegisterClass *>
6185 AArch64TargetLowering::getRegForInlineAsmConstraint(
6186     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6187   if (Constraint.size() == 1) {
6188     switch (Constraint[0]) {
6189     case 'r':
6190       if (VT.getSizeInBits() == 64)
6191         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6192       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6193     case 'w':
6194       if (!Subtarget->hasFPARMv8())
6195         break;
6196       if (VT.isScalableVector())
6197         return std::make_pair(0U, &AArch64::ZPRRegClass);
6198       if (VT.getSizeInBits() == 16)
6199         return std::make_pair(0U, &AArch64::FPR16RegClass);
6200       if (VT.getSizeInBits() == 32)
6201         return std::make_pair(0U, &AArch64::FPR32RegClass);
6202       if (VT.getSizeInBits() == 64)
6203         return std::make_pair(0U, &AArch64::FPR64RegClass);
6204       if (VT.getSizeInBits() == 128)
6205         return std::make_pair(0U, &AArch64::FPR128RegClass);
6206       break;
6207     // The instructions that this constraint is designed for can
6208     // only take 128-bit registers so just use that regclass.
6209     case 'x':
6210       if (!Subtarget->hasFPARMv8())
6211         break;
6212       if (VT.isScalableVector())
6213         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6214       if (VT.getSizeInBits() == 128)
6215         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6216       break;
6217     case 'y':
6218       if (!Subtarget->hasFPARMv8())
6219         break;
6220       if (VT.isScalableVector())
6221         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6222       break;
6223     }
6224   } else {
6225     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6226     if (PC != PredicateConstraint::Invalid) {
6227       assert(VT.isScalableVector());
6228       bool restricted = (PC == PredicateConstraint::Upl);
6229       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6230                           : std::make_pair(0U, &AArch64::PPRRegClass);
6231     }
6232   }
6233   if (StringRef("{cc}").equals_lower(Constraint))
6234     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6235 
6236   // Use the default implementation in TargetLowering to convert the register
6237   // constraint into a member of a register class.
6238   std::pair<unsigned, const TargetRegisterClass *> Res;
6239   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6240 
6241   // Not found as a standard register?
6242   if (!Res.second) {
6243     unsigned Size = Constraint.size();
6244     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6245         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6246       int RegNo;
6247       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6248       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6249         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6250         // By default we'll emit v0-v31 for this unless there's a modifier where
6251         // we'll emit the correct register as well.
6252         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6253           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6254           Res.second = &AArch64::FPR64RegClass;
6255         } else {
6256           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6257           Res.second = &AArch64::FPR128RegClass;
6258         }
6259       }
6260     }
6261   }
6262 
6263   if (Res.second && !Subtarget->hasFPARMv8() &&
6264       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6265       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6266     return std::make_pair(0U, nullptr);
6267 
6268   return Res;
6269 }
6270 
6271 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6272 /// vector.  If it is invalid, don't add anything to Ops.
6273 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6274     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6275     SelectionDAG &DAG) const {
6276   SDValue Result;
6277 
6278   // Currently only support length 1 constraints.
6279   if (Constraint.length() != 1)
6280     return;
6281 
6282   char ConstraintLetter = Constraint[0];
6283   switch (ConstraintLetter) {
6284   default:
6285     break;
6286 
6287   // This set of constraints deal with valid constants for various instructions.
6288   // Validate and return a target constant for them if we can.
6289   case 'z': {
6290     // 'z' maps to xzr or wzr so it needs an input of 0.
6291     if (!isNullConstant(Op))
6292       return;
6293 
6294     if (Op.getValueType() == MVT::i64)
6295       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6296     else
6297       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6298     break;
6299   }
6300   case 'S': {
6301     // An absolute symbolic address or label reference.
6302     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6303       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6304                                           GA->getValueType(0));
6305     } else if (const BlockAddressSDNode *BA =
6306                    dyn_cast<BlockAddressSDNode>(Op)) {
6307       Result =
6308           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6309     } else if (const ExternalSymbolSDNode *ES =
6310                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6311       Result =
6312           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6313     } else
6314       return;
6315     break;
6316   }
6317 
6318   case 'I':
6319   case 'J':
6320   case 'K':
6321   case 'L':
6322   case 'M':
6323   case 'N':
6324     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6325     if (!C)
6326       return;
6327 
6328     // Grab the value and do some validation.
6329     uint64_t CVal = C->getZExtValue();
6330     switch (ConstraintLetter) {
6331     // The I constraint applies only to simple ADD or SUB immediate operands:
6332     // i.e. 0 to 4095 with optional shift by 12
6333     // The J constraint applies only to ADD or SUB immediates that would be
6334     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6335     // instruction [or vice versa], in other words -1 to -4095 with optional
6336     // left shift by 12.
6337     case 'I':
6338       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6339         break;
6340       return;
6341     case 'J': {
6342       uint64_t NVal = -C->getSExtValue();
6343       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6344         CVal = C->getSExtValue();
6345         break;
6346       }
6347       return;
6348     }
6349     // The K and L constraints apply *only* to logical immediates, including
6350     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6351     // been removed and MOV should be used). So these constraints have to
6352     // distinguish between bit patterns that are valid 32-bit or 64-bit
6353     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6354     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6355     // versa.
6356     case 'K':
6357       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6358         break;
6359       return;
6360     case 'L':
6361       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6362         break;
6363       return;
6364     // The M and N constraints are a superset of K and L respectively, for use
6365     // with the MOV (immediate) alias. As well as the logical immediates they
6366     // also match 32 or 64-bit immediates that can be loaded either using a
6367     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6368     // (M) or 64-bit 0x1234000000000000 (N) etc.
6369     // As a note some of this code is liberally stolen from the asm parser.
6370     case 'M': {
6371       if (!isUInt<32>(CVal))
6372         return;
6373       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6374         break;
6375       if ((CVal & 0xFFFF) == CVal)
6376         break;
6377       if ((CVal & 0xFFFF0000ULL) == CVal)
6378         break;
6379       uint64_t NCVal = ~(uint32_t)CVal;
6380       if ((NCVal & 0xFFFFULL) == NCVal)
6381         break;
6382       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6383         break;
6384       return;
6385     }
6386     case 'N': {
6387       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6388         break;
6389       if ((CVal & 0xFFFFULL) == CVal)
6390         break;
6391       if ((CVal & 0xFFFF0000ULL) == CVal)
6392         break;
6393       if ((CVal & 0xFFFF00000000ULL) == CVal)
6394         break;
6395       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6396         break;
6397       uint64_t NCVal = ~CVal;
6398       if ((NCVal & 0xFFFFULL) == NCVal)
6399         break;
6400       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6401         break;
6402       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6403         break;
6404       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6405         break;
6406       return;
6407     }
6408     default:
6409       return;
6410     }
6411 
6412     // All assembler immediates are 64-bit integers.
6413     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6414     break;
6415   }
6416 
6417   if (Result.getNode()) {
6418     Ops.push_back(Result);
6419     return;
6420   }
6421 
6422   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6423 }
6424 
6425 //===----------------------------------------------------------------------===//
6426 //                     AArch64 Advanced SIMD Support
6427 //===----------------------------------------------------------------------===//
6428 
6429 /// WidenVector - Given a value in the V64 register class, produce the
6430 /// equivalent value in the V128 register class.
6431 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6432   EVT VT = V64Reg.getValueType();
6433   unsigned NarrowSize = VT.getVectorNumElements();
6434   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6435   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6436   SDLoc DL(V64Reg);
6437 
6438   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6439                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6440 }
6441 
6442 /// getExtFactor - Determine the adjustment factor for the position when
6443 /// generating an "extract from vector registers" instruction.
6444 static unsigned getExtFactor(SDValue &V) {
6445   EVT EltType = V.getValueType().getVectorElementType();
6446   return EltType.getSizeInBits() / 8;
6447 }
6448 
6449 /// NarrowVector - Given a value in the V128 register class, produce the
6450 /// equivalent value in the V64 register class.
6451 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6452   EVT VT = V128Reg.getValueType();
6453   unsigned WideSize = VT.getVectorNumElements();
6454   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6455   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6456   SDLoc DL(V128Reg);
6457 
6458   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6459 }
6460 
6461 // Gather data to see if the operation can be modelled as a
6462 // shuffle in combination with VEXTs.
6463 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6464                                                   SelectionDAG &DAG) const {
6465   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6466   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6467   SDLoc dl(Op);
6468   EVT VT = Op.getValueType();
6469   unsigned NumElts = VT.getVectorNumElements();
6470 
6471   struct ShuffleSourceInfo {
6472     SDValue Vec;
6473     unsigned MinElt;
6474     unsigned MaxElt;
6475 
6476     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6477     // be compatible with the shuffle we intend to construct. As a result
6478     // ShuffleVec will be some sliding window into the original Vec.
6479     SDValue ShuffleVec;
6480 
6481     // Code should guarantee that element i in Vec starts at element "WindowBase
6482     // + i * WindowScale in ShuffleVec".
6483     int WindowBase;
6484     int WindowScale;
6485 
6486     ShuffleSourceInfo(SDValue Vec)
6487       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6488           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6489 
6490     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6491   };
6492 
6493   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6494   // node.
6495   SmallVector<ShuffleSourceInfo, 2> Sources;
6496   for (unsigned i = 0; i < NumElts; ++i) {
6497     SDValue V = Op.getOperand(i);
6498     if (V.isUndef())
6499       continue;
6500     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6501              !isa<ConstantSDNode>(V.getOperand(1))) {
6502       LLVM_DEBUG(
6503           dbgs() << "Reshuffle failed: "
6504                     "a shuffle can only come from building a vector from "
6505                     "various elements of other vectors, provided their "
6506                     "indices are constant\n");
6507       return SDValue();
6508     }
6509 
6510     // Add this element source to the list if it's not already there.
6511     SDValue SourceVec = V.getOperand(0);
6512     auto Source = find(Sources, SourceVec);
6513     if (Source == Sources.end())
6514       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6515 
6516     // Update the minimum and maximum lane number seen.
6517     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6518     Source->MinElt = std::min(Source->MinElt, EltNo);
6519     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6520   }
6521 
6522   if (Sources.size() > 2) {
6523     LLVM_DEBUG(
6524         dbgs() << "Reshuffle failed: currently only do something sane when at "
6525                   "most two source vectors are involved\n");
6526     return SDValue();
6527   }
6528 
6529   // Find out the smallest element size among result and two sources, and use
6530   // it as element size to build the shuffle_vector.
6531   EVT SmallestEltTy = VT.getVectorElementType();
6532   for (auto &Source : Sources) {
6533     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6534     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6535       SmallestEltTy = SrcEltTy;
6536     }
6537   }
6538   unsigned ResMultiplier =
6539       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6540   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6541   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6542 
6543   // If the source vector is too wide or too narrow, we may nevertheless be able
6544   // to construct a compatible shuffle either by concatenating it with UNDEF or
6545   // extracting a suitable range of elements.
6546   for (auto &Src : Sources) {
6547     EVT SrcVT = Src.ShuffleVec.getValueType();
6548 
6549     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6550       continue;
6551 
6552     // This stage of the search produces a source with the same element type as
6553     // the original, but with a total width matching the BUILD_VECTOR output.
6554     EVT EltVT = SrcVT.getVectorElementType();
6555     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6556     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6557 
6558     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6559       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6560       // We can pad out the smaller vector for free, so if it's part of a
6561       // shuffle...
6562       Src.ShuffleVec =
6563           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6564                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6565       continue;
6566     }
6567 
6568     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6569 
6570     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6571       LLVM_DEBUG(
6572           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6573       return SDValue();
6574     }
6575 
6576     if (Src.MinElt >= NumSrcElts) {
6577       // The extraction can just take the second half
6578       Src.ShuffleVec =
6579           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6580                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6581       Src.WindowBase = -NumSrcElts;
6582     } else if (Src.MaxElt < NumSrcElts) {
6583       // The extraction can just take the first half
6584       Src.ShuffleVec =
6585           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6586                       DAG.getConstant(0, dl, MVT::i64));
6587     } else {
6588       // An actual VEXT is needed
6589       SDValue VEXTSrc1 =
6590           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6591                       DAG.getConstant(0, dl, MVT::i64));
6592       SDValue VEXTSrc2 =
6593           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6594                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6595       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6596 
6597       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6598                                    VEXTSrc2,
6599                                    DAG.getConstant(Imm, dl, MVT::i32));
6600       Src.WindowBase = -Src.MinElt;
6601     }
6602   }
6603 
6604   // Another possible incompatibility occurs from the vector element types. We
6605   // can fix this by bitcasting the source vectors to the same type we intend
6606   // for the shuffle.
6607   for (auto &Src : Sources) {
6608     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6609     if (SrcEltTy == SmallestEltTy)
6610       continue;
6611     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6612     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6613     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6614     Src.WindowBase *= Src.WindowScale;
6615   }
6616 
6617   // Final sanity check before we try to actually produce a shuffle.
6618   LLVM_DEBUG(for (auto Src
6619                   : Sources)
6620                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6621 
6622   // The stars all align, our next step is to produce the mask for the shuffle.
6623   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6624   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6625   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6626     SDValue Entry = Op.getOperand(i);
6627     if (Entry.isUndef())
6628       continue;
6629 
6630     auto Src = find(Sources, Entry.getOperand(0));
6631     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6632 
6633     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6634     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6635     // segment.
6636     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6637     int BitsDefined =
6638         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6639     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6640 
6641     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6642     // starting at the appropriate offset.
6643     int *LaneMask = &Mask[i * ResMultiplier];
6644 
6645     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6646     ExtractBase += NumElts * (Src - Sources.begin());
6647     for (int j = 0; j < LanesDefined; ++j)
6648       LaneMask[j] = ExtractBase + j;
6649   }
6650 
6651   // Final check before we try to produce nonsense...
6652   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6653     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6654     return SDValue();
6655   }
6656 
6657   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6658   for (unsigned i = 0; i < Sources.size(); ++i)
6659     ShuffleOps[i] = Sources[i].ShuffleVec;
6660 
6661   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6662                                          ShuffleOps[1], Mask);
6663   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6664 
6665   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6666              dbgs() << "Reshuffle, creating node: "; V.dump(););
6667 
6668   return V;
6669 }
6670 
6671 // check if an EXT instruction can handle the shuffle mask when the
6672 // vector sources of the shuffle are the same.
6673 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6674   unsigned NumElts = VT.getVectorNumElements();
6675 
6676   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6677   if (M[0] < 0)
6678     return false;
6679 
6680   Imm = M[0];
6681 
6682   // If this is a VEXT shuffle, the immediate value is the index of the first
6683   // element.  The other shuffle indices must be the successive elements after
6684   // the first one.
6685   unsigned ExpectedElt = Imm;
6686   for (unsigned i = 1; i < NumElts; ++i) {
6687     // Increment the expected index.  If it wraps around, just follow it
6688     // back to index zero and keep going.
6689     ++ExpectedElt;
6690     if (ExpectedElt == NumElts)
6691       ExpectedElt = 0;
6692 
6693     if (M[i] < 0)
6694       continue; // ignore UNDEF indices
6695     if (ExpectedElt != static_cast<unsigned>(M[i]))
6696       return false;
6697   }
6698 
6699   return true;
6700 }
6701 
6702 // check if an EXT instruction can handle the shuffle mask when the
6703 // vector sources of the shuffle are different.
6704 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6705                       unsigned &Imm) {
6706   // Look for the first non-undef element.
6707   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6708 
6709   // Benefit form APInt to handle overflow when calculating expected element.
6710   unsigned NumElts = VT.getVectorNumElements();
6711   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6712   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6713   // The following shuffle indices must be the successive elements after the
6714   // first real element.
6715   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6716       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6717   if (FirstWrongElt != M.end())
6718     return false;
6719 
6720   // The index of an EXT is the first element if it is not UNDEF.
6721   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6722   // value of the first element.  E.g.
6723   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6724   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6725   // ExpectedElt is the last mask index plus 1.
6726   Imm = ExpectedElt.getZExtValue();
6727 
6728   // There are two difference cases requiring to reverse input vectors.
6729   // For example, for vector <4 x i32> we have the following cases,
6730   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6731   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6732   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6733   // to reverse two input vectors.
6734   if (Imm < NumElts)
6735     ReverseEXT = true;
6736   else
6737     Imm -= NumElts;
6738 
6739   return true;
6740 }
6741 
6742 /// isREVMask - Check if a vector shuffle corresponds to a REV
6743 /// instruction with the specified blocksize.  (The order of the elements
6744 /// within each block of the vector is reversed.)
6745 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6746   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6747          "Only possible block sizes for REV are: 16, 32, 64");
6748 
6749   unsigned EltSz = VT.getScalarSizeInBits();
6750   if (EltSz == 64)
6751     return false;
6752 
6753   unsigned NumElts = VT.getVectorNumElements();
6754   unsigned BlockElts = M[0] + 1;
6755   // If the first shuffle index is UNDEF, be optimistic.
6756   if (M[0] < 0)
6757     BlockElts = BlockSize / EltSz;
6758 
6759   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6760     return false;
6761 
6762   for (unsigned i = 0; i < NumElts; ++i) {
6763     if (M[i] < 0)
6764       continue; // ignore UNDEF indices
6765     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6766       return false;
6767   }
6768 
6769   return true;
6770 }
6771 
6772 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6773   unsigned NumElts = VT.getVectorNumElements();
6774   if (NumElts % 2 != 0)
6775     return false;
6776   WhichResult = (M[0] == 0 ? 0 : 1);
6777   unsigned Idx = WhichResult * NumElts / 2;
6778   for (unsigned i = 0; i != NumElts; i += 2) {
6779     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6780         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6781       return false;
6782     Idx += 1;
6783   }
6784 
6785   return true;
6786 }
6787 
6788 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6789   unsigned NumElts = VT.getVectorNumElements();
6790   WhichResult = (M[0] == 0 ? 0 : 1);
6791   for (unsigned i = 0; i != NumElts; ++i) {
6792     if (M[i] < 0)
6793       continue; // ignore UNDEF indices
6794     if ((unsigned)M[i] != 2 * i + WhichResult)
6795       return false;
6796   }
6797 
6798   return true;
6799 }
6800 
6801 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6802   unsigned NumElts = VT.getVectorNumElements();
6803   if (NumElts % 2 != 0)
6804     return false;
6805   WhichResult = (M[0] == 0 ? 0 : 1);
6806   for (unsigned i = 0; i < NumElts; i += 2) {
6807     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6808         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6809       return false;
6810   }
6811   return true;
6812 }
6813 
6814 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6815 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6816 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6817 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6818   unsigned NumElts = VT.getVectorNumElements();
6819   if (NumElts % 2 != 0)
6820     return false;
6821   WhichResult = (M[0] == 0 ? 0 : 1);
6822   unsigned Idx = WhichResult * NumElts / 2;
6823   for (unsigned i = 0; i != NumElts; i += 2) {
6824     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6825         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6826       return false;
6827     Idx += 1;
6828   }
6829 
6830   return true;
6831 }
6832 
6833 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6834 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6835 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6836 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6837   unsigned Half = VT.getVectorNumElements() / 2;
6838   WhichResult = (M[0] == 0 ? 0 : 1);
6839   for (unsigned j = 0; j != 2; ++j) {
6840     unsigned Idx = WhichResult;
6841     for (unsigned i = 0; i != Half; ++i) {
6842       int MIdx = M[i + j * Half];
6843       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6844         return false;
6845       Idx += 2;
6846     }
6847   }
6848 
6849   return true;
6850 }
6851 
6852 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6853 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6854 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6855 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6856   unsigned NumElts = VT.getVectorNumElements();
6857   if (NumElts % 2 != 0)
6858     return false;
6859   WhichResult = (M[0] == 0 ? 0 : 1);
6860   for (unsigned i = 0; i < NumElts; i += 2) {
6861     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6862         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6863       return false;
6864   }
6865   return true;
6866 }
6867 
6868 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6869                       bool &DstIsLeft, int &Anomaly) {
6870   if (M.size() != static_cast<size_t>(NumInputElements))
6871     return false;
6872 
6873   int NumLHSMatch = 0, NumRHSMatch = 0;
6874   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6875 
6876   for (int i = 0; i < NumInputElements; ++i) {
6877     if (M[i] == -1) {
6878       ++NumLHSMatch;
6879       ++NumRHSMatch;
6880       continue;
6881     }
6882 
6883     if (M[i] == i)
6884       ++NumLHSMatch;
6885     else
6886       LastLHSMismatch = i;
6887 
6888     if (M[i] == i + NumInputElements)
6889       ++NumRHSMatch;
6890     else
6891       LastRHSMismatch = i;
6892   }
6893 
6894   if (NumLHSMatch == NumInputElements - 1) {
6895     DstIsLeft = true;
6896     Anomaly = LastLHSMismatch;
6897     return true;
6898   } else if (NumRHSMatch == NumInputElements - 1) {
6899     DstIsLeft = false;
6900     Anomaly = LastRHSMismatch;
6901     return true;
6902   }
6903 
6904   return false;
6905 }
6906 
6907 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6908   if (VT.getSizeInBits() != 128)
6909     return false;
6910 
6911   unsigned NumElts = VT.getVectorNumElements();
6912 
6913   for (int I = 0, E = NumElts / 2; I != E; I++) {
6914     if (Mask[I] != I)
6915       return false;
6916   }
6917 
6918   int Offset = NumElts / 2;
6919   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6920     if (Mask[I] != I + SplitLHS * Offset)
6921       return false;
6922   }
6923 
6924   return true;
6925 }
6926 
6927 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6928   SDLoc DL(Op);
6929   EVT VT = Op.getValueType();
6930   SDValue V0 = Op.getOperand(0);
6931   SDValue V1 = Op.getOperand(1);
6932   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6933 
6934   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6935       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6936     return SDValue();
6937 
6938   bool SplitV0 = V0.getValueSizeInBits() == 128;
6939 
6940   if (!isConcatMask(Mask, VT, SplitV0))
6941     return SDValue();
6942 
6943   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
6944   if (SplitV0) {
6945     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6946                      DAG.getConstant(0, DL, MVT::i64));
6947   }
6948   if (V1.getValueSizeInBits() == 128) {
6949     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6950                      DAG.getConstant(0, DL, MVT::i64));
6951   }
6952   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6953 }
6954 
6955 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6956 /// the specified operations to build the shuffle.
6957 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6958                                       SDValue RHS, SelectionDAG &DAG,
6959                                       const SDLoc &dl) {
6960   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6961   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6962   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6963 
6964   enum {
6965     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6966     OP_VREV,
6967     OP_VDUP0,
6968     OP_VDUP1,
6969     OP_VDUP2,
6970     OP_VDUP3,
6971     OP_VEXT1,
6972     OP_VEXT2,
6973     OP_VEXT3,
6974     OP_VUZPL, // VUZP, left result
6975     OP_VUZPR, // VUZP, right result
6976     OP_VZIPL, // VZIP, left result
6977     OP_VZIPR, // VZIP, right result
6978     OP_VTRNL, // VTRN, left result
6979     OP_VTRNR  // VTRN, right result
6980   };
6981 
6982   if (OpNum == OP_COPY) {
6983     if (LHSID == (1 * 9 + 2) * 9 + 3)
6984       return LHS;
6985     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6986     return RHS;
6987   }
6988 
6989   SDValue OpLHS, OpRHS;
6990   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6991   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6992   EVT VT = OpLHS.getValueType();
6993 
6994   switch (OpNum) {
6995   default:
6996     llvm_unreachable("Unknown shuffle opcode!");
6997   case OP_VREV:
6998     // VREV divides the vector in half and swaps within the half.
6999     if (VT.getVectorElementType() == MVT::i32 ||
7000         VT.getVectorElementType() == MVT::f32)
7001       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7002     // vrev <4 x i16> -> REV32
7003     if (VT.getVectorElementType() == MVT::i16 ||
7004         VT.getVectorElementType() == MVT::f16)
7005       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7006     // vrev <4 x i8> -> REV16
7007     assert(VT.getVectorElementType() == MVT::i8);
7008     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7009   case OP_VDUP0:
7010   case OP_VDUP1:
7011   case OP_VDUP2:
7012   case OP_VDUP3: {
7013     EVT EltTy = VT.getVectorElementType();
7014     unsigned Opcode;
7015     if (EltTy == MVT::i8)
7016       Opcode = AArch64ISD::DUPLANE8;
7017     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
7018       Opcode = AArch64ISD::DUPLANE16;
7019     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7020       Opcode = AArch64ISD::DUPLANE32;
7021     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7022       Opcode = AArch64ISD::DUPLANE64;
7023     else
7024       llvm_unreachable("Invalid vector element type?");
7025 
7026     if (VT.getSizeInBits() == 64)
7027       OpLHS = WidenVector(OpLHS, DAG);
7028     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7029     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7030   }
7031   case OP_VEXT1:
7032   case OP_VEXT2:
7033   case OP_VEXT3: {
7034     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7035     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7036                        DAG.getConstant(Imm, dl, MVT::i32));
7037   }
7038   case OP_VUZPL:
7039     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7040                        OpRHS);
7041   case OP_VUZPR:
7042     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7043                        OpRHS);
7044   case OP_VZIPL:
7045     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7046                        OpRHS);
7047   case OP_VZIPR:
7048     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7049                        OpRHS);
7050   case OP_VTRNL:
7051     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7052                        OpRHS);
7053   case OP_VTRNR:
7054     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7055                        OpRHS);
7056   }
7057 }
7058 
7059 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7060                            SelectionDAG &DAG) {
7061   // Check to see if we can use the TBL instruction.
7062   SDValue V1 = Op.getOperand(0);
7063   SDValue V2 = Op.getOperand(1);
7064   SDLoc DL(Op);
7065 
7066   EVT EltVT = Op.getValueType().getVectorElementType();
7067   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7068 
7069   SmallVector<SDValue, 8> TBLMask;
7070   for (int Val : ShuffleMask) {
7071     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7072       unsigned Offset = Byte + Val * BytesPerElt;
7073       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7074     }
7075   }
7076 
7077   MVT IndexVT = MVT::v8i8;
7078   unsigned IndexLen = 8;
7079   if (Op.getValueSizeInBits() == 128) {
7080     IndexVT = MVT::v16i8;
7081     IndexLen = 16;
7082   }
7083 
7084   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7085   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7086 
7087   SDValue Shuffle;
7088   if (V2.getNode()->isUndef()) {
7089     if (IndexLen == 8)
7090       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7091     Shuffle = DAG.getNode(
7092         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7093         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7094         DAG.getBuildVector(IndexVT, DL,
7095                            makeArrayRef(TBLMask.data(), IndexLen)));
7096   } else {
7097     if (IndexLen == 8) {
7098       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7099       Shuffle = DAG.getNode(
7100           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7101           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7102           DAG.getBuildVector(IndexVT, DL,
7103                              makeArrayRef(TBLMask.data(), IndexLen)));
7104     } else {
7105       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7106       // cannot currently represent the register constraints on the input
7107       // table registers.
7108       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7109       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7110       //                   IndexLen));
7111       Shuffle = DAG.getNode(
7112           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7113           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7114           V2Cst, DAG.getBuildVector(IndexVT, DL,
7115                                     makeArrayRef(TBLMask.data(), IndexLen)));
7116     }
7117   }
7118   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7119 }
7120 
7121 static unsigned getDUPLANEOp(EVT EltType) {
7122   if (EltType == MVT::i8)
7123     return AArch64ISD::DUPLANE8;
7124   if (EltType == MVT::i16 || EltType == MVT::f16)
7125     return AArch64ISD::DUPLANE16;
7126   if (EltType == MVT::i32 || EltType == MVT::f32)
7127     return AArch64ISD::DUPLANE32;
7128   if (EltType == MVT::i64 || EltType == MVT::f64)
7129     return AArch64ISD::DUPLANE64;
7130 
7131   llvm_unreachable("Invalid vector element type?");
7132 }
7133 
7134 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7135                                                    SelectionDAG &DAG) const {
7136   SDLoc dl(Op);
7137   EVT VT = Op.getValueType();
7138 
7139   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7140 
7141   // Convert shuffles that are directly supported on NEON to target-specific
7142   // DAG nodes, instead of keeping them as shuffles and matching them again
7143   // during code selection.  This is more efficient and avoids the possibility
7144   // of inconsistencies between legalization and selection.
7145   ArrayRef<int> ShuffleMask = SVN->getMask();
7146 
7147   SDValue V1 = Op.getOperand(0);
7148   SDValue V2 = Op.getOperand(1);
7149 
7150   if (SVN->isSplat()) {
7151     int Lane = SVN->getSplatIndex();
7152     // If this is undef splat, generate it via "just" vdup, if possible.
7153     if (Lane == -1)
7154       Lane = 0;
7155 
7156     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7157       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7158                          V1.getOperand(0));
7159     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7160     // constant. If so, we can just reference the lane's definition directly.
7161     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7162         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7163       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7164 
7165     // Otherwise, duplicate from the lane of the input vector.
7166     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7167 
7168     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7169     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7170       // Match: dup (bitcast (extract_subv X, C)), LaneC
7171       if (BitCast.getOpcode() != ISD::BITCAST ||
7172           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7173         return false;
7174 
7175       // The extract index must align in the destination type. That may not
7176       // happen if the bitcast is from narrow to wide type.
7177       SDValue Extract = BitCast.getOperand(0);
7178       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7179       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7180       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7181       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7182       if (ExtIdxInBits % CastedEltBitWidth != 0)
7183         return false;
7184 
7185       // Update the lane value by offsetting with the scaled extract index.
7186       LaneC += ExtIdxInBits / CastedEltBitWidth;
7187 
7188       // Determine the casted vector type of the wide vector input.
7189       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7190       // Examples:
7191       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7192       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7193       unsigned SrcVecNumElts =
7194           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7195       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7196                                 SrcVecNumElts);
7197       return true;
7198     };
7199     MVT CastVT;
7200     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7201       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7202     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7203       // The lane is incremented by the index of the extract.
7204       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7205       Lane += V1.getConstantOperandVal(1);
7206       V1 = V1.getOperand(0);
7207     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7208       // The lane is decremented if we are splatting from the 2nd operand.
7209       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7210       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7211       Lane -= Idx * VT.getVectorNumElements() / 2;
7212       V1 = WidenVector(V1.getOperand(Idx), DAG);
7213     } else if (VT.getSizeInBits() == 64) {
7214       // Widen the operand to 128-bit register with undef.
7215       V1 = WidenVector(V1, DAG);
7216     }
7217     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7218   }
7219 
7220   if (isREVMask(ShuffleMask, VT, 64))
7221     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7222   if (isREVMask(ShuffleMask, VT, 32))
7223     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7224   if (isREVMask(ShuffleMask, VT, 16))
7225     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7226 
7227   bool ReverseEXT = false;
7228   unsigned Imm;
7229   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7230     if (ReverseEXT)
7231       std::swap(V1, V2);
7232     Imm *= getExtFactor(V1);
7233     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7234                        DAG.getConstant(Imm, dl, MVT::i32));
7235   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7236     Imm *= getExtFactor(V1);
7237     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7238                        DAG.getConstant(Imm, dl, MVT::i32));
7239   }
7240 
7241   unsigned WhichResult;
7242   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7243     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7244     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7245   }
7246   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7247     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7248     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7249   }
7250   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7251     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7252     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7253   }
7254 
7255   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7256     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7257     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7258   }
7259   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7260     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7261     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7262   }
7263   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7264     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7265     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7266   }
7267 
7268   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7269     return Concat;
7270 
7271   bool DstIsLeft;
7272   int Anomaly;
7273   int NumInputElements = V1.getValueType().getVectorNumElements();
7274   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7275     SDValue DstVec = DstIsLeft ? V1 : V2;
7276     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7277 
7278     SDValue SrcVec = V1;
7279     int SrcLane = ShuffleMask[Anomaly];
7280     if (SrcLane >= NumInputElements) {
7281       SrcVec = V2;
7282       SrcLane -= VT.getVectorNumElements();
7283     }
7284     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7285 
7286     EVT ScalarVT = VT.getVectorElementType();
7287 
7288     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7289       ScalarVT = MVT::i32;
7290 
7291     return DAG.getNode(
7292         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7293         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7294         DstLaneV);
7295   }
7296 
7297   // If the shuffle is not directly supported and it has 4 elements, use
7298   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7299   unsigned NumElts = VT.getVectorNumElements();
7300   if (NumElts == 4) {
7301     unsigned PFIndexes[4];
7302     for (unsigned i = 0; i != 4; ++i) {
7303       if (ShuffleMask[i] < 0)
7304         PFIndexes[i] = 8;
7305       else
7306         PFIndexes[i] = ShuffleMask[i];
7307     }
7308 
7309     // Compute the index in the perfect shuffle table.
7310     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7311                             PFIndexes[2] * 9 + PFIndexes[3];
7312     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7313     unsigned Cost = (PFEntry >> 30);
7314 
7315     if (Cost <= 4)
7316       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7317   }
7318 
7319   return GenerateTBL(Op, ShuffleMask, DAG);
7320 }
7321 
7322 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7323                                                  SelectionDAG &DAG) const {
7324   SDLoc dl(Op);
7325   EVT VT = Op.getValueType();
7326   EVT ElemVT = VT.getScalarType();
7327 
7328   SDValue SplatVal = Op.getOperand(0);
7329 
7330   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7331   // FPRs don't have this restriction.
7332   switch (ElemVT.getSimpleVT().SimpleTy) {
7333   case MVT::i8:
7334   case MVT::i16:
7335   case MVT::i32:
7336     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7337     return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7338   case MVT::i64:
7339     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7340     return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7341   case MVT::i1: {
7342     // The general case of i1.  There isn't any natural way to do this,
7343     // so we use some trickery with whilelo.
7344     // TODO: Add special cases for splat of constant true/false.
7345     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7346     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7347                            DAG.getValueType(MVT::i1));
7348     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7349                                        MVT::i64);
7350     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7351                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
7352   }
7353   // TODO: we can support float types, but haven't added patterns yet.
7354   case MVT::f16:
7355   case MVT::f32:
7356   case MVT::f64:
7357   default:
7358     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7359   }
7360 }
7361 
7362 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7363                                APInt &UndefBits) {
7364   EVT VT = BVN->getValueType(0);
7365   APInt SplatBits, SplatUndef;
7366   unsigned SplatBitSize;
7367   bool HasAnyUndefs;
7368   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7369     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7370 
7371     for (unsigned i = 0; i < NumSplats; ++i) {
7372       CnstBits <<= SplatBitSize;
7373       UndefBits <<= SplatBitSize;
7374       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7375       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7376     }
7377 
7378     return true;
7379   }
7380 
7381   return false;
7382 }
7383 
7384 // Try 64-bit splatted SIMD immediate.
7385 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7386                                  const APInt &Bits) {
7387   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7388     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7389     EVT VT = Op.getValueType();
7390     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7391 
7392     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7393       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7394 
7395       SDLoc dl(Op);
7396       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7397                                 DAG.getConstant(Value, dl, MVT::i32));
7398       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7399     }
7400   }
7401 
7402   return SDValue();
7403 }
7404 
7405 // Try 32-bit splatted SIMD immediate.
7406 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7407                                   const APInt &Bits,
7408                                   const SDValue *LHS = nullptr) {
7409   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7410     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7411     EVT VT = Op.getValueType();
7412     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7413     bool isAdvSIMDModImm = false;
7414     uint64_t Shift;
7415 
7416     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7417       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7418       Shift = 0;
7419     }
7420     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7421       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7422       Shift = 8;
7423     }
7424     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7425       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7426       Shift = 16;
7427     }
7428     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7429       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7430       Shift = 24;
7431     }
7432 
7433     if (isAdvSIMDModImm) {
7434       SDLoc dl(Op);
7435       SDValue Mov;
7436 
7437       if (LHS)
7438         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7439                           DAG.getConstant(Value, dl, MVT::i32),
7440                           DAG.getConstant(Shift, dl, MVT::i32));
7441       else
7442         Mov = DAG.getNode(NewOp, dl, MovTy,
7443                           DAG.getConstant(Value, dl, MVT::i32),
7444                           DAG.getConstant(Shift, dl, MVT::i32));
7445 
7446       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7447     }
7448   }
7449 
7450   return SDValue();
7451 }
7452 
7453 // Try 16-bit splatted SIMD immediate.
7454 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7455                                   const APInt &Bits,
7456                                   const SDValue *LHS = nullptr) {
7457   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7458     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7459     EVT VT = Op.getValueType();
7460     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7461     bool isAdvSIMDModImm = false;
7462     uint64_t Shift;
7463 
7464     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7465       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7466       Shift = 0;
7467     }
7468     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7469       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7470       Shift = 8;
7471     }
7472 
7473     if (isAdvSIMDModImm) {
7474       SDLoc dl(Op);
7475       SDValue Mov;
7476 
7477       if (LHS)
7478         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7479                           DAG.getConstant(Value, dl, MVT::i32),
7480                           DAG.getConstant(Shift, dl, MVT::i32));
7481       else
7482         Mov = DAG.getNode(NewOp, dl, MovTy,
7483                           DAG.getConstant(Value, dl, MVT::i32),
7484                           DAG.getConstant(Shift, dl, MVT::i32));
7485 
7486       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7487     }
7488   }
7489 
7490   return SDValue();
7491 }
7492 
7493 // Try 32-bit splatted SIMD immediate with shifted ones.
7494 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7495                                     SelectionDAG &DAG, const APInt &Bits) {
7496   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7497     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7498     EVT VT = Op.getValueType();
7499     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7500     bool isAdvSIMDModImm = false;
7501     uint64_t Shift;
7502 
7503     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7504       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7505       Shift = 264;
7506     }
7507     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7508       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7509       Shift = 272;
7510     }
7511 
7512     if (isAdvSIMDModImm) {
7513       SDLoc dl(Op);
7514       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7515                                 DAG.getConstant(Value, dl, MVT::i32),
7516                                 DAG.getConstant(Shift, dl, MVT::i32));
7517       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7518     }
7519   }
7520 
7521   return SDValue();
7522 }
7523 
7524 // Try 8-bit splatted SIMD immediate.
7525 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7526                                  const APInt &Bits) {
7527   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7528     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7529     EVT VT = Op.getValueType();
7530     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7531 
7532     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7533       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7534 
7535       SDLoc dl(Op);
7536       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7537                                 DAG.getConstant(Value, dl, MVT::i32));
7538       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7539     }
7540   }
7541 
7542   return SDValue();
7543 }
7544 
7545 // Try FP splatted SIMD immediate.
7546 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7547                                   const APInt &Bits) {
7548   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7549     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7550     EVT VT = Op.getValueType();
7551     bool isWide = (VT.getSizeInBits() == 128);
7552     MVT MovTy;
7553     bool isAdvSIMDModImm = false;
7554 
7555     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7556       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7557       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7558     }
7559     else if (isWide &&
7560              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7561       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7562       MovTy = MVT::v2f64;
7563     }
7564 
7565     if (isAdvSIMDModImm) {
7566       SDLoc dl(Op);
7567       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7568                                 DAG.getConstant(Value, dl, MVT::i32));
7569       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7570     }
7571   }
7572 
7573   return SDValue();
7574 }
7575 
7576 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7577 // consists of only the same constant int value, returned in reference arg
7578 // ConstVal
7579 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7580                                      uint64_t &ConstVal) {
7581   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7582   if (!Bvec)
7583     return false;
7584   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7585   if (!FirstElt)
7586     return false;
7587   EVT VT = Bvec->getValueType(0);
7588   unsigned NumElts = VT.getVectorNumElements();
7589   for (unsigned i = 1; i < NumElts; ++i)
7590     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7591       return false;
7592   ConstVal = FirstElt->getZExtValue();
7593   return true;
7594 }
7595 
7596 static unsigned getIntrinsicID(const SDNode *N) {
7597   unsigned Opcode = N->getOpcode();
7598   switch (Opcode) {
7599   default:
7600     return Intrinsic::not_intrinsic;
7601   case ISD::INTRINSIC_WO_CHAIN: {
7602     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7603     if (IID < Intrinsic::num_intrinsics)
7604       return IID;
7605     return Intrinsic::not_intrinsic;
7606   }
7607   }
7608 }
7609 
7610 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7611 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7612 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7613 // Also, logical shift right -> sri, with the same structure.
7614 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7615   EVT VT = N->getValueType(0);
7616 
7617   if (!VT.isVector())
7618     return SDValue();
7619 
7620   SDLoc DL(N);
7621 
7622   // Is the first op an AND?
7623   const SDValue And = N->getOperand(0);
7624   if (And.getOpcode() != ISD::AND)
7625     return SDValue();
7626 
7627   // Is the second op an shl or lshr?
7628   SDValue Shift = N->getOperand(1);
7629   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7630   // or AArch64ISD::VLSHR vector, #shift
7631   unsigned ShiftOpc = Shift.getOpcode();
7632   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7633     return SDValue();
7634   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7635 
7636   // Is the shift amount constant?
7637   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7638   if (!C2node)
7639     return SDValue();
7640 
7641   // Is the and mask vector all constant?
7642   uint64_t C1;
7643   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7644     return SDValue();
7645 
7646   // Is C1 == ~C2, taking into account how much one can shift elements of a
7647   // particular size?
7648   uint64_t C2 = C2node->getZExtValue();
7649   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7650   if (C2 > ElemSizeInBits)
7651     return SDValue();
7652   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7653   if ((C1 & ElemMask) != (~C2 & ElemMask))
7654     return SDValue();
7655 
7656   SDValue X = And.getOperand(0);
7657   SDValue Y = Shift.getOperand(0);
7658 
7659   unsigned Intrin =
7660       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7661   SDValue ResultSLI =
7662       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7663                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7664                   Shift.getOperand(1));
7665 
7666   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7667   LLVM_DEBUG(N->dump(&DAG));
7668   LLVM_DEBUG(dbgs() << "into: \n");
7669   LLVM_DEBUG(ResultSLI->dump(&DAG));
7670 
7671   ++NumShiftInserts;
7672   return ResultSLI;
7673 }
7674 
7675 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7676                                              SelectionDAG &DAG) const {
7677   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7678   if (EnableAArch64SlrGeneration) {
7679     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7680       return Res;
7681   }
7682 
7683   EVT VT = Op.getValueType();
7684 
7685   SDValue LHS = Op.getOperand(0);
7686   BuildVectorSDNode *BVN =
7687       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7688   if (!BVN) {
7689     // OR commutes, so try swapping the operands.
7690     LHS = Op.getOperand(1);
7691     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7692   }
7693   if (!BVN)
7694     return Op;
7695 
7696   APInt DefBits(VT.getSizeInBits(), 0);
7697   APInt UndefBits(VT.getSizeInBits(), 0);
7698   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7699     SDValue NewOp;
7700 
7701     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7702                                     DefBits, &LHS)) ||
7703         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7704                                     DefBits, &LHS)))
7705       return NewOp;
7706 
7707     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7708                                     UndefBits, &LHS)) ||
7709         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7710                                     UndefBits, &LHS)))
7711       return NewOp;
7712   }
7713 
7714   // We can always fall back to a non-immediate OR.
7715   return Op;
7716 }
7717 
7718 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7719 // be truncated to fit element width.
7720 static SDValue NormalizeBuildVector(SDValue Op,
7721                                     SelectionDAG &DAG) {
7722   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7723   SDLoc dl(Op);
7724   EVT VT = Op.getValueType();
7725   EVT EltTy= VT.getVectorElementType();
7726 
7727   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7728     return Op;
7729 
7730   SmallVector<SDValue, 16> Ops;
7731   for (SDValue Lane : Op->ops()) {
7732     // For integer vectors, type legalization would have promoted the
7733     // operands already. Otherwise, if Op is a floating-point splat
7734     // (with operands cast to integers), then the only possibilities
7735     // are constants and UNDEFs.
7736     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7737       APInt LowBits(EltTy.getSizeInBits(),
7738                     CstLane->getZExtValue());
7739       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7740     } else if (Lane.getNode()->isUndef()) {
7741       Lane = DAG.getUNDEF(MVT::i32);
7742     } else {
7743       assert(Lane.getValueType() == MVT::i32 &&
7744              "Unexpected BUILD_VECTOR operand type");
7745     }
7746     Ops.push_back(Lane);
7747   }
7748   return DAG.getBuildVector(VT, dl, Ops);
7749 }
7750 
7751 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7752   EVT VT = Op.getValueType();
7753 
7754   APInt DefBits(VT.getSizeInBits(), 0);
7755   APInt UndefBits(VT.getSizeInBits(), 0);
7756   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7757   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7758     SDValue NewOp;
7759     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7760         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7761         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7762         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7763         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7764         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7765       return NewOp;
7766 
7767     DefBits = ~DefBits;
7768     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7769         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7770         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7771       return NewOp;
7772 
7773     DefBits = UndefBits;
7774     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7775         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7776         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7777         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7778         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7779         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7780       return NewOp;
7781 
7782     DefBits = ~UndefBits;
7783     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7784         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7785         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7786       return NewOp;
7787   }
7788 
7789   return SDValue();
7790 }
7791 
7792 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7793                                                  SelectionDAG &DAG) const {
7794   EVT VT = Op.getValueType();
7795 
7796   // Try to build a simple constant vector.
7797   Op = NormalizeBuildVector(Op, DAG);
7798   if (VT.isInteger()) {
7799     // Certain vector constants, used to express things like logical NOT and
7800     // arithmetic NEG, are passed through unmodified.  This allows special
7801     // patterns for these operations to match, which will lower these constants
7802     // to whatever is proven necessary.
7803     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7804     if (BVN->isConstant())
7805       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7806         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7807         APInt Val(BitSize,
7808                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7809         if (Val.isNullValue() || Val.isAllOnesValue())
7810           return Op;
7811       }
7812   }
7813 
7814   if (SDValue V = ConstantBuildVector(Op, DAG))
7815     return V;
7816 
7817   // Scan through the operands to find some interesting properties we can
7818   // exploit:
7819   //   1) If only one value is used, we can use a DUP, or
7820   //   2) if only the low element is not undef, we can just insert that, or
7821   //   3) if only one constant value is used (w/ some non-constant lanes),
7822   //      we can splat the constant value into the whole vector then fill
7823   //      in the non-constant lanes.
7824   //   4) FIXME: If different constant values are used, but we can intelligently
7825   //             select the values we'll be overwriting for the non-constant
7826   //             lanes such that we can directly materialize the vector
7827   //             some other way (MOVI, e.g.), we can be sneaky.
7828   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7829   SDLoc dl(Op);
7830   unsigned NumElts = VT.getVectorNumElements();
7831   bool isOnlyLowElement = true;
7832   bool usesOnlyOneValue = true;
7833   bool usesOnlyOneConstantValue = true;
7834   bool isConstant = true;
7835   bool AllLanesExtractElt = true;
7836   unsigned NumConstantLanes = 0;
7837   SDValue Value;
7838   SDValue ConstantValue;
7839   for (unsigned i = 0; i < NumElts; ++i) {
7840     SDValue V = Op.getOperand(i);
7841     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7842       AllLanesExtractElt = false;
7843     if (V.isUndef())
7844       continue;
7845     if (i > 0)
7846       isOnlyLowElement = false;
7847     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7848       isConstant = false;
7849 
7850     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7851       ++NumConstantLanes;
7852       if (!ConstantValue.getNode())
7853         ConstantValue = V;
7854       else if (ConstantValue != V)
7855         usesOnlyOneConstantValue = false;
7856     }
7857 
7858     if (!Value.getNode())
7859       Value = V;
7860     else if (V != Value)
7861       usesOnlyOneValue = false;
7862   }
7863 
7864   if (!Value.getNode()) {
7865     LLVM_DEBUG(
7866         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7867     return DAG.getUNDEF(VT);
7868   }
7869 
7870   // Convert BUILD_VECTOR where all elements but the lowest are undef into
7871   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7872   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7873   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7874     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7875                          "SCALAR_TO_VECTOR node\n");
7876     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7877   }
7878 
7879   if (AllLanesExtractElt) {
7880     SDNode *Vector = nullptr;
7881     bool Even = false;
7882     bool Odd = false;
7883     // Check whether the extract elements match the Even pattern <0,2,4,...> or
7884     // the Odd pattern <1,3,5,...>.
7885     for (unsigned i = 0; i < NumElts; ++i) {
7886       SDValue V = Op.getOperand(i);
7887       const SDNode *N = V.getNode();
7888       if (!isa<ConstantSDNode>(N->getOperand(1)))
7889         break;
7890       SDValue N0 = N->getOperand(0);
7891 
7892       // All elements are extracted from the same vector.
7893       if (!Vector) {
7894         Vector = N0.getNode();
7895         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7896         // BUILD_VECTOR.
7897         if (VT.getVectorElementType() !=
7898             N0.getValueType().getVectorElementType())
7899           break;
7900       } else if (Vector != N0.getNode()) {
7901         Odd = false;
7902         Even = false;
7903         break;
7904       }
7905 
7906       // Extracted values are either at Even indices <0,2,4,...> or at Odd
7907       // indices <1,3,5,...>.
7908       uint64_t Val = N->getConstantOperandVal(1);
7909       if (Val == 2 * i) {
7910         Even = true;
7911         continue;
7912       }
7913       if (Val - 1 == 2 * i) {
7914         Odd = true;
7915         continue;
7916       }
7917 
7918       // Something does not match: abort.
7919       Odd = false;
7920       Even = false;
7921       break;
7922     }
7923     if (Even || Odd) {
7924       SDValue LHS =
7925           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7926                       DAG.getConstant(0, dl, MVT::i64));
7927       SDValue RHS =
7928           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7929                       DAG.getConstant(NumElts, dl, MVT::i64));
7930 
7931       if (Even && !Odd)
7932         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7933                            RHS);
7934       if (Odd && !Even)
7935         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7936                            RHS);
7937     }
7938   }
7939 
7940   // Use DUP for non-constant splats. For f32 constant splats, reduce to
7941   // i32 and try again.
7942   if (usesOnlyOneValue) {
7943     if (!isConstant) {
7944       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7945           Value.getValueType() != VT) {
7946         LLVM_DEBUG(
7947             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7948         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7949       }
7950 
7951       // This is actually a DUPLANExx operation, which keeps everything vectory.
7952 
7953       SDValue Lane = Value.getOperand(1);
7954       Value = Value.getOperand(0);
7955       if (Value.getValueSizeInBits() == 64) {
7956         LLVM_DEBUG(
7957             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7958                       "widening it\n");
7959         Value = WidenVector(Value, DAG);
7960       }
7961 
7962       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7963       return DAG.getNode(Opcode, dl, VT, Value, Lane);
7964     }
7965 
7966     if (VT.getVectorElementType().isFloatingPoint()) {
7967       SmallVector<SDValue, 8> Ops;
7968       EVT EltTy = VT.getVectorElementType();
7969       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7970               "Unsupported floating-point vector type");
7971       LLVM_DEBUG(
7972           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7973                     "BITCASTS, and try again\n");
7974       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7975       for (unsigned i = 0; i < NumElts; ++i)
7976         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7977       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7978       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7979       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7980                  Val.dump(););
7981       Val = LowerBUILD_VECTOR(Val, DAG);
7982       if (Val.getNode())
7983         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7984     }
7985   }
7986 
7987   // If there was only one constant value used and for more than one lane,
7988   // start by splatting that value, then replace the non-constant lanes. This
7989   // is better than the default, which will perform a separate initialization
7990   // for each lane.
7991   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7992     // Firstly, try to materialize the splat constant.
7993     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7994             Val = ConstantBuildVector(Vec, DAG);
7995     if (!Val) {
7996       // Otherwise, materialize the constant and splat it.
7997       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7998       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7999     }
8000 
8001     // Now insert the non-constant lanes.
8002     for (unsigned i = 0; i < NumElts; ++i) {
8003       SDValue V = Op.getOperand(i);
8004       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8005       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8006         // Note that type legalization likely mucked about with the VT of the
8007         // source operand, so we may have to convert it here before inserting.
8008         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8009     }
8010     return Val;
8011   }
8012 
8013   // This will generate a load from the constant pool.
8014   if (isConstant) {
8015     LLVM_DEBUG(
8016         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8017                   "expansion\n");
8018     return SDValue();
8019   }
8020 
8021   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8022   if (NumElts >= 4) {
8023     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8024       return shuffle;
8025   }
8026 
8027   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8028   // know the default expansion would otherwise fall back on something even
8029   // worse. For a vector with one or two non-undef values, that's
8030   // scalar_to_vector for the elements followed by a shuffle (provided the
8031   // shuffle is valid for the target) and materialization element by element
8032   // on the stack followed by a load for everything else.
8033   if (!isConstant && !usesOnlyOneValue) {
8034     LLVM_DEBUG(
8035         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8036                   "of INSERT_VECTOR_ELT\n");
8037 
8038     SDValue Vec = DAG.getUNDEF(VT);
8039     SDValue Op0 = Op.getOperand(0);
8040     unsigned i = 0;
8041 
8042     // Use SCALAR_TO_VECTOR for lane zero to
8043     // a) Avoid a RMW dependency on the full vector register, and
8044     // b) Allow the register coalescer to fold away the copy if the
8045     //    value is already in an S or D register, and we're forced to emit an
8046     //    INSERT_SUBREG that we can't fold anywhere.
8047     //
8048     // We also allow types like i8 and i16 which are illegal scalar but legal
8049     // vector element types. After type-legalization the inserted value is
8050     // extended (i32) and it is safe to cast them to the vector type by ignoring
8051     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8052     if (!Op0.isUndef()) {
8053       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8054       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8055       ++i;
8056     }
8057     LLVM_DEBUG(if (i < NumElts) dbgs()
8058                    << "Creating nodes for the other vector elements:\n";);
8059     for (; i < NumElts; ++i) {
8060       SDValue V = Op.getOperand(i);
8061       if (V.isUndef())
8062         continue;
8063       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8064       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8065     }
8066     return Vec;
8067   }
8068 
8069   LLVM_DEBUG(
8070       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8071                 "better alternative\n");
8072   return SDValue();
8073 }
8074 
8075 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8076                                                       SelectionDAG &DAG) const {
8077   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8078 
8079   // Check for non-constant or out of range lane.
8080   EVT VT = Op.getOperand(0).getValueType();
8081   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8082   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8083     return SDValue();
8084 
8085 
8086   // Insertion/extraction are legal for V128 types.
8087   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8088       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8089       VT == MVT::v8f16)
8090     return Op;
8091 
8092   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8093       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8094     return SDValue();
8095 
8096   // For V64 types, we perform insertion by expanding the value
8097   // to a V128 type and perform the insertion on that.
8098   SDLoc DL(Op);
8099   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8100   EVT WideTy = WideVec.getValueType();
8101 
8102   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8103                              Op.getOperand(1), Op.getOperand(2));
8104   // Re-narrow the resultant vector.
8105   return NarrowVector(Node, DAG);
8106 }
8107 
8108 SDValue
8109 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8110                                                SelectionDAG &DAG) const {
8111   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8112 
8113   // Check for non-constant or out of range lane.
8114   EVT VT = Op.getOperand(0).getValueType();
8115   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8116   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8117     return SDValue();
8118 
8119 
8120   // Insertion/extraction are legal for V128 types.
8121   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8122       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8123       VT == MVT::v8f16)
8124     return Op;
8125 
8126   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8127       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8128     return SDValue();
8129 
8130   // For V64 types, we perform extraction by expanding the value
8131   // to a V128 type and perform the extraction on that.
8132   SDLoc DL(Op);
8133   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8134   EVT WideTy = WideVec.getValueType();
8135 
8136   EVT ExtrTy = WideTy.getVectorElementType();
8137   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8138     ExtrTy = MVT::i32;
8139 
8140   // For extractions, we just return the result directly.
8141   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8142                      Op.getOperand(1));
8143 }
8144 
8145 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8146                                                       SelectionDAG &DAG) const {
8147   EVT VT = Op.getOperand(0).getValueType();
8148   SDLoc dl(Op);
8149   // Just in case...
8150   if (!VT.isVector())
8151     return SDValue();
8152 
8153   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8154   if (!Cst)
8155     return SDValue();
8156   unsigned Val = Cst->getZExtValue();
8157 
8158   unsigned Size = Op.getValueSizeInBits();
8159 
8160   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8161   if (Val == 0)
8162     return Op;
8163 
8164   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8165   // that directly.
8166   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
8167     return Op;
8168 
8169   return SDValue();
8170 }
8171 
8172 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8173   if (VT.getVectorNumElements() == 4 &&
8174       (VT.is128BitVector() || VT.is64BitVector())) {
8175     unsigned PFIndexes[4];
8176     for (unsigned i = 0; i != 4; ++i) {
8177       if (M[i] < 0)
8178         PFIndexes[i] = 8;
8179       else
8180         PFIndexes[i] = M[i];
8181     }
8182 
8183     // Compute the index in the perfect shuffle table.
8184     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8185                             PFIndexes[2] * 9 + PFIndexes[3];
8186     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8187     unsigned Cost = (PFEntry >> 30);
8188 
8189     if (Cost <= 4)
8190       return true;
8191   }
8192 
8193   bool DummyBool;
8194   int DummyInt;
8195   unsigned DummyUnsigned;
8196 
8197   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8198           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8199           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8200           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8201           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8202           isZIPMask(M, VT, DummyUnsigned) ||
8203           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8204           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8205           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8206           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8207           isConcatMask(M, VT, VT.getSizeInBits() == 128));
8208 }
8209 
8210 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8211 /// operand of a vector shift operation, where all the elements of the
8212 /// build_vector must have the same constant integer value.
8213 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8214   // Ignore bit_converts.
8215   while (Op.getOpcode() == ISD::BITCAST)
8216     Op = Op.getOperand(0);
8217   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8218   APInt SplatBits, SplatUndef;
8219   unsigned SplatBitSize;
8220   bool HasAnyUndefs;
8221   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8222                                     HasAnyUndefs, ElementBits) ||
8223       SplatBitSize > ElementBits)
8224     return false;
8225   Cnt = SplatBits.getSExtValue();
8226   return true;
8227 }
8228 
8229 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8230 /// operand of a vector shift left operation.  That value must be in the range:
8231 ///   0 <= Value < ElementBits for a left shift; or
8232 ///   0 <= Value <= ElementBits for a long left shift.
8233 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8234   assert(VT.isVector() && "vector shift count is not a vector type");
8235   int64_t ElementBits = VT.getScalarSizeInBits();
8236   if (!getVShiftImm(Op, ElementBits, Cnt))
8237     return false;
8238   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8239 }
8240 
8241 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8242 /// operand of a vector shift right operation. The value must be in the range:
8243 ///   1 <= Value <= ElementBits for a right shift; or
8244 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8245   assert(VT.isVector() && "vector shift count is not a vector type");
8246   int64_t ElementBits = VT.getScalarSizeInBits();
8247   if (!getVShiftImm(Op, ElementBits, Cnt))
8248     return false;
8249   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8250 }
8251 
8252 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8253                                                       SelectionDAG &DAG) const {
8254   EVT VT = Op.getValueType();
8255   SDLoc DL(Op);
8256   int64_t Cnt;
8257 
8258   if (!Op.getOperand(1).getValueType().isVector())
8259     return Op;
8260   unsigned EltSize = VT.getScalarSizeInBits();
8261 
8262   switch (Op.getOpcode()) {
8263   default:
8264     llvm_unreachable("unexpected shift opcode");
8265 
8266   case ISD::SHL:
8267     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8268       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8269                          DAG.getConstant(Cnt, DL, MVT::i32));
8270     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8271                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8272                                        MVT::i32),
8273                        Op.getOperand(0), Op.getOperand(1));
8274   case ISD::SRA:
8275   case ISD::SRL:
8276     // Right shift immediate
8277     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8278       unsigned Opc =
8279           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8280       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8281                          DAG.getConstant(Cnt, DL, MVT::i32));
8282     }
8283 
8284     // Right shift register.  Note, there is not a shift right register
8285     // instruction, but the shift left register instruction takes a signed
8286     // value, where negative numbers specify a right shift.
8287     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8288                                                 : Intrinsic::aarch64_neon_ushl;
8289     // negate the shift amount
8290     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8291     SDValue NegShiftLeft =
8292         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8293                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8294                     NegShift);
8295     return NegShiftLeft;
8296   }
8297 
8298   return SDValue();
8299 }
8300 
8301 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8302                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
8303                                     const SDLoc &dl, SelectionDAG &DAG) {
8304   EVT SrcVT = LHS.getValueType();
8305   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8306          "function only supposed to emit natural comparisons");
8307 
8308   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8309   APInt CnstBits(VT.getSizeInBits(), 0);
8310   APInt UndefBits(VT.getSizeInBits(), 0);
8311   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8312   bool IsZero = IsCnst && (CnstBits == 0);
8313 
8314   if (SrcVT.getVectorElementType().isFloatingPoint()) {
8315     switch (CC) {
8316     default:
8317       return SDValue();
8318     case AArch64CC::NE: {
8319       SDValue Fcmeq;
8320       if (IsZero)
8321         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8322       else
8323         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8324       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8325     }
8326     case AArch64CC::EQ:
8327       if (IsZero)
8328         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8329       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8330     case AArch64CC::GE:
8331       if (IsZero)
8332         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8333       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8334     case AArch64CC::GT:
8335       if (IsZero)
8336         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8337       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8338     case AArch64CC::LS:
8339       if (IsZero)
8340         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8341       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8342     case AArch64CC::LT:
8343       if (!NoNans)
8344         return SDValue();
8345       // If we ignore NaNs then we can use to the MI implementation.
8346       LLVM_FALLTHROUGH;
8347     case AArch64CC::MI:
8348       if (IsZero)
8349         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8350       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8351     }
8352   }
8353 
8354   switch (CC) {
8355   default:
8356     return SDValue();
8357   case AArch64CC::NE: {
8358     SDValue Cmeq;
8359     if (IsZero)
8360       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8361     else
8362       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8363     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8364   }
8365   case AArch64CC::EQ:
8366     if (IsZero)
8367       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8368     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8369   case AArch64CC::GE:
8370     if (IsZero)
8371       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8372     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8373   case AArch64CC::GT:
8374     if (IsZero)
8375       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8376     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8377   case AArch64CC::LE:
8378     if (IsZero)
8379       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8380     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8381   case AArch64CC::LS:
8382     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8383   case AArch64CC::LO:
8384     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8385   case AArch64CC::LT:
8386     if (IsZero)
8387       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8388     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8389   case AArch64CC::HI:
8390     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8391   case AArch64CC::HS:
8392     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8393   }
8394 }
8395 
8396 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8397                                            SelectionDAG &DAG) const {
8398   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8399   SDValue LHS = Op.getOperand(0);
8400   SDValue RHS = Op.getOperand(1);
8401   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8402   SDLoc dl(Op);
8403 
8404   if (LHS.getValueType().getVectorElementType().isInteger()) {
8405     assert(LHS.getValueType() == RHS.getValueType());
8406     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8407     SDValue Cmp =
8408         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8409     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8410   }
8411 
8412   const bool FullFP16 =
8413     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8414 
8415   // Make v4f16 (only) fcmp operations utilise vector instructions
8416   // v8f16 support will be a litle more complicated
8417   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8418     if (LHS.getValueType().getVectorNumElements() == 4) {
8419       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8420       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8421       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8422       DAG.ReplaceAllUsesWith(Op, NewSetcc);
8423       CmpVT = MVT::v4i32;
8424     } else
8425       return SDValue();
8426   }
8427 
8428   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8429           LHS.getValueType().getVectorElementType() != MVT::f128);
8430 
8431   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8432   // clean.  Some of them require two branches to implement.
8433   AArch64CC::CondCode CC1, CC2;
8434   bool ShouldInvert;
8435   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8436 
8437   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8438   SDValue Cmp =
8439       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8440   if (!Cmp.getNode())
8441     return SDValue();
8442 
8443   if (CC2 != AArch64CC::AL) {
8444     SDValue Cmp2 =
8445         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8446     if (!Cmp2.getNode())
8447       return SDValue();
8448 
8449     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8450   }
8451 
8452   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8453 
8454   if (ShouldInvert)
8455     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8456 
8457   return Cmp;
8458 }
8459 
8460 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8461                                   SelectionDAG &DAG) {
8462   SDValue VecOp = ScalarOp.getOperand(0);
8463   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8464   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8465                      DAG.getConstant(0, DL, MVT::i64));
8466 }
8467 
8468 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8469                                               SelectionDAG &DAG) const {
8470   SDLoc dl(Op);
8471   switch (Op.getOpcode()) {
8472   case ISD::VECREDUCE_ADD:
8473     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8474   case ISD::VECREDUCE_SMAX:
8475     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8476   case ISD::VECREDUCE_SMIN:
8477     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8478   case ISD::VECREDUCE_UMAX:
8479     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8480   case ISD::VECREDUCE_UMIN:
8481     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8482   case ISD::VECREDUCE_FMAX: {
8483     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8484     return DAG.getNode(
8485         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8486         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8487         Op.getOperand(0));
8488   }
8489   case ISD::VECREDUCE_FMIN: {
8490     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8491     return DAG.getNode(
8492         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8493         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8494         Op.getOperand(0));
8495   }
8496   default:
8497     llvm_unreachable("Unhandled reduction");
8498   }
8499 }
8500 
8501 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8502                                                     SelectionDAG &DAG) const {
8503   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8504   if (!Subtarget.hasLSE())
8505     return SDValue();
8506 
8507   // LSE has an atomic load-add instruction, but not a load-sub.
8508   SDLoc dl(Op);
8509   MVT VT = Op.getSimpleValueType();
8510   SDValue RHS = Op.getOperand(2);
8511   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8512   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8513   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8514                        Op.getOperand(0), Op.getOperand(1), RHS,
8515                        AN->getMemOperand());
8516 }
8517 
8518 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8519                                                     SelectionDAG &DAG) const {
8520   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8521   if (!Subtarget.hasLSE())
8522     return SDValue();
8523 
8524   // LSE has an atomic load-clear instruction, but not a load-and.
8525   SDLoc dl(Op);
8526   MVT VT = Op.getSimpleValueType();
8527   SDValue RHS = Op.getOperand(2);
8528   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8529   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8530   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8531                        Op.getOperand(0), Op.getOperand(1), RHS,
8532                        AN->getMemOperand());
8533 }
8534 
8535 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8536     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8537   SDLoc dl(Op);
8538   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8539   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8540 
8541   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8542   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8543   if (Subtarget->hasCustomCallingConv())
8544     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8545 
8546   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8547                      DAG.getConstant(4, dl, MVT::i64));
8548   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8549   Chain =
8550       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8551                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8552                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8553   // To match the actual intent better, we should read the output from X15 here
8554   // again (instead of potentially spilling it to the stack), but rereading Size
8555   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8556   // here.
8557 
8558   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8559                      DAG.getConstant(4, dl, MVT::i64));
8560   return Chain;
8561 }
8562 
8563 SDValue
8564 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8565                                                SelectionDAG &DAG) const {
8566   assert(Subtarget->isTargetWindows() &&
8567          "Only Windows alloca probing supported");
8568   SDLoc dl(Op);
8569   // Get the inputs.
8570   SDNode *Node = Op.getNode();
8571   SDValue Chain = Op.getOperand(0);
8572   SDValue Size = Op.getOperand(1);
8573   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8574   EVT VT = Node->getValueType(0);
8575 
8576   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8577           "no-stack-arg-probe")) {
8578     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8579     Chain = SP.getValue(1);
8580     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8581     if (Align)
8582       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8583                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8584     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8585     SDValue Ops[2] = {SP, Chain};
8586     return DAG.getMergeValues(Ops, dl);
8587   }
8588 
8589   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8590 
8591   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8592 
8593   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8594   Chain = SP.getValue(1);
8595   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8596   if (Align)
8597     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8598                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8599   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8600 
8601   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8602                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8603 
8604   SDValue Ops[2] = {SP, Chain};
8605   return DAG.getMergeValues(Ops, dl);
8606 }
8607 
8608 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8609 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8610 /// specified in the intrinsic calls.
8611 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8612                                                const CallInst &I,
8613                                                MachineFunction &MF,
8614                                                unsigned Intrinsic) const {
8615   auto &DL = I.getModule()->getDataLayout();
8616   switch (Intrinsic) {
8617   case Intrinsic::aarch64_neon_ld2:
8618   case Intrinsic::aarch64_neon_ld3:
8619   case Intrinsic::aarch64_neon_ld4:
8620   case Intrinsic::aarch64_neon_ld1x2:
8621   case Intrinsic::aarch64_neon_ld1x3:
8622   case Intrinsic::aarch64_neon_ld1x4:
8623   case Intrinsic::aarch64_neon_ld2lane:
8624   case Intrinsic::aarch64_neon_ld3lane:
8625   case Intrinsic::aarch64_neon_ld4lane:
8626   case Intrinsic::aarch64_neon_ld2r:
8627   case Intrinsic::aarch64_neon_ld3r:
8628   case Intrinsic::aarch64_neon_ld4r: {
8629     Info.opc = ISD::INTRINSIC_W_CHAIN;
8630     // Conservatively set memVT to the entire set of vectors loaded.
8631     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8632     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8633     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8634     Info.offset = 0;
8635     Info.align.reset();
8636     // volatile loads with NEON intrinsics not supported
8637     Info.flags = MachineMemOperand::MOLoad;
8638     return true;
8639   }
8640   case Intrinsic::aarch64_neon_st2:
8641   case Intrinsic::aarch64_neon_st3:
8642   case Intrinsic::aarch64_neon_st4:
8643   case Intrinsic::aarch64_neon_st1x2:
8644   case Intrinsic::aarch64_neon_st1x3:
8645   case Intrinsic::aarch64_neon_st1x4:
8646   case Intrinsic::aarch64_neon_st2lane:
8647   case Intrinsic::aarch64_neon_st3lane:
8648   case Intrinsic::aarch64_neon_st4lane: {
8649     Info.opc = ISD::INTRINSIC_VOID;
8650     // Conservatively set memVT to the entire set of vectors stored.
8651     unsigned NumElts = 0;
8652     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8653       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8654       if (!ArgTy->isVectorTy())
8655         break;
8656       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8657     }
8658     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8659     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8660     Info.offset = 0;
8661     Info.align.reset();
8662     // volatile stores with NEON intrinsics not supported
8663     Info.flags = MachineMemOperand::MOStore;
8664     return true;
8665   }
8666   case Intrinsic::aarch64_ldaxr:
8667   case Intrinsic::aarch64_ldxr: {
8668     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8669     Info.opc = ISD::INTRINSIC_W_CHAIN;
8670     Info.memVT = MVT::getVT(PtrTy->getElementType());
8671     Info.ptrVal = I.getArgOperand(0);
8672     Info.offset = 0;
8673     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8674     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8675     return true;
8676   }
8677   case Intrinsic::aarch64_stlxr:
8678   case Intrinsic::aarch64_stxr: {
8679     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8680     Info.opc = ISD::INTRINSIC_W_CHAIN;
8681     Info.memVT = MVT::getVT(PtrTy->getElementType());
8682     Info.ptrVal = I.getArgOperand(1);
8683     Info.offset = 0;
8684     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8685     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8686     return true;
8687   }
8688   case Intrinsic::aarch64_ldaxp:
8689   case Intrinsic::aarch64_ldxp:
8690     Info.opc = ISD::INTRINSIC_W_CHAIN;
8691     Info.memVT = MVT::i128;
8692     Info.ptrVal = I.getArgOperand(0);
8693     Info.offset = 0;
8694     Info.align = Align(16);
8695     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8696     return true;
8697   case Intrinsic::aarch64_stlxp:
8698   case Intrinsic::aarch64_stxp:
8699     Info.opc = ISD::INTRINSIC_W_CHAIN;
8700     Info.memVT = MVT::i128;
8701     Info.ptrVal = I.getArgOperand(2);
8702     Info.offset = 0;
8703     Info.align = Align(16);
8704     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8705     return true;
8706   case Intrinsic::aarch64_sve_ldnt1: {
8707     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8708     Info.opc = ISD::INTRINSIC_W_CHAIN;
8709     Info.memVT = MVT::getVT(PtrTy->getElementType());
8710     Info.ptrVal = I.getArgOperand(1);
8711     Info.offset = 0;
8712     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8713     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
8714     return true;
8715   }
8716   case Intrinsic::aarch64_sve_stnt1: {
8717     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
8718     Info.opc = ISD::INTRINSIC_W_CHAIN;
8719     Info.memVT = MVT::getVT(PtrTy->getElementType());
8720     Info.ptrVal = I.getArgOperand(2);
8721     Info.offset = 0;
8722     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8723     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
8724     return true;
8725   }
8726   default:
8727     break;
8728   }
8729 
8730   return false;
8731 }
8732 
8733 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8734                                                   ISD::LoadExtType ExtTy,
8735                                                   EVT NewVT) const {
8736   // TODO: This may be worth removing. Check regression tests for diffs.
8737   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8738     return false;
8739 
8740   // If we're reducing the load width in order to avoid having to use an extra
8741   // instruction to do extension then it's probably a good idea.
8742   if (ExtTy != ISD::NON_EXTLOAD)
8743     return true;
8744   // Don't reduce load width if it would prevent us from combining a shift into
8745   // the offset.
8746   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8747   assert(Mem);
8748   const SDValue &Base = Mem->getBasePtr();
8749   if (Base.getOpcode() == ISD::ADD &&
8750       Base.getOperand(1).getOpcode() == ISD::SHL &&
8751       Base.getOperand(1).hasOneUse() &&
8752       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8753     // The shift can be combined if it matches the size of the value being
8754     // loaded (and so reducing the width would make it not match).
8755     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8756     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8757     if (ShiftAmount == Log2_32(LoadBytes))
8758       return false;
8759   }
8760   // We have no reason to disallow reducing the load width, so allow it.
8761   return true;
8762 }
8763 
8764 // Truncations from 64-bit GPR to 32-bit GPR is free.
8765 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8766   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8767     return false;
8768   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8769   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8770   return NumBits1 > NumBits2;
8771 }
8772 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8773   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8774     return false;
8775   unsigned NumBits1 = VT1.getSizeInBits();
8776   unsigned NumBits2 = VT2.getSizeInBits();
8777   return NumBits1 > NumBits2;
8778 }
8779 
8780 /// Check if it is profitable to hoist instruction in then/else to if.
8781 /// Not profitable if I and it's user can form a FMA instruction
8782 /// because we prefer FMSUB/FMADD.
8783 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8784   if (I->getOpcode() != Instruction::FMul)
8785     return true;
8786 
8787   if (!I->hasOneUse())
8788     return true;
8789 
8790   Instruction *User = I->user_back();
8791 
8792   if (User &&
8793       !(User->getOpcode() == Instruction::FSub ||
8794         User->getOpcode() == Instruction::FAdd))
8795     return true;
8796 
8797   const TargetOptions &Options = getTargetMachine().Options;
8798   const Function *F = I->getFunction();
8799   const DataLayout &DL = F->getParent()->getDataLayout();
8800   Type *Ty = User->getOperand(0)->getType();
8801 
8802   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
8803            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
8804            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8805             Options.UnsafeFPMath));
8806 }
8807 
8808 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8809 // 64-bit GPR.
8810 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8811   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8812     return false;
8813   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8814   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8815   return NumBits1 == 32 && NumBits2 == 64;
8816 }
8817 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8818   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8819     return false;
8820   unsigned NumBits1 = VT1.getSizeInBits();
8821   unsigned NumBits2 = VT2.getSizeInBits();
8822   return NumBits1 == 32 && NumBits2 == 64;
8823 }
8824 
8825 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8826   EVT VT1 = Val.getValueType();
8827   if (isZExtFree(VT1, VT2)) {
8828     return true;
8829   }
8830 
8831   if (Val.getOpcode() != ISD::LOAD)
8832     return false;
8833 
8834   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8835   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8836           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8837           VT1.getSizeInBits() <= 32);
8838 }
8839 
8840 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8841   if (isa<FPExtInst>(Ext))
8842     return false;
8843 
8844   // Vector types are not free.
8845   if (Ext->getType()->isVectorTy())
8846     return false;
8847 
8848   for (const Use &U : Ext->uses()) {
8849     // The extension is free if we can fold it with a left shift in an
8850     // addressing mode or an arithmetic operation: add, sub, and cmp.
8851 
8852     // Is there a shift?
8853     const Instruction *Instr = cast<Instruction>(U.getUser());
8854 
8855     // Is this a constant shift?
8856     switch (Instr->getOpcode()) {
8857     case Instruction::Shl:
8858       if (!isa<ConstantInt>(Instr->getOperand(1)))
8859         return false;
8860       break;
8861     case Instruction::GetElementPtr: {
8862       gep_type_iterator GTI = gep_type_begin(Instr);
8863       auto &DL = Ext->getModule()->getDataLayout();
8864       std::advance(GTI, U.getOperandNo()-1);
8865       Type *IdxTy = GTI.getIndexedType();
8866       // This extension will end up with a shift because of the scaling factor.
8867       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8868       // Get the shift amount based on the scaling factor:
8869       // log2(sizeof(IdxTy)) - log2(8).
8870       uint64_t ShiftAmt =
8871         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
8872       // Is the constant foldable in the shift of the addressing mode?
8873       // I.e., shift amount is between 1 and 4 inclusive.
8874       if (ShiftAmt == 0 || ShiftAmt > 4)
8875         return false;
8876       break;
8877     }
8878     case Instruction::Trunc:
8879       // Check if this is a noop.
8880       // trunc(sext ty1 to ty2) to ty1.
8881       if (Instr->getType() == Ext->getOperand(0)->getType())
8882         continue;
8883       LLVM_FALLTHROUGH;
8884     default:
8885       return false;
8886     }
8887 
8888     // At this point we can use the bfm family, so this extension is free
8889     // for that use.
8890   }
8891   return true;
8892 }
8893 
8894 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8895 /// or upper half of the vector elements.
8896 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8897   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8898     auto *FullVT = cast<VectorType>(FullV->getType());
8899     auto *HalfVT = cast<VectorType>(HalfV->getType());
8900     return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8901   };
8902 
8903   auto extractHalf = [](Value *FullV, Value *HalfV) {
8904     auto *FullVT = cast<VectorType>(FullV->getType());
8905     auto *HalfVT = cast<VectorType>(HalfV->getType());
8906     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8907   };
8908 
8909   Constant *M1, *M2;
8910   Value *S1Op1, *S2Op1;
8911   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8912       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8913     return false;
8914 
8915   // Check that the operands are half as wide as the result and we extract
8916   // half of the elements of the input vectors.
8917   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8918       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8919     return false;
8920 
8921   // Check the mask extracts either the lower or upper half of vector
8922   // elements.
8923   int M1Start = -1;
8924   int M2Start = -1;
8925   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8926   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8927       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8928       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8929     return false;
8930 
8931   return true;
8932 }
8933 
8934 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8935 /// of the vector elements.
8936 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8937   auto areExtDoubled = [](Instruction *Ext) {
8938     return Ext->getType()->getScalarSizeInBits() ==
8939            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8940   };
8941 
8942   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8943       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8944       !areExtDoubled(cast<Instruction>(Ext1)) ||
8945       !areExtDoubled(cast<Instruction>(Ext2)))
8946     return false;
8947 
8948   return true;
8949 }
8950 
8951 /// Check if sinking \p I's operands to I's basic block is profitable, because
8952 /// the operands can be folded into a target instruction, e.g.
8953 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8954 bool AArch64TargetLowering::shouldSinkOperands(
8955     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8956   if (!I->getType()->isVectorTy())
8957     return false;
8958 
8959   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8960     switch (II->getIntrinsicID()) {
8961     case Intrinsic::aarch64_neon_umull:
8962       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8963         return false;
8964       Ops.push_back(&II->getOperandUse(0));
8965       Ops.push_back(&II->getOperandUse(1));
8966       return true;
8967     default:
8968       return false;
8969     }
8970   }
8971 
8972   switch (I->getOpcode()) {
8973   case Instruction::Sub:
8974   case Instruction::Add: {
8975     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8976       return false;
8977 
8978     // If the exts' operands extract either the lower or upper elements, we
8979     // can sink them too.
8980     auto Ext1 = cast<Instruction>(I->getOperand(0));
8981     auto Ext2 = cast<Instruction>(I->getOperand(1));
8982     if (areExtractShuffleVectors(Ext1, Ext2)) {
8983       Ops.push_back(&Ext1->getOperandUse(0));
8984       Ops.push_back(&Ext2->getOperandUse(0));
8985     }
8986 
8987     Ops.push_back(&I->getOperandUse(0));
8988     Ops.push_back(&I->getOperandUse(1));
8989 
8990     return true;
8991   }
8992   default:
8993     return false;
8994   }
8995   return false;
8996 }
8997 
8998 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8999                                           unsigned &RequiredAligment) const {
9000   if (!LoadedType.isSimple() ||
9001       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9002     return false;
9003   // Cyclone supports unaligned accesses.
9004   RequiredAligment = 0;
9005   unsigned NumBits = LoadedType.getSizeInBits();
9006   return NumBits == 32 || NumBits == 64;
9007 }
9008 
9009 /// A helper function for determining the number of interleaved accesses we
9010 /// will generate when lowering accesses of the given type.
9011 unsigned
9012 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9013                                                  const DataLayout &DL) const {
9014   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9015 }
9016 
9017 MachineMemOperand::Flags
9018 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
9019   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9020       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9021     return MOStridedAccess;
9022   return MachineMemOperand::MONone;
9023 }
9024 
9025 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9026     VectorType *VecTy, const DataLayout &DL) const {
9027 
9028   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9029   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9030 
9031   // Ensure the number of vector elements is greater than 1.
9032   if (VecTy->getNumElements() < 2)
9033     return false;
9034 
9035   // Ensure the element type is legal.
9036   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9037     return false;
9038 
9039   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9040   // 128 will be split into multiple interleaved accesses.
9041   return VecSize == 64 || VecSize % 128 == 0;
9042 }
9043 
9044 /// Lower an interleaved load into a ldN intrinsic.
9045 ///
9046 /// E.g. Lower an interleaved load (Factor = 2):
9047 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9048 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9049 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9050 ///
9051 ///      Into:
9052 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9053 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9054 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9055 bool AArch64TargetLowering::lowerInterleavedLoad(
9056     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9057     ArrayRef<unsigned> Indices, unsigned Factor) const {
9058   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9059          "Invalid interleave factor");
9060   assert(!Shuffles.empty() && "Empty shufflevector input");
9061   assert(Shuffles.size() == Indices.size() &&
9062          "Unmatched number of shufflevectors and indices");
9063 
9064   const DataLayout &DL = LI->getModule()->getDataLayout();
9065 
9066   VectorType *VecTy = Shuffles[0]->getType();
9067 
9068   // Skip if we do not have NEON and skip illegal vector types. We can
9069   // "legalize" wide vector types into multiple interleaved accesses as long as
9070   // the vector types are divisible by 128.
9071   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
9072     return false;
9073 
9074   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
9075 
9076   // A pointer vector can not be the return type of the ldN intrinsics. Need to
9077   // load integer vectors first and then convert to pointer vectors.
9078   Type *EltTy = VecTy->getVectorElementType();
9079   if (EltTy->isPointerTy())
9080     VecTy =
9081         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
9082 
9083   IRBuilder<> Builder(LI);
9084 
9085   // The base address of the load.
9086   Value *BaseAddr = LI->getPointerOperand();
9087 
9088   if (NumLoads > 1) {
9089     // If we're going to generate more than one load, reset the sub-vector type
9090     // to something legal.
9091     VecTy = VectorType::get(VecTy->getVectorElementType(),
9092                             VecTy->getVectorNumElements() / NumLoads);
9093 
9094     // We will compute the pointer operand of each load from the original base
9095     // address using GEPs. Cast the base address to a pointer to the scalar
9096     // element type.
9097     BaseAddr = Builder.CreateBitCast(
9098         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
9099                       LI->getPointerAddressSpace()));
9100   }
9101 
9102   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
9103   Type *Tys[2] = {VecTy, PtrTy};
9104   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9105                                             Intrinsic::aarch64_neon_ld3,
9106                                             Intrinsic::aarch64_neon_ld4};
9107   Function *LdNFunc =
9108       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9109 
9110   // Holds sub-vectors extracted from the load intrinsic return values. The
9111   // sub-vectors are associated with the shufflevector instructions they will
9112   // replace.
9113   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9114 
9115   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9116 
9117     // If we're generating more than one load, compute the base address of
9118     // subsequent loads as an offset from the previous.
9119     if (LoadCount > 0)
9120       BaseAddr =
9121           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
9122                                      VecTy->getVectorNumElements() * Factor);
9123 
9124     CallInst *LdN = Builder.CreateCall(
9125         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9126 
9127     // Extract and store the sub-vectors returned by the load intrinsic.
9128     for (unsigned i = 0; i < Shuffles.size(); i++) {
9129       ShuffleVectorInst *SVI = Shuffles[i];
9130       unsigned Index = Indices[i];
9131 
9132       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9133 
9134       // Convert the integer vector to pointer vector if the element is pointer.
9135       if (EltTy->isPointerTy())
9136         SubVec = Builder.CreateIntToPtr(
9137             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
9138                                     VecTy->getVectorNumElements()));
9139       SubVecs[SVI].push_back(SubVec);
9140     }
9141   }
9142 
9143   // Replace uses of the shufflevector instructions with the sub-vectors
9144   // returned by the load intrinsic. If a shufflevector instruction is
9145   // associated with more than one sub-vector, those sub-vectors will be
9146   // concatenated into a single wide vector.
9147   for (ShuffleVectorInst *SVI : Shuffles) {
9148     auto &SubVec = SubVecs[SVI];
9149     auto *WideVec =
9150         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9151     SVI->replaceAllUsesWith(WideVec);
9152   }
9153 
9154   return true;
9155 }
9156 
9157 /// Lower an interleaved store into a stN intrinsic.
9158 ///
9159 /// E.g. Lower an interleaved store (Factor = 3):
9160 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9161 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9162 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9163 ///
9164 ///      Into:
9165 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9166 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9167 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9168 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9169 ///
9170 /// Note that the new shufflevectors will be removed and we'll only generate one
9171 /// st3 instruction in CodeGen.
9172 ///
9173 /// Example for a more general valid mask (Factor 3). Lower:
9174 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9175 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9176 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9177 ///
9178 ///      Into:
9179 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9180 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9181 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9182 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9183 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9184                                                   ShuffleVectorInst *SVI,
9185                                                   unsigned Factor) const {
9186   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9187          "Invalid interleave factor");
9188 
9189   VectorType *VecTy = SVI->getType();
9190   assert(VecTy->getVectorNumElements() % Factor == 0 &&
9191          "Invalid interleaved store");
9192 
9193   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
9194   Type *EltTy = VecTy->getVectorElementType();
9195   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
9196 
9197   const DataLayout &DL = SI->getModule()->getDataLayout();
9198 
9199   // Skip if we do not have NEON and skip illegal vector types. We can
9200   // "legalize" wide vector types into multiple interleaved accesses as long as
9201   // the vector types are divisible by 128.
9202   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9203     return false;
9204 
9205   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9206 
9207   Value *Op0 = SVI->getOperand(0);
9208   Value *Op1 = SVI->getOperand(1);
9209   IRBuilder<> Builder(SI);
9210 
9211   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9212   // vectors to integer vectors.
9213   if (EltTy->isPointerTy()) {
9214     Type *IntTy = DL.getIntPtrType(EltTy);
9215     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
9216 
9217     // Convert to the corresponding integer vector.
9218     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
9219     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9220     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9221 
9222     SubVecTy = VectorType::get(IntTy, LaneLen);
9223   }
9224 
9225   // The base address of the store.
9226   Value *BaseAddr = SI->getPointerOperand();
9227 
9228   if (NumStores > 1) {
9229     // If we're going to generate more than one store, reset the lane length
9230     // and sub-vector type to something legal.
9231     LaneLen /= NumStores;
9232     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
9233 
9234     // We will compute the pointer operand of each store from the original base
9235     // address using GEPs. Cast the base address to a pointer to the scalar
9236     // element type.
9237     BaseAddr = Builder.CreateBitCast(
9238         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
9239                       SI->getPointerAddressSpace()));
9240   }
9241 
9242   auto Mask = SVI->getShuffleMask();
9243 
9244   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
9245   Type *Tys[2] = {SubVecTy, PtrTy};
9246   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
9247                                              Intrinsic::aarch64_neon_st3,
9248                                              Intrinsic::aarch64_neon_st4};
9249   Function *StNFunc =
9250       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
9251 
9252   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9253 
9254     SmallVector<Value *, 5> Ops;
9255 
9256     // Split the shufflevector operands into sub vectors for the new stN call.
9257     for (unsigned i = 0; i < Factor; i++) {
9258       unsigned IdxI = StoreCount * LaneLen * Factor + i;
9259       if (Mask[IdxI] >= 0) {
9260         Ops.push_back(Builder.CreateShuffleVector(
9261             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9262       } else {
9263         unsigned StartMask = 0;
9264         for (unsigned j = 1; j < LaneLen; j++) {
9265           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9266           if (Mask[IdxJ * Factor + IdxI] >= 0) {
9267             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9268             break;
9269           }
9270         }
9271         // Note: Filling undef gaps with random elements is ok, since
9272         // those elements were being written anyway (with undefs).
9273         // In the case of all undefs we're defaulting to using elems from 0
9274         // Note: StartMask cannot be negative, it's checked in
9275         // isReInterleaveMask
9276         Ops.push_back(Builder.CreateShuffleVector(
9277             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9278       }
9279     }
9280 
9281     // If we generating more than one store, we compute the base address of
9282     // subsequent stores as an offset from the previous.
9283     if (StoreCount > 0)
9284       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
9285                                             BaseAddr, LaneLen * Factor);
9286 
9287     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9288     Builder.CreateCall(StNFunc, Ops);
9289   }
9290   return true;
9291 }
9292 
9293 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9294                        unsigned AlignCheck) {
9295   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9296           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9297 }
9298 
9299 EVT AArch64TargetLowering::getOptimalMemOpType(
9300     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9301     bool ZeroMemset, bool MemcpyStrSrc,
9302     const AttributeList &FuncAttributes) const {
9303   bool CanImplicitFloat =
9304       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9305   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9306   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9307   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9308   // taken one instruction to materialize the v2i64 zero and one store (with
9309   // restrictive addressing mode). Just do i64 stores.
9310   bool IsSmallMemset = IsMemset && Size < 32;
9311   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9312     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9313       return true;
9314     bool Fast;
9315     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9316                                           &Fast) &&
9317            Fast;
9318   };
9319 
9320   if (CanUseNEON && IsMemset && !IsSmallMemset &&
9321       AlignmentIsAcceptable(MVT::v2i64, 16))
9322     return MVT::v2i64;
9323   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9324     return MVT::f128;
9325   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9326     return MVT::i64;
9327   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9328     return MVT::i32;
9329   return MVT::Other;
9330 }
9331 
9332 LLT AArch64TargetLowering::getOptimalMemOpLLT(
9333     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9334     bool ZeroMemset, bool MemcpyStrSrc,
9335     const AttributeList &FuncAttributes) const {
9336   bool CanImplicitFloat =
9337       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9338   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9339   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9340   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9341   // taken one instruction to materialize the v2i64 zero and one store (with
9342   // restrictive addressing mode). Just do i64 stores.
9343   bool IsSmallMemset = IsMemset && Size < 32;
9344   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9345     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9346       return true;
9347     bool Fast;
9348     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9349                                           &Fast) &&
9350            Fast;
9351   };
9352 
9353   if (CanUseNEON && IsMemset && !IsSmallMemset &&
9354       AlignmentIsAcceptable(MVT::v2i64, 16))
9355     return LLT::vector(2, 64);
9356   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9357     return LLT::scalar(128);
9358   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9359     return LLT::scalar(64);
9360   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9361     return LLT::scalar(32);
9362   return LLT();
9363 }
9364 
9365 // 12-bit optionally shifted immediates are legal for adds.
9366 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9367   if (Immed == std::numeric_limits<int64_t>::min()) {
9368     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9369                       << ": avoid UB for INT64_MIN\n");
9370     return false;
9371   }
9372   // Same encoding for add/sub, just flip the sign.
9373   Immed = std::abs(Immed);
9374   bool IsLegal = ((Immed >> 12) == 0 ||
9375                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9376   LLVM_DEBUG(dbgs() << "Is " << Immed
9377                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9378   return IsLegal;
9379 }
9380 
9381 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9382 // immediates is the same as for an add or a sub.
9383 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9384   return isLegalAddImmediate(Immed);
9385 }
9386 
9387 /// isLegalAddressingMode - Return true if the addressing mode represented
9388 /// by AM is legal for this target, for a load/store of the specified type.
9389 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9390                                                   const AddrMode &AM, Type *Ty,
9391                                                   unsigned AS, Instruction *I) const {
9392   // AArch64 has five basic addressing modes:
9393   //  reg
9394   //  reg + 9-bit signed offset
9395   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
9396   //  reg1 + reg2
9397   //  reg + SIZE_IN_BYTES * reg
9398 
9399   // No global is ever allowed as a base.
9400   if (AM.BaseGV)
9401     return false;
9402 
9403   // No reg+reg+imm addressing.
9404   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9405     return false;
9406 
9407   // check reg + imm case:
9408   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9409   uint64_t NumBytes = 0;
9410   if (Ty->isSized()) {
9411     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9412     NumBytes = NumBits / 8;
9413     if (!isPowerOf2_64(NumBits))
9414       NumBytes = 0;
9415   }
9416 
9417   if (!AM.Scale) {
9418     int64_t Offset = AM.BaseOffs;
9419 
9420     // 9-bit signed offset
9421     if (isInt<9>(Offset))
9422       return true;
9423 
9424     // 12-bit unsigned offset
9425     unsigned shift = Log2_64(NumBytes);
9426     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9427         // Must be a multiple of NumBytes (NumBytes is a power of 2)
9428         (Offset >> shift) << shift == Offset)
9429       return true;
9430     return false;
9431   }
9432 
9433   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9434 
9435   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9436 }
9437 
9438 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9439   // Consider splitting large offset of struct or array.
9440   return true;
9441 }
9442 
9443 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9444                                                 const AddrMode &AM, Type *Ty,
9445                                                 unsigned AS) const {
9446   // Scaling factors are not free at all.
9447   // Operands                     | Rt Latency
9448   // -------------------------------------------
9449   // Rt, [Xn, Xm]                 | 4
9450   // -------------------------------------------
9451   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
9452   // Rt, [Xn, Wm, <extend> #imm]  |
9453   if (isLegalAddressingMode(DL, AM, Ty, AS))
9454     // Scale represents reg2 * scale, thus account for 1 if
9455     // it is not equal to 0 or 1.
9456     return AM.Scale != 0 && AM.Scale != 1;
9457   return -1;
9458 }
9459 
9460 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
9461     const MachineFunction &MF, EVT VT) const {
9462   VT = VT.getScalarType();
9463 
9464   if (!VT.isSimple())
9465     return false;
9466 
9467   switch (VT.getSimpleVT().SimpleTy) {
9468   case MVT::f32:
9469   case MVT::f64:
9470     return true;
9471   default:
9472     break;
9473   }
9474 
9475   return false;
9476 }
9477 
9478 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
9479                                                        Type *Ty) const {
9480   switch (Ty->getScalarType()->getTypeID()) {
9481   case Type::FloatTyID:
9482   case Type::DoubleTyID:
9483     return true;
9484   default:
9485     return false;
9486   }
9487 }
9488 
9489 const MCPhysReg *
9490 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9491   // LR is a callee-save register, but we must treat it as clobbered by any call
9492   // site. Hence we include LR in the scratch registers, which are in turn added
9493   // as implicit-defs for stackmaps and patchpoints.
9494   static const MCPhysReg ScratchRegs[] = {
9495     AArch64::X16, AArch64::X17, AArch64::LR, 0
9496   };
9497   return ScratchRegs;
9498 }
9499 
9500 bool
9501 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9502                                                      CombineLevel Level) const {
9503   N = N->getOperand(0).getNode();
9504   EVT VT = N->getValueType(0);
9505     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9506     // it with shift to let it be lowered to UBFX.
9507   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9508       isa<ConstantSDNode>(N->getOperand(1))) {
9509     uint64_t TruncMask = N->getConstantOperandVal(1);
9510     if (isMask_64(TruncMask) &&
9511       N->getOperand(0).getOpcode() == ISD::SRL &&
9512       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9513       return false;
9514   }
9515   return true;
9516 }
9517 
9518 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9519                                                               Type *Ty) const {
9520   assert(Ty->isIntegerTy());
9521 
9522   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9523   if (BitSize == 0)
9524     return false;
9525 
9526   int64_t Val = Imm.getSExtValue();
9527   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9528     return true;
9529 
9530   if ((int64_t)Val < 0)
9531     Val = ~Val;
9532   if (BitSize == 32)
9533     Val &= (1LL << 32) - 1;
9534 
9535   unsigned LZ = countLeadingZeros((uint64_t)Val);
9536   unsigned Shift = (63 - LZ) / 16;
9537   // MOVZ is free so return true for one or fewer MOVK.
9538   return Shift < 3;
9539 }
9540 
9541 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9542                                                     unsigned Index) const {
9543   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9544     return false;
9545 
9546   return (Index == 0 || Index == ResVT.getVectorNumElements());
9547 }
9548 
9549 /// Turn vector tests of the signbit in the form of:
9550 ///   xor (sra X, elt_size(X)-1), -1
9551 /// into:
9552 ///   cmge X, X, #0
9553 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9554                                          const AArch64Subtarget *Subtarget) {
9555   EVT VT = N->getValueType(0);
9556   if (!Subtarget->hasNEON() || !VT.isVector())
9557     return SDValue();
9558 
9559   // There must be a shift right algebraic before the xor, and the xor must be a
9560   // 'not' operation.
9561   SDValue Shift = N->getOperand(0);
9562   SDValue Ones = N->getOperand(1);
9563   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9564       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9565     return SDValue();
9566 
9567   // The shift should be smearing the sign bit across each vector element.
9568   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9569   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9570   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9571     return SDValue();
9572 
9573   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9574 }
9575 
9576 // Generate SUBS and CSEL for integer abs.
9577 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9578   EVT VT = N->getValueType(0);
9579 
9580   SDValue N0 = N->getOperand(0);
9581   SDValue N1 = N->getOperand(1);
9582   SDLoc DL(N);
9583 
9584   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9585   // and change it to SUB and CSEL.
9586   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9587       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9588       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9589     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9590       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9591         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9592                                   N0.getOperand(0));
9593         // Generate SUBS & CSEL.
9594         SDValue Cmp =
9595             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9596                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9597         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9598                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9599                            SDValue(Cmp.getNode(), 1));
9600       }
9601   return SDValue();
9602 }
9603 
9604 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9605                                  TargetLowering::DAGCombinerInfo &DCI,
9606                                  const AArch64Subtarget *Subtarget) {
9607   if (DCI.isBeforeLegalizeOps())
9608     return SDValue();
9609 
9610   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9611     return Cmp;
9612 
9613   return performIntegerAbsCombine(N, DAG);
9614 }
9615 
9616 SDValue
9617 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9618                                      SelectionDAG &DAG,
9619                                      SmallVectorImpl<SDNode *> &Created) const {
9620   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9621   if (isIntDivCheap(N->getValueType(0), Attr))
9622     return SDValue(N,0); // Lower SDIV as SDIV
9623 
9624   // fold (sdiv X, pow2)
9625   EVT VT = N->getValueType(0);
9626   if ((VT != MVT::i32 && VT != MVT::i64) ||
9627       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9628     return SDValue();
9629 
9630   SDLoc DL(N);
9631   SDValue N0 = N->getOperand(0);
9632   unsigned Lg2 = Divisor.countTrailingZeros();
9633   SDValue Zero = DAG.getConstant(0, DL, VT);
9634   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9635 
9636   // Add (N0 < 0) ? Pow2 - 1 : 0;
9637   SDValue CCVal;
9638   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9639   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9640   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9641 
9642   Created.push_back(Cmp.getNode());
9643   Created.push_back(Add.getNode());
9644   Created.push_back(CSel.getNode());
9645 
9646   // Divide by pow2.
9647   SDValue SRA =
9648       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9649 
9650   // If we're dividing by a positive value, we're done.  Otherwise, we must
9651   // negate the result.
9652   if (Divisor.isNonNegative())
9653     return SRA;
9654 
9655   Created.push_back(SRA.getNode());
9656   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9657 }
9658 
9659 static bool IsSVECntIntrinsic(SDValue S) {
9660   switch(getIntrinsicID(S.getNode())) {
9661   default:
9662     break;
9663   case Intrinsic::aarch64_sve_cntb:
9664   case Intrinsic::aarch64_sve_cnth:
9665   case Intrinsic::aarch64_sve_cntw:
9666   case Intrinsic::aarch64_sve_cntd:
9667     return true;
9668   }
9669   return false;
9670 }
9671 
9672 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9673                                  TargetLowering::DAGCombinerInfo &DCI,
9674                                  const AArch64Subtarget *Subtarget) {
9675   if (DCI.isBeforeLegalizeOps())
9676     return SDValue();
9677 
9678   // The below optimizations require a constant RHS.
9679   if (!isa<ConstantSDNode>(N->getOperand(1)))
9680     return SDValue();
9681 
9682   SDValue N0 = N->getOperand(0);
9683   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9684   const APInt &ConstValue = C->getAPIntValue();
9685 
9686   // Allow the scaling to be folded into the `cnt` instruction by preventing
9687   // the scaling to be obscured here. This makes it easier to pattern match.
9688   if (IsSVECntIntrinsic(N0) ||
9689      (N0->getOpcode() == ISD::TRUNCATE &&
9690       (IsSVECntIntrinsic(N0->getOperand(0)))))
9691        if (ConstValue.sge(1) && ConstValue.sle(16))
9692          return SDValue();
9693 
9694   // Multiplication of a power of two plus/minus one can be done more
9695   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9696   // future CPUs have a cheaper MADD instruction, this may need to be
9697   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9698   // 64-bit is 5 cycles, so this is always a win.
9699   // More aggressively, some multiplications N0 * C can be lowered to
9700   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9701   // e.g. 6=3*2=(2+1)*2.
9702   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9703   // which equals to (1+2)*16-(1+2).
9704   // TrailingZeroes is used to test if the mul can be lowered to
9705   // shift+add+shift.
9706   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9707   if (TrailingZeroes) {
9708     // Conservatively do not lower to shift+add+shift if the mul might be
9709     // folded into smul or umul.
9710     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9711                             isZeroExtended(N0.getNode(), DAG)))
9712       return SDValue();
9713     // Conservatively do not lower to shift+add+shift if the mul might be
9714     // folded into madd or msub.
9715     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9716                            N->use_begin()->getOpcode() == ISD::SUB))
9717       return SDValue();
9718   }
9719   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9720   // and shift+add+shift.
9721   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9722 
9723   unsigned ShiftAmt, AddSubOpc;
9724   // Is the shifted value the LHS operand of the add/sub?
9725   bool ShiftValUseIsN0 = true;
9726   // Do we need to negate the result?
9727   bool NegateResult = false;
9728 
9729   if (ConstValue.isNonNegative()) {
9730     // (mul x, 2^N + 1) => (add (shl x, N), x)
9731     // (mul x, 2^N - 1) => (sub (shl x, N), x)
9732     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9733     APInt SCVMinus1 = ShiftedConstValue - 1;
9734     APInt CVPlus1 = ConstValue + 1;
9735     if (SCVMinus1.isPowerOf2()) {
9736       ShiftAmt = SCVMinus1.logBase2();
9737       AddSubOpc = ISD::ADD;
9738     } else if (CVPlus1.isPowerOf2()) {
9739       ShiftAmt = CVPlus1.logBase2();
9740       AddSubOpc = ISD::SUB;
9741     } else
9742       return SDValue();
9743   } else {
9744     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9745     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9746     APInt CVNegPlus1 = -ConstValue + 1;
9747     APInt CVNegMinus1 = -ConstValue - 1;
9748     if (CVNegPlus1.isPowerOf2()) {
9749       ShiftAmt = CVNegPlus1.logBase2();
9750       AddSubOpc = ISD::SUB;
9751       ShiftValUseIsN0 = false;
9752     } else if (CVNegMinus1.isPowerOf2()) {
9753       ShiftAmt = CVNegMinus1.logBase2();
9754       AddSubOpc = ISD::ADD;
9755       NegateResult = true;
9756     } else
9757       return SDValue();
9758   }
9759 
9760   SDLoc DL(N);
9761   EVT VT = N->getValueType(0);
9762   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9763                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
9764 
9765   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9766   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9767   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9768   assert(!(NegateResult && TrailingZeroes) &&
9769          "NegateResult and TrailingZeroes cannot both be true for now.");
9770   // Negate the result.
9771   if (NegateResult)
9772     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9773   // Shift the result.
9774   if (TrailingZeroes)
9775     return DAG.getNode(ISD::SHL, DL, VT, Res,
9776                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9777   return Res;
9778 }
9779 
9780 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9781                                                          SelectionDAG &DAG) {
9782   // Take advantage of vector comparisons producing 0 or -1 in each lane to
9783   // optimize away operation when it's from a constant.
9784   //
9785   // The general transformation is:
9786   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9787   //       AND(VECTOR_CMP(x,y), constant2)
9788   //    constant2 = UNARYOP(constant)
9789 
9790   // Early exit if this isn't a vector operation, the operand of the
9791   // unary operation isn't a bitwise AND, or if the sizes of the operations
9792   // aren't the same.
9793   EVT VT = N->getValueType(0);
9794   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9795       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9796       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9797     return SDValue();
9798 
9799   // Now check that the other operand of the AND is a constant. We could
9800   // make the transformation for non-constant splats as well, but it's unclear
9801   // that would be a benefit as it would not eliminate any operations, just
9802   // perform one more step in scalar code before moving to the vector unit.
9803   if (BuildVectorSDNode *BV =
9804           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9805     // Bail out if the vector isn't a constant.
9806     if (!BV->isConstant())
9807       return SDValue();
9808 
9809     // Everything checks out. Build up the new and improved node.
9810     SDLoc DL(N);
9811     EVT IntVT = BV->getValueType(0);
9812     // Create a new constant of the appropriate type for the transformed
9813     // DAG.
9814     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9815     // The AND node needs bitcasts to/from an integer vector type around it.
9816     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9817     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9818                                  N->getOperand(0)->getOperand(0), MaskConst);
9819     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9820     return Res;
9821   }
9822 
9823   return SDValue();
9824 }
9825 
9826 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9827                                      const AArch64Subtarget *Subtarget) {
9828   // First try to optimize away the conversion when it's conditionally from
9829   // a constant. Vectors only.
9830   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9831     return Res;
9832 
9833   EVT VT = N->getValueType(0);
9834   if (VT != MVT::f32 && VT != MVT::f64)
9835     return SDValue();
9836 
9837   // Only optimize when the source and destination types have the same width.
9838   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9839     return SDValue();
9840 
9841   // If the result of an integer load is only used by an integer-to-float
9842   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9843   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9844   SDValue N0 = N->getOperand(0);
9845   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9846       // Do not change the width of a volatile load.
9847       !cast<LoadSDNode>(N0)->isVolatile()) {
9848     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9849     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9850                                LN0->getPointerInfo(), LN0->getAlignment(),
9851                                LN0->getMemOperand()->getFlags());
9852 
9853     // Make sure successors of the original load stay after it by updating them
9854     // to use the new Chain.
9855     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9856 
9857     unsigned Opcode =
9858         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9859     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9860   }
9861 
9862   return SDValue();
9863 }
9864 
9865 /// Fold a floating-point multiply by power of two into floating-point to
9866 /// fixed-point conversion.
9867 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9868                                      TargetLowering::DAGCombinerInfo &DCI,
9869                                      const AArch64Subtarget *Subtarget) {
9870   if (!Subtarget->hasNEON())
9871     return SDValue();
9872 
9873   if (!N->getValueType(0).isSimple())
9874     return SDValue();
9875 
9876   SDValue Op = N->getOperand(0);
9877   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9878       Op.getOpcode() != ISD::FMUL)
9879     return SDValue();
9880 
9881   SDValue ConstVec = Op->getOperand(1);
9882   if (!isa<BuildVectorSDNode>(ConstVec))
9883     return SDValue();
9884 
9885   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9886   uint32_t FloatBits = FloatTy.getSizeInBits();
9887   if (FloatBits != 32 && FloatBits != 64)
9888     return SDValue();
9889 
9890   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9891   uint32_t IntBits = IntTy.getSizeInBits();
9892   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9893     return SDValue();
9894 
9895   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9896   if (IntBits > FloatBits)
9897     return SDValue();
9898 
9899   BitVector UndefElements;
9900   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9901   int32_t Bits = IntBits == 64 ? 64 : 32;
9902   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9903   if (C == -1 || C == 0 || C > Bits)
9904     return SDValue();
9905 
9906   MVT ResTy;
9907   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9908   switch (NumLanes) {
9909   default:
9910     return SDValue();
9911   case 2:
9912     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9913     break;
9914   case 4:
9915     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9916     break;
9917   }
9918 
9919   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9920     return SDValue();
9921 
9922   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9923          "Illegal vector type after legalization");
9924 
9925   SDLoc DL(N);
9926   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9927   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9928                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
9929   SDValue FixConv =
9930       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9931                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9932                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9933   // We can handle smaller integers by generating an extra trunc.
9934   if (IntBits < FloatBits)
9935     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9936 
9937   return FixConv;
9938 }
9939 
9940 /// Fold a floating-point divide by power of two into fixed-point to
9941 /// floating-point conversion.
9942 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9943                                   TargetLowering::DAGCombinerInfo &DCI,
9944                                   const AArch64Subtarget *Subtarget) {
9945   if (!Subtarget->hasNEON())
9946     return SDValue();
9947 
9948   SDValue Op = N->getOperand(0);
9949   unsigned Opc = Op->getOpcode();
9950   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9951       !Op.getOperand(0).getValueType().isSimple() ||
9952       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9953     return SDValue();
9954 
9955   SDValue ConstVec = N->getOperand(1);
9956   if (!isa<BuildVectorSDNode>(ConstVec))
9957     return SDValue();
9958 
9959   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9960   int32_t IntBits = IntTy.getSizeInBits();
9961   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9962     return SDValue();
9963 
9964   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9965   int32_t FloatBits = FloatTy.getSizeInBits();
9966   if (FloatBits != 32 && FloatBits != 64)
9967     return SDValue();
9968 
9969   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9970   if (IntBits > FloatBits)
9971     return SDValue();
9972 
9973   BitVector UndefElements;
9974   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9975   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9976   if (C == -1 || C == 0 || C > FloatBits)
9977     return SDValue();
9978 
9979   MVT ResTy;
9980   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9981   switch (NumLanes) {
9982   default:
9983     return SDValue();
9984   case 2:
9985     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9986     break;
9987   case 4:
9988     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9989     break;
9990   }
9991 
9992   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9993     return SDValue();
9994 
9995   SDLoc DL(N);
9996   SDValue ConvInput = Op.getOperand(0);
9997   bool IsSigned = Opc == ISD::SINT_TO_FP;
9998   if (IntBits < FloatBits)
9999     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10000                             ResTy, ConvInput);
10001 
10002   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10003                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10004   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10005                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10006                      DAG.getConstant(C, DL, MVT::i32));
10007 }
10008 
10009 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10010 /// searches for and classifies those shifts.
10011 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10012                          bool &FromHi) {
10013   if (N.getOpcode() == ISD::SHL)
10014     FromHi = false;
10015   else if (N.getOpcode() == ISD::SRL)
10016     FromHi = true;
10017   else
10018     return false;
10019 
10020   if (!isa<ConstantSDNode>(N.getOperand(1)))
10021     return false;
10022 
10023   ShiftAmount = N->getConstantOperandVal(1);
10024   Src = N->getOperand(0);
10025   return true;
10026 }
10027 
10028 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10029 /// registers viewed as a high/low pair. This function looks for the pattern:
10030 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10031 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10032 /// aren't independent.
10033 static SDValue tryCombineToEXTR(SDNode *N,
10034                                 TargetLowering::DAGCombinerInfo &DCI) {
10035   SelectionDAG &DAG = DCI.DAG;
10036   SDLoc DL(N);
10037   EVT VT = N->getValueType(0);
10038 
10039   assert(N->getOpcode() == ISD::OR && "Unexpected root");
10040 
10041   if (VT != MVT::i32 && VT != MVT::i64)
10042     return SDValue();
10043 
10044   SDValue LHS;
10045   uint32_t ShiftLHS = 0;
10046   bool LHSFromHi = false;
10047   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10048     return SDValue();
10049 
10050   SDValue RHS;
10051   uint32_t ShiftRHS = 0;
10052   bool RHSFromHi = false;
10053   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10054     return SDValue();
10055 
10056   // If they're both trying to come from the high part of the register, they're
10057   // not really an EXTR.
10058   if (LHSFromHi == RHSFromHi)
10059     return SDValue();
10060 
10061   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10062     return SDValue();
10063 
10064   if (LHSFromHi) {
10065     std::swap(LHS, RHS);
10066     std::swap(ShiftLHS, ShiftRHS);
10067   }
10068 
10069   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10070                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
10071 }
10072 
10073 static SDValue tryCombineToBSL(SDNode *N,
10074                                 TargetLowering::DAGCombinerInfo &DCI) {
10075   EVT VT = N->getValueType(0);
10076   SelectionDAG &DAG = DCI.DAG;
10077   SDLoc DL(N);
10078 
10079   if (!VT.isVector())
10080     return SDValue();
10081 
10082   SDValue N0 = N->getOperand(0);
10083   if (N0.getOpcode() != ISD::AND)
10084     return SDValue();
10085 
10086   SDValue N1 = N->getOperand(1);
10087   if (N1.getOpcode() != ISD::AND)
10088     return SDValue();
10089 
10090   // We only have to look for constant vectors here since the general, variable
10091   // case can be handled in TableGen.
10092   unsigned Bits = VT.getScalarSizeInBits();
10093   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10094   for (int i = 1; i >= 0; --i)
10095     for (int j = 1; j >= 0; --j) {
10096       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10097       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10098       if (!BVN0 || !BVN1)
10099         continue;
10100 
10101       bool FoundMatch = true;
10102       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10103         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10104         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10105         if (!CN0 || !CN1 ||
10106             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10107           FoundMatch = false;
10108           break;
10109         }
10110       }
10111 
10112       if (FoundMatch)
10113         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
10114                            N0->getOperand(1 - i), N1->getOperand(1 - j));
10115     }
10116 
10117   return SDValue();
10118 }
10119 
10120 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10121                                 const AArch64Subtarget *Subtarget) {
10122   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10123   SelectionDAG &DAG = DCI.DAG;
10124   EVT VT = N->getValueType(0);
10125 
10126   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10127     return SDValue();
10128 
10129   if (SDValue Res = tryCombineToEXTR(N, DCI))
10130     return Res;
10131 
10132   if (SDValue Res = tryCombineToBSL(N, DCI))
10133     return Res;
10134 
10135   return SDValue();
10136 }
10137 
10138 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10139   if (!MemVT.getVectorElementType().isSimple())
10140     return false;
10141 
10142   uint64_t MaskForTy = 0ull;
10143   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10144   case MVT::i8:
10145     MaskForTy = 0xffull;
10146     break;
10147   case MVT::i16:
10148     MaskForTy = 0xffffull;
10149     break;
10150   case MVT::i32:
10151     MaskForTy = 0xffffffffull;
10152     break;
10153   default:
10154     return false;
10155     break;
10156   }
10157 
10158   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10159     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10160       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10161 
10162   return false;
10163 }
10164 
10165 static SDValue performSVEAndCombine(SDNode *N,
10166                                     TargetLowering::DAGCombinerInfo &DCI) {
10167   if (DCI.isBeforeLegalizeOps())
10168     return SDValue();
10169 
10170   SDValue Src = N->getOperand(0);
10171   SDValue Mask = N->getOperand(1);
10172 
10173   if (!Src.hasOneUse())
10174     return SDValue();
10175 
10176   // GLD1* instructions perform an implicit zero-extend, which makes them
10177   // perfect candidates for combining.
10178   switch (Src->getOpcode()) {
10179   case AArch64ISD::GLD1:
10180   case AArch64ISD::GLD1_SCALED:
10181   case AArch64ISD::GLD1_SXTW:
10182   case AArch64ISD::GLD1_SXTW_SCALED:
10183   case AArch64ISD::GLD1_UXTW:
10184   case AArch64ISD::GLD1_UXTW_SCALED:
10185   case AArch64ISD::GLD1_IMM:
10186     break;
10187   default:
10188     return SDValue();
10189   }
10190 
10191   EVT MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
10192 
10193   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
10194     return Src;
10195 
10196   return SDValue();
10197 }
10198 
10199 static SDValue performANDCombine(SDNode *N,
10200                                  TargetLowering::DAGCombinerInfo &DCI) {
10201   SelectionDAG &DAG = DCI.DAG;
10202   SDValue LHS = N->getOperand(0);
10203   EVT VT = N->getValueType(0);
10204   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
10205     return SDValue();
10206 
10207   if (VT.isScalableVector())
10208     return performSVEAndCombine(N, DCI);
10209 
10210   BuildVectorSDNode *BVN =
10211       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
10212   if (!BVN)
10213     return SDValue();
10214 
10215   // AND does not accept an immediate, so check if we can use a BIC immediate
10216   // instruction instead. We do this here instead of using a (and x, (mvni imm))
10217   // pattern in isel, because some immediates may be lowered to the preferred
10218   // (and x, (movi imm)) form, even though an mvni representation also exists.
10219   APInt DefBits(VT.getSizeInBits(), 0);
10220   APInt UndefBits(VT.getSizeInBits(), 0);
10221   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10222     SDValue NewOp;
10223 
10224     DefBits = ~DefBits;
10225     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10226                                     DefBits, &LHS)) ||
10227         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10228                                     DefBits, &LHS)))
10229       return NewOp;
10230 
10231     UndefBits = ~UndefBits;
10232     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10233                                     UndefBits, &LHS)) ||
10234         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10235                                     UndefBits, &LHS)))
10236       return NewOp;
10237   }
10238 
10239   return SDValue();
10240 }
10241 
10242 static SDValue performSRLCombine(SDNode *N,
10243                                  TargetLowering::DAGCombinerInfo &DCI) {
10244   SelectionDAG &DAG = DCI.DAG;
10245   EVT VT = N->getValueType(0);
10246   if (VT != MVT::i32 && VT != MVT::i64)
10247     return SDValue();
10248 
10249   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
10250   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
10251   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
10252   SDValue N0 = N->getOperand(0);
10253   if (N0.getOpcode() == ISD::BSWAP) {
10254     SDLoc DL(N);
10255     SDValue N1 = N->getOperand(1);
10256     SDValue N00 = N0.getOperand(0);
10257     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10258       uint64_t ShiftAmt = C->getZExtValue();
10259       if (VT == MVT::i32 && ShiftAmt == 16 &&
10260           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
10261         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10262       if (VT == MVT::i64 && ShiftAmt == 32 &&
10263           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
10264         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10265     }
10266   }
10267   return SDValue();
10268 }
10269 
10270 static SDValue performConcatVectorsCombine(SDNode *N,
10271                                            TargetLowering::DAGCombinerInfo &DCI,
10272                                            SelectionDAG &DAG) {
10273   SDLoc dl(N);
10274   EVT VT = N->getValueType(0);
10275   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
10276 
10277   // Optimize concat_vectors of truncated vectors, where the intermediate
10278   // type is illegal, to avoid said illegality,  e.g.,
10279   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
10280   //                          (v2i16 (truncate (v2i64)))))
10281   // ->
10282   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10283   //                                    (v4i32 (bitcast (v2i64))),
10284   //                                    <0, 2, 4, 6>)))
10285   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10286   // on both input and result type, so we might generate worse code.
10287   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10288   if (N->getNumOperands() == 2 &&
10289       N0->getOpcode() == ISD::TRUNCATE &&
10290       N1->getOpcode() == ISD::TRUNCATE) {
10291     SDValue N00 = N0->getOperand(0);
10292     SDValue N10 = N1->getOperand(0);
10293     EVT N00VT = N00.getValueType();
10294 
10295     if (N00VT == N10.getValueType() &&
10296         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10297         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10298       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10299       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10300       for (size_t i = 0; i < Mask.size(); ++i)
10301         Mask[i] = i * 2;
10302       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10303                          DAG.getVectorShuffle(
10304                              MidVT, dl,
10305                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10306                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10307     }
10308   }
10309 
10310   // Wait 'til after everything is legalized to try this. That way we have
10311   // legal vector types and such.
10312   if (DCI.isBeforeLegalizeOps())
10313     return SDValue();
10314 
10315   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10316   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10317   // canonicalise to that.
10318   if (N0 == N1 && VT.getVectorNumElements() == 2) {
10319     assert(VT.getScalarSizeInBits() == 64);
10320     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10321                        DAG.getConstant(0, dl, MVT::i64));
10322   }
10323 
10324   // Canonicalise concat_vectors so that the right-hand vector has as few
10325   // bit-casts as possible before its real operation. The primary matching
10326   // destination for these operations will be the narrowing "2" instructions,
10327   // which depend on the operation being performed on this right-hand vector.
10328   // For example,
10329   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
10330   // becomes
10331   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10332 
10333   if (N1->getOpcode() != ISD::BITCAST)
10334     return SDValue();
10335   SDValue RHS = N1->getOperand(0);
10336   MVT RHSTy = RHS.getValueType().getSimpleVT();
10337   // If the RHS is not a vector, this is not the pattern we're looking for.
10338   if (!RHSTy.isVector())
10339     return SDValue();
10340 
10341   LLVM_DEBUG(
10342       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10343 
10344   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10345                                   RHSTy.getVectorNumElements() * 2);
10346   return DAG.getNode(ISD::BITCAST, dl, VT,
10347                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10348                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10349                                  RHS));
10350 }
10351 
10352 static SDValue tryCombineFixedPointConvert(SDNode *N,
10353                                            TargetLowering::DAGCombinerInfo &DCI,
10354                                            SelectionDAG &DAG) {
10355   // Wait until after everything is legalized to try this. That way we have
10356   // legal vector types and such.
10357   if (DCI.isBeforeLegalizeOps())
10358     return SDValue();
10359   // Transform a scalar conversion of a value from a lane extract into a
10360   // lane extract of a vector conversion. E.g., from foo1 to foo2:
10361   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10362   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10363   //
10364   // The second form interacts better with instruction selection and the
10365   // register allocator to avoid cross-class register copies that aren't
10366   // coalescable due to a lane reference.
10367 
10368   // Check the operand and see if it originates from a lane extract.
10369   SDValue Op1 = N->getOperand(1);
10370   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10371     // Yep, no additional predication needed. Perform the transform.
10372     SDValue IID = N->getOperand(0);
10373     SDValue Shift = N->getOperand(2);
10374     SDValue Vec = Op1.getOperand(0);
10375     SDValue Lane = Op1.getOperand(1);
10376     EVT ResTy = N->getValueType(0);
10377     EVT VecResTy;
10378     SDLoc DL(N);
10379 
10380     // The vector width should be 128 bits by the time we get here, even
10381     // if it started as 64 bits (the extract_vector handling will have
10382     // done so).
10383     assert(Vec.getValueSizeInBits() == 128 &&
10384            "unexpected vector size on extract_vector_elt!");
10385     if (Vec.getValueType() == MVT::v4i32)
10386       VecResTy = MVT::v4f32;
10387     else if (Vec.getValueType() == MVT::v2i64)
10388       VecResTy = MVT::v2f64;
10389     else
10390       llvm_unreachable("unexpected vector type!");
10391 
10392     SDValue Convert =
10393         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10394     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10395   }
10396   return SDValue();
10397 }
10398 
10399 // AArch64 high-vector "long" operations are formed by performing the non-high
10400 // version on an extract_subvector of each operand which gets the high half:
10401 //
10402 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10403 //
10404 // However, there are cases which don't have an extract_high explicitly, but
10405 // have another operation that can be made compatible with one for free. For
10406 // example:
10407 //
10408 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
10409 //
10410 // This routine does the actual conversion of such DUPs, once outer routines
10411 // have determined that everything else is in order.
10412 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10413 // similarly here.
10414 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10415   switch (N.getOpcode()) {
10416   case AArch64ISD::DUP:
10417   case AArch64ISD::DUPLANE8:
10418   case AArch64ISD::DUPLANE16:
10419   case AArch64ISD::DUPLANE32:
10420   case AArch64ISD::DUPLANE64:
10421   case AArch64ISD::MOVI:
10422   case AArch64ISD::MOVIshift:
10423   case AArch64ISD::MOVIedit:
10424   case AArch64ISD::MOVImsl:
10425   case AArch64ISD::MVNIshift:
10426   case AArch64ISD::MVNImsl:
10427     break;
10428   default:
10429     // FMOV could be supported, but isn't very useful, as it would only occur
10430     // if you passed a bitcast' floating point immediate to an eligible long
10431     // integer op (addl, smull, ...).
10432     return SDValue();
10433   }
10434 
10435   MVT NarrowTy = N.getSimpleValueType();
10436   if (!NarrowTy.is64BitVector())
10437     return SDValue();
10438 
10439   MVT ElementTy = NarrowTy.getVectorElementType();
10440   unsigned NumElems = NarrowTy.getVectorNumElements();
10441   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10442 
10443   SDLoc dl(N);
10444   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10445                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10446                      DAG.getConstant(NumElems, dl, MVT::i64));
10447 }
10448 
10449 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10450   if (N.getOpcode() == ISD::BITCAST)
10451     N = N.getOperand(0);
10452   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10453     return false;
10454   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10455          N.getOperand(0).getValueType().getVectorNumElements() / 2;
10456 }
10457 
10458 /// Helper structure to keep track of ISD::SET_CC operands.
10459 struct GenericSetCCInfo {
10460   const SDValue *Opnd0;
10461   const SDValue *Opnd1;
10462   ISD::CondCode CC;
10463 };
10464 
10465 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10466 struct AArch64SetCCInfo {
10467   const SDValue *Cmp;
10468   AArch64CC::CondCode CC;
10469 };
10470 
10471 /// Helper structure to keep track of SetCC information.
10472 union SetCCInfo {
10473   GenericSetCCInfo Generic;
10474   AArch64SetCCInfo AArch64;
10475 };
10476 
10477 /// Helper structure to be able to read SetCC information.  If set to
10478 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10479 /// GenericSetCCInfo.
10480 struct SetCCInfoAndKind {
10481   SetCCInfo Info;
10482   bool IsAArch64;
10483 };
10484 
10485 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10486 /// an
10487 /// AArch64 lowered one.
10488 /// \p SetCCInfo is filled accordingly.
10489 /// \post SetCCInfo is meanginfull only when this function returns true.
10490 /// \return True when Op is a kind of SET_CC operation.
10491 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10492   // If this is a setcc, this is straight forward.
10493   if (Op.getOpcode() == ISD::SETCC) {
10494     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10495     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10496     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10497     SetCCInfo.IsAArch64 = false;
10498     return true;
10499   }
10500   // Otherwise, check if this is a matching csel instruction.
10501   // In other words:
10502   // - csel 1, 0, cc
10503   // - csel 0, 1, !cc
10504   if (Op.getOpcode() != AArch64ISD::CSEL)
10505     return false;
10506   // Set the information about the operands.
10507   // TODO: we want the operands of the Cmp not the csel
10508   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10509   SetCCInfo.IsAArch64 = true;
10510   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10511       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10512 
10513   // Check that the operands matches the constraints:
10514   // (1) Both operands must be constants.
10515   // (2) One must be 1 and the other must be 0.
10516   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10517   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10518 
10519   // Check (1).
10520   if (!TValue || !FValue)
10521     return false;
10522 
10523   // Check (2).
10524   if (!TValue->isOne()) {
10525     // Update the comparison when we are interested in !cc.
10526     std::swap(TValue, FValue);
10527     SetCCInfo.Info.AArch64.CC =
10528         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10529   }
10530   return TValue->isOne() && FValue->isNullValue();
10531 }
10532 
10533 // Returns true if Op is setcc or zext of setcc.
10534 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10535   if (isSetCC(Op, Info))
10536     return true;
10537   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10538     isSetCC(Op->getOperand(0), Info));
10539 }
10540 
10541 // The folding we want to perform is:
10542 // (add x, [zext] (setcc cc ...) )
10543 //   -->
10544 // (csel x, (add x, 1), !cc ...)
10545 //
10546 // The latter will get matched to a CSINC instruction.
10547 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10548   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10549   SDValue LHS = Op->getOperand(0);
10550   SDValue RHS = Op->getOperand(1);
10551   SetCCInfoAndKind InfoAndKind;
10552 
10553   // If neither operand is a SET_CC, give up.
10554   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10555     std::swap(LHS, RHS);
10556     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10557       return SDValue();
10558   }
10559 
10560   // FIXME: This could be generatized to work for FP comparisons.
10561   EVT CmpVT = InfoAndKind.IsAArch64
10562                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10563                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10564   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10565     return SDValue();
10566 
10567   SDValue CCVal;
10568   SDValue Cmp;
10569   SDLoc dl(Op);
10570   if (InfoAndKind.IsAArch64) {
10571     CCVal = DAG.getConstant(
10572         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10573         MVT::i32);
10574     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10575   } else
10576     Cmp = getAArch64Cmp(
10577         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
10578         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
10579         dl);
10580 
10581   EVT VT = Op->getValueType(0);
10582   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10583   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10584 }
10585 
10586 // The basic add/sub long vector instructions have variants with "2" on the end
10587 // which act on the high-half of their inputs. They are normally matched by
10588 // patterns like:
10589 //
10590 // (add (zeroext (extract_high LHS)),
10591 //      (zeroext (extract_high RHS)))
10592 // -> uaddl2 vD, vN, vM
10593 //
10594 // However, if one of the extracts is something like a duplicate, this
10595 // instruction can still be used profitably. This function puts the DAG into a
10596 // more appropriate form for those patterns to trigger.
10597 static SDValue performAddSubLongCombine(SDNode *N,
10598                                         TargetLowering::DAGCombinerInfo &DCI,
10599                                         SelectionDAG &DAG) {
10600   if (DCI.isBeforeLegalizeOps())
10601     return SDValue();
10602 
10603   MVT VT = N->getSimpleValueType(0);
10604   if (!VT.is128BitVector()) {
10605     if (N->getOpcode() == ISD::ADD)
10606       return performSetccAddFolding(N, DAG);
10607     return SDValue();
10608   }
10609 
10610   // Make sure both branches are extended in the same way.
10611   SDValue LHS = N->getOperand(0);
10612   SDValue RHS = N->getOperand(1);
10613   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10614        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10615       LHS.getOpcode() != RHS.getOpcode())
10616     return SDValue();
10617 
10618   unsigned ExtType = LHS.getOpcode();
10619 
10620   // It's not worth doing if at least one of the inputs isn't already an
10621   // extract, but we don't know which it'll be so we have to try both.
10622   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10623     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10624     if (!RHS.getNode())
10625       return SDValue();
10626 
10627     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10628   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10629     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10630     if (!LHS.getNode())
10631       return SDValue();
10632 
10633     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10634   }
10635 
10636   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10637 }
10638 
10639 // Massage DAGs which we can use the high-half "long" operations on into
10640 // something isel will recognize better. E.g.
10641 //
10642 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10643 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10644 //                     (extract_high (v2i64 (dup128 scalar)))))
10645 //
10646 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10647                                        TargetLowering::DAGCombinerInfo &DCI,
10648                                        SelectionDAG &DAG) {
10649   if (DCI.isBeforeLegalizeOps())
10650     return SDValue();
10651 
10652   SDValue LHS = N->getOperand(1);
10653   SDValue RHS = N->getOperand(2);
10654   assert(LHS.getValueType().is64BitVector() &&
10655          RHS.getValueType().is64BitVector() &&
10656          "unexpected shape for long operation");
10657 
10658   // Either node could be a DUP, but it's not worth doing both of them (you'd
10659   // just as well use the non-high version) so look for a corresponding extract
10660   // operation on the other "wing".
10661   if (isEssentiallyExtractHighSubvector(LHS)) {
10662     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10663     if (!RHS.getNode())
10664       return SDValue();
10665   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10666     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10667     if (!LHS.getNode())
10668       return SDValue();
10669   }
10670 
10671   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10672                      N->getOperand(0), LHS, RHS);
10673 }
10674 
10675 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10676   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10677   unsigned ElemBits = ElemTy.getSizeInBits();
10678 
10679   int64_t ShiftAmount;
10680   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10681     APInt SplatValue, SplatUndef;
10682     unsigned SplatBitSize;
10683     bool HasAnyUndefs;
10684     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10685                               HasAnyUndefs, ElemBits) ||
10686         SplatBitSize != ElemBits)
10687       return SDValue();
10688 
10689     ShiftAmount = SplatValue.getSExtValue();
10690   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10691     ShiftAmount = CVN->getSExtValue();
10692   } else
10693     return SDValue();
10694 
10695   unsigned Opcode;
10696   bool IsRightShift;
10697   switch (IID) {
10698   default:
10699     llvm_unreachable("Unknown shift intrinsic");
10700   case Intrinsic::aarch64_neon_sqshl:
10701     Opcode = AArch64ISD::SQSHL_I;
10702     IsRightShift = false;
10703     break;
10704   case Intrinsic::aarch64_neon_uqshl:
10705     Opcode = AArch64ISD::UQSHL_I;
10706     IsRightShift = false;
10707     break;
10708   case Intrinsic::aarch64_neon_srshl:
10709     Opcode = AArch64ISD::SRSHR_I;
10710     IsRightShift = true;
10711     break;
10712   case Intrinsic::aarch64_neon_urshl:
10713     Opcode = AArch64ISD::URSHR_I;
10714     IsRightShift = true;
10715     break;
10716   case Intrinsic::aarch64_neon_sqshlu:
10717     Opcode = AArch64ISD::SQSHLU_I;
10718     IsRightShift = false;
10719     break;
10720   case Intrinsic::aarch64_neon_sshl:
10721   case Intrinsic::aarch64_neon_ushl:
10722     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
10723     // left shift for positive shift amounts. Below, we only replace the current
10724     // node with VSHL, if this condition is met.
10725     Opcode = AArch64ISD::VSHL;
10726     IsRightShift = false;
10727     break;
10728   }
10729 
10730   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10731     SDLoc dl(N);
10732     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10733                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10734   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10735     SDLoc dl(N);
10736     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10737                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
10738   }
10739 
10740   return SDValue();
10741 }
10742 
10743 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10744 // the intrinsics must be legal and take an i32, this means there's almost
10745 // certainly going to be a zext in the DAG which we can eliminate.
10746 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10747   SDValue AndN = N->getOperand(2);
10748   if (AndN.getOpcode() != ISD::AND)
10749     return SDValue();
10750 
10751   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10752   if (!CMask || CMask->getZExtValue() != Mask)
10753     return SDValue();
10754 
10755   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10756                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10757 }
10758 
10759 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10760                                            SelectionDAG &DAG) {
10761   SDLoc dl(N);
10762   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10763                      DAG.getNode(Opc, dl,
10764                                  N->getOperand(1).getSimpleValueType(),
10765                                  N->getOperand(1)),
10766                      DAG.getConstant(0, dl, MVT::i64));
10767 }
10768 
10769 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
10770                                     SelectionDAG &DAG) {
10771   SDLoc dl(N);
10772   LLVMContext &Ctx = *DAG.getContext();
10773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10774 
10775   EVT VT = N->getValueType(0);
10776   SDValue Pred = N->getOperand(1);
10777   SDValue Data = N->getOperand(2);
10778   EVT DataVT = Data.getValueType();
10779 
10780   if (DataVT.getVectorElementType().isScalarInteger() &&
10781       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
10782     if (!TLI.isTypeLegal(DataVT))
10783       return SDValue();
10784 
10785     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
10786       AArch64::NeonBitsPerVector / VT.getSizeInBits());
10787     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
10788     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
10789     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
10790 
10791     return Result;
10792   }
10793 
10794   return SDValue();
10795 }
10796 
10797 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
10798   SDLoc dl(N);
10799   LLVMContext &Ctx = *DAG.getContext();
10800   EVT VT = N->getValueType(0);
10801 
10802   assert(VT.isScalableVector() && "Expected a scalable vector.");
10803 
10804   // Current lowering only supports the SVE-ACLE types.
10805   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
10806     return SDValue();
10807 
10808   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
10809   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
10810   EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
10811 
10812   // Convert everything to the domain of EXT (i.e bytes).
10813   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
10814   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
10815   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
10816                             DAG.getConstant(ElemSize, dl, MVT::i32));
10817 
10818   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
10819   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
10820 }
10821 
10822 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID,
10823                                         bool Invert,
10824                                         TargetLowering::DAGCombinerInfo &DCI,
10825                                         SelectionDAG &DAG) {
10826   if (DCI.isBeforeLegalize())
10827     return SDValue();
10828 
10829   SDValue Comparator = N->getOperand(3);
10830   if (Comparator.getOpcode() == AArch64ISD::DUP ||
10831       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
10832     unsigned IID = getIntrinsicID(N);
10833     EVT VT = N->getValueType(0);
10834     EVT CmpVT = N->getOperand(2).getValueType();
10835     SDValue Pred = N->getOperand(1);
10836     SDValue Imm;
10837     SDLoc DL(N);
10838 
10839     switch (IID) {
10840     default:
10841       llvm_unreachable("Called with wrong intrinsic!");
10842       break;
10843 
10844     // Signed comparisons
10845     case Intrinsic::aarch64_sve_cmpeq_wide:
10846     case Intrinsic::aarch64_sve_cmpne_wide:
10847     case Intrinsic::aarch64_sve_cmpge_wide:
10848     case Intrinsic::aarch64_sve_cmpgt_wide:
10849     case Intrinsic::aarch64_sve_cmplt_wide:
10850     case Intrinsic::aarch64_sve_cmple_wide: {
10851       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10852         int64_t ImmVal = CN->getSExtValue();
10853         if (ImmVal >= -16 && ImmVal <= 15)
10854           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10855         else
10856           return SDValue();
10857       }
10858       break;
10859     }
10860     // Unsigned comparisons
10861     case Intrinsic::aarch64_sve_cmphs_wide:
10862     case Intrinsic::aarch64_sve_cmphi_wide:
10863     case Intrinsic::aarch64_sve_cmplo_wide:
10864     case Intrinsic::aarch64_sve_cmpls_wide:  {
10865       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10866         uint64_t ImmVal = CN->getZExtValue();
10867         if (ImmVal <= 127)
10868           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10869         else
10870           return SDValue();
10871       }
10872       break;
10873     }
10874     }
10875 
10876     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
10877     SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64);
10878     SDValue Op0, Op1;
10879     if (Invert) {
10880       Op0 = Splat;
10881       Op1 = N->getOperand(2);
10882     } else {
10883       Op0 = N->getOperand(2);
10884       Op1 = Splat;
10885     }
10886     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10887                        ID, Pred, Op0, Op1);
10888   }
10889 
10890   return SDValue();
10891 }
10892 
10893 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
10894                         AArch64CC::CondCode Cond) {
10895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10896 
10897   SDLoc DL(Op);
10898   assert(Op.getValueType().isScalableVector() &&
10899          TLI.isTypeLegal(Op.getValueType()) &&
10900          "Expected legal scalable vector type!");
10901 
10902   // Ensure target specific opcodes are using legal type.
10903   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
10904   SDValue TVal = DAG.getConstant(1, DL, OutVT);
10905   SDValue FVal = DAG.getConstant(0, DL, OutVT);
10906 
10907   // Set condition code (CC) flags.
10908   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
10909 
10910   // Convert CC to integer based on requested condition.
10911   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
10912   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
10913   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
10914   return DAG.getZExtOrTrunc(Res, DL, VT);
10915 }
10916 
10917 static SDValue performIntrinsicCombine(SDNode *N,
10918                                        TargetLowering::DAGCombinerInfo &DCI,
10919                                        const AArch64Subtarget *Subtarget) {
10920   SelectionDAG &DAG = DCI.DAG;
10921   unsigned IID = getIntrinsicID(N);
10922   switch (IID) {
10923   default:
10924     break;
10925   case Intrinsic::aarch64_neon_vcvtfxs2fp:
10926   case Intrinsic::aarch64_neon_vcvtfxu2fp:
10927     return tryCombineFixedPointConvert(N, DCI, DAG);
10928   case Intrinsic::aarch64_neon_saddv:
10929     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10930   case Intrinsic::aarch64_neon_uaddv:
10931     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10932   case Intrinsic::aarch64_neon_sminv:
10933     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10934   case Intrinsic::aarch64_neon_uminv:
10935     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10936   case Intrinsic::aarch64_neon_smaxv:
10937     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10938   case Intrinsic::aarch64_neon_umaxv:
10939     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10940   case Intrinsic::aarch64_neon_fmax:
10941     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10942                        N->getOperand(1), N->getOperand(2));
10943   case Intrinsic::aarch64_neon_fmin:
10944     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10945                        N->getOperand(1), N->getOperand(2));
10946   case Intrinsic::aarch64_neon_fmaxnm:
10947     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10948                        N->getOperand(1), N->getOperand(2));
10949   case Intrinsic::aarch64_neon_fminnm:
10950     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10951                        N->getOperand(1), N->getOperand(2));
10952   case Intrinsic::aarch64_neon_smull:
10953   case Intrinsic::aarch64_neon_umull:
10954   case Intrinsic::aarch64_neon_pmull:
10955   case Intrinsic::aarch64_neon_sqdmull:
10956     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10957   case Intrinsic::aarch64_neon_sqshl:
10958   case Intrinsic::aarch64_neon_uqshl:
10959   case Intrinsic::aarch64_neon_sqshlu:
10960   case Intrinsic::aarch64_neon_srshl:
10961   case Intrinsic::aarch64_neon_urshl:
10962   case Intrinsic::aarch64_neon_sshl:
10963   case Intrinsic::aarch64_neon_ushl:
10964     return tryCombineShiftImm(IID, N, DAG);
10965   case Intrinsic::aarch64_crc32b:
10966   case Intrinsic::aarch64_crc32cb:
10967     return tryCombineCRC32(0xff, N, DAG);
10968   case Intrinsic::aarch64_crc32h:
10969   case Intrinsic::aarch64_crc32ch:
10970     return tryCombineCRC32(0xffff, N, DAG);
10971   case Intrinsic::aarch64_sve_smaxv:
10972     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
10973   case Intrinsic::aarch64_sve_umaxv:
10974     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
10975   case Intrinsic::aarch64_sve_sminv:
10976     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
10977   case Intrinsic::aarch64_sve_uminv:
10978     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
10979   case Intrinsic::aarch64_sve_orv:
10980     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
10981   case Intrinsic::aarch64_sve_eorv:
10982     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
10983   case Intrinsic::aarch64_sve_andv:
10984     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
10985   case Intrinsic::aarch64_sve_ext:
10986     return LowerSVEIntrinsicEXT(N, DAG);
10987   case Intrinsic::aarch64_sve_cmpeq_wide:
10988     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq,
10989                                     false, DCI, DAG);
10990   case Intrinsic::aarch64_sve_cmpne_wide:
10991     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne,
10992                                     false, DCI, DAG);
10993   case Intrinsic::aarch64_sve_cmpge_wide:
10994     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
10995                                     false, DCI, DAG);
10996   case Intrinsic::aarch64_sve_cmpgt_wide:
10997     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
10998                                     false, DCI, DAG);
10999   case Intrinsic::aarch64_sve_cmplt_wide:
11000     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11001                                     true, DCI, DAG);
11002   case Intrinsic::aarch64_sve_cmple_wide:
11003     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11004                                     true, DCI, DAG);
11005   case Intrinsic::aarch64_sve_cmphs_wide:
11006     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs,
11007                                     false, DCI, DAG);
11008   case Intrinsic::aarch64_sve_cmphi_wide:
11009     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi,
11010                                     false, DCI, DAG);
11011   case Intrinsic::aarch64_sve_cmplo_wide:
11012     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true,
11013                                     DCI, DAG);
11014   case Intrinsic::aarch64_sve_cmpls_wide:
11015     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true,
11016                                     DCI, DAG);
11017   case Intrinsic::aarch64_sve_ptest_any:
11018     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11019                     AArch64CC::ANY_ACTIVE);
11020   case Intrinsic::aarch64_sve_ptest_first:
11021     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11022                     AArch64CC::FIRST_ACTIVE);
11023   case Intrinsic::aarch64_sve_ptest_last:
11024     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11025                     AArch64CC::LAST_ACTIVE);
11026   }
11027   return SDValue();
11028 }
11029 
11030 static SDValue performExtendCombine(SDNode *N,
11031                                     TargetLowering::DAGCombinerInfo &DCI,
11032                                     SelectionDAG &DAG) {
11033   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
11034   // we can convert that DUP into another extract_high (of a bigger DUP), which
11035   // helps the backend to decide that an sabdl2 would be useful, saving a real
11036   // extract_high operation.
11037   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
11038       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
11039     SDNode *ABDNode = N->getOperand(0).getNode();
11040     unsigned IID = getIntrinsicID(ABDNode);
11041     if (IID == Intrinsic::aarch64_neon_sabd ||
11042         IID == Intrinsic::aarch64_neon_uabd) {
11043       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
11044       if (!NewABD.getNode())
11045         return SDValue();
11046 
11047       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
11048                          NewABD);
11049     }
11050   }
11051 
11052   // This is effectively a custom type legalization for AArch64.
11053   //
11054   // Type legalization will split an extend of a small, legal, type to a larger
11055   // illegal type by first splitting the destination type, often creating
11056   // illegal source types, which then get legalized in isel-confusing ways,
11057   // leading to really terrible codegen. E.g.,
11058   //   %result = v8i32 sext v8i8 %value
11059   // becomes
11060   //   %losrc = extract_subreg %value, ...
11061   //   %hisrc = extract_subreg %value, ...
11062   //   %lo = v4i32 sext v4i8 %losrc
11063   //   %hi = v4i32 sext v4i8 %hisrc
11064   // Things go rapidly downhill from there.
11065   //
11066   // For AArch64, the [sz]ext vector instructions can only go up one element
11067   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
11068   // take two instructions.
11069   //
11070   // This implies that the most efficient way to do the extend from v8i8
11071   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
11072   // the normal splitting to happen for the v8i16->v8i32.
11073 
11074   // This is pre-legalization to catch some cases where the default
11075   // type legalization will create ill-tempered code.
11076   if (!DCI.isBeforeLegalizeOps())
11077     return SDValue();
11078 
11079   // We're only interested in cleaning things up for non-legal vector types
11080   // here. If both the source and destination are legal, things will just
11081   // work naturally without any fiddling.
11082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11083   EVT ResVT = N->getValueType(0);
11084   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
11085     return SDValue();
11086   // If the vector type isn't a simple VT, it's beyond the scope of what
11087   // we're  worried about here. Let legalization do its thing and hope for
11088   // the best.
11089   SDValue Src = N->getOperand(0);
11090   EVT SrcVT = Src->getValueType(0);
11091   if (!ResVT.isSimple() || !SrcVT.isSimple())
11092     return SDValue();
11093 
11094   // If the source VT is a 64-bit vector, we can play games and get the
11095   // better results we want.
11096   if (SrcVT.getSizeInBits() != 64)
11097     return SDValue();
11098 
11099   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
11100   unsigned ElementCount = SrcVT.getVectorNumElements();
11101   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
11102   SDLoc DL(N);
11103   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
11104 
11105   // Now split the rest of the operation into two halves, each with a 64
11106   // bit source.
11107   EVT LoVT, HiVT;
11108   SDValue Lo, Hi;
11109   unsigned NumElements = ResVT.getVectorNumElements();
11110   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
11111   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
11112                                  ResVT.getVectorElementType(), NumElements / 2);
11113 
11114   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
11115                                LoVT.getVectorNumElements());
11116   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11117                    DAG.getConstant(0, DL, MVT::i64));
11118   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11119                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
11120   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
11121   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
11122 
11123   // Now combine the parts back together so we still have a single result
11124   // like the combiner expects.
11125   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
11126 }
11127 
11128 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
11129                                SDValue SplatVal, unsigned NumVecElts) {
11130   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
11131   unsigned OrigAlignment = St.getAlignment();
11132   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
11133 
11134   // Create scalar stores. This is at least as good as the code sequence for a
11135   // split unaligned store which is a dup.s, ext.b, and two stores.
11136   // Most of the time the three stores should be replaced by store pair
11137   // instructions (stp).
11138   SDLoc DL(&St);
11139   SDValue BasePtr = St.getBasePtr();
11140   uint64_t BaseOffset = 0;
11141 
11142   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
11143   SDValue NewST1 =
11144       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
11145                    OrigAlignment, St.getMemOperand()->getFlags());
11146 
11147   // As this in ISel, we will not merge this add which may degrade results.
11148   if (BasePtr->getOpcode() == ISD::ADD &&
11149       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
11150     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
11151     BasePtr = BasePtr->getOperand(0);
11152   }
11153 
11154   unsigned Offset = EltOffset;
11155   while (--NumVecElts) {
11156     unsigned Alignment = MinAlign(OrigAlignment, Offset);
11157     SDValue OffsetPtr =
11158         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11159                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
11160     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
11161                           PtrInfo.getWithOffset(Offset), Alignment,
11162                           St.getMemOperand()->getFlags());
11163     Offset += EltOffset;
11164   }
11165   return NewST1;
11166 }
11167 
11168 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
11169   SDLoc DL(N);
11170   EVT VT = N->getValueType(0);
11171   EVT PtrTy = N->getOperand(3).getValueType();
11172 
11173   EVT LoadVT = VT;
11174   if (VT.isFloatingPoint())
11175     LoadVT = VT.changeTypeToInteger();
11176 
11177   auto *MINode = cast<MemIntrinsicSDNode>(N);
11178   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
11179   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
11180                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
11181                                 MINode->getOperand(2), PassThru,
11182                                 MINode->getMemoryVT(), MINode->getMemOperand(),
11183                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
11184 
11185    if (VT.isFloatingPoint()) {
11186      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
11187      return DAG.getMergeValues(Ops, DL);
11188    }
11189 
11190   return L;
11191 }
11192 
11193 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
11194   SDLoc DL(N);
11195 
11196   SDValue Data = N->getOperand(2);
11197   EVT DataVT = Data.getValueType();
11198   EVT PtrTy = N->getOperand(4).getValueType();
11199 
11200   if (DataVT.isFloatingPoint())
11201     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
11202 
11203   auto *MINode = cast<MemIntrinsicSDNode>(N);
11204   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
11205                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
11206                             MINode->getMemoryVT(), MINode->getMemOperand(),
11207                             ISD::UNINDEXED, false, false);
11208 }
11209 
11210 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
11211 /// load store optimizer pass will merge them to store pair stores.  This should
11212 /// be better than a movi to create the vector zero followed by a vector store
11213 /// if the zero constant is not re-used, since one instructions and one register
11214 /// live range will be removed.
11215 ///
11216 /// For example, the final generated code should be:
11217 ///
11218 ///   stp xzr, xzr, [x0]
11219 ///
11220 /// instead of:
11221 ///
11222 ///   movi v0.2d, #0
11223 ///   str q0, [x0]
11224 ///
11225 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11226   SDValue StVal = St.getValue();
11227   EVT VT = StVal.getValueType();
11228 
11229   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
11230   // 2, 3 or 4 i32 elements.
11231   int NumVecElts = VT.getVectorNumElements();
11232   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
11233          VT.getVectorElementType().getSizeInBits() == 64) ||
11234         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
11235          VT.getVectorElementType().getSizeInBits() == 32)))
11236     return SDValue();
11237 
11238   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
11239     return SDValue();
11240 
11241   // If the zero constant has more than one use then the vector store could be
11242   // better since the constant mov will be amortized and stp q instructions
11243   // should be able to be formed.
11244   if (!StVal.hasOneUse())
11245     return SDValue();
11246 
11247   // If the store is truncating then it's going down to i16 or smaller, which
11248   // means it can be implemented in a single store anyway.
11249   if (St.isTruncatingStore())
11250     return SDValue();
11251 
11252   // If the immediate offset of the address operand is too large for the stp
11253   // instruction, then bail out.
11254   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
11255     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
11256     if (Offset < -512 || Offset > 504)
11257       return SDValue();
11258   }
11259 
11260   for (int I = 0; I < NumVecElts; ++I) {
11261     SDValue EltVal = StVal.getOperand(I);
11262     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
11263       return SDValue();
11264   }
11265 
11266   // Use a CopyFromReg WZR/XZR here to prevent
11267   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
11268   SDLoc DL(&St);
11269   unsigned ZeroReg;
11270   EVT ZeroVT;
11271   if (VT.getVectorElementType().getSizeInBits() == 32) {
11272     ZeroReg = AArch64::WZR;
11273     ZeroVT = MVT::i32;
11274   } else {
11275     ZeroReg = AArch64::XZR;
11276     ZeroVT = MVT::i64;
11277   }
11278   SDValue SplatVal =
11279       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
11280   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11281 }
11282 
11283 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
11284 /// value. The load store optimizer pass will merge them to store pair stores.
11285 /// This has better performance than a splat of the scalar followed by a split
11286 /// vector store. Even if the stores are not merged it is four stores vs a dup,
11287 /// followed by an ext.b and two stores.
11288 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11289   SDValue StVal = St.getValue();
11290   EVT VT = StVal.getValueType();
11291 
11292   // Don't replace floating point stores, they possibly won't be transformed to
11293   // stp because of the store pair suppress pass.
11294   if (VT.isFloatingPoint())
11295     return SDValue();
11296 
11297   // We can express a splat as store pair(s) for 2 or 4 elements.
11298   unsigned NumVecElts = VT.getVectorNumElements();
11299   if (NumVecElts != 4 && NumVecElts != 2)
11300     return SDValue();
11301 
11302   // If the store is truncating then it's going down to i16 or smaller, which
11303   // means it can be implemented in a single store anyway.
11304   if (St.isTruncatingStore())
11305     return SDValue();
11306 
11307   // Check that this is a splat.
11308   // Make sure that each of the relevant vector element locations are inserted
11309   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
11310   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
11311   SDValue SplatVal;
11312   for (unsigned I = 0; I < NumVecElts; ++I) {
11313     // Check for insert vector elements.
11314     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
11315       return SDValue();
11316 
11317     // Check that same value is inserted at each vector element.
11318     if (I == 0)
11319       SplatVal = StVal.getOperand(1);
11320     else if (StVal.getOperand(1) != SplatVal)
11321       return SDValue();
11322 
11323     // Check insert element index.
11324     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
11325     if (!CIndex)
11326       return SDValue();
11327     uint64_t IndexVal = CIndex->getZExtValue();
11328     if (IndexVal >= NumVecElts)
11329       return SDValue();
11330     IndexNotInserted.reset(IndexVal);
11331 
11332     StVal = StVal.getOperand(0);
11333   }
11334   // Check that all vector element locations were inserted to.
11335   if (IndexNotInserted.any())
11336       return SDValue();
11337 
11338   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11339 }
11340 
11341 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11342                            SelectionDAG &DAG,
11343                            const AArch64Subtarget *Subtarget) {
11344 
11345   StoreSDNode *S = cast<StoreSDNode>(N);
11346   if (S->isVolatile() || S->isIndexed())
11347     return SDValue();
11348 
11349   SDValue StVal = S->getValue();
11350   EVT VT = StVal.getValueType();
11351   if (!VT.isVector())
11352     return SDValue();
11353 
11354   // If we get a splat of zeros, convert this vector store to a store of
11355   // scalars. They will be merged into store pairs of xzr thereby removing one
11356   // instruction and one register.
11357   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
11358     return ReplacedZeroSplat;
11359 
11360   // FIXME: The logic for deciding if an unaligned store should be split should
11361   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
11362   // a call to that function here.
11363 
11364   if (!Subtarget->isMisaligned128StoreSlow())
11365     return SDValue();
11366 
11367   // Don't split at -Oz.
11368   if (DAG.getMachineFunction().getFunction().hasMinSize())
11369     return SDValue();
11370 
11371   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
11372   // those up regresses performance on micro-benchmarks and olden/bh.
11373   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
11374     return SDValue();
11375 
11376   // Split unaligned 16B stores. They are terrible for performance.
11377   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
11378   // extensions can use this to mark that it does not want splitting to happen
11379   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
11380   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
11381   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
11382       S->getAlignment() <= 2)
11383     return SDValue();
11384 
11385   // If we get a splat of a scalar convert this vector store to a store of
11386   // scalars. They will be merged into store pairs thereby removing two
11387   // instructions.
11388   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
11389     return ReplacedSplat;
11390 
11391   SDLoc DL(S);
11392 
11393   // Split VT into two.
11394   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11395   unsigned NumElts = HalfVT.getVectorNumElements();
11396   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11397                                    DAG.getConstant(0, DL, MVT::i64));
11398   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11399                                    DAG.getConstant(NumElts, DL, MVT::i64));
11400   SDValue BasePtr = S->getBasePtr();
11401   SDValue NewST1 =
11402       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
11403                    S->getAlignment(), S->getMemOperand()->getFlags());
11404   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11405                                   DAG.getConstant(8, DL, MVT::i64));
11406   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
11407                       S->getPointerInfo(), S->getAlignment(),
11408                       S->getMemOperand()->getFlags());
11409 }
11410 
11411 /// Target-specific DAG combine function for post-increment LD1 (lane) and
11412 /// post-increment LD1R.
11413 static SDValue performPostLD1Combine(SDNode *N,
11414                                      TargetLowering::DAGCombinerInfo &DCI,
11415                                      bool IsLaneOp) {
11416   if (DCI.isBeforeLegalizeOps())
11417     return SDValue();
11418 
11419   SelectionDAG &DAG = DCI.DAG;
11420   EVT VT = N->getValueType(0);
11421 
11422   unsigned LoadIdx = IsLaneOp ? 1 : 0;
11423   SDNode *LD = N->getOperand(LoadIdx).getNode();
11424   // If it is not LOAD, can not do such combine.
11425   if (LD->getOpcode() != ISD::LOAD)
11426     return SDValue();
11427 
11428   // The vector lane must be a constant in the LD1LANE opcode.
11429   SDValue Lane;
11430   if (IsLaneOp) {
11431     Lane = N->getOperand(2);
11432     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
11433     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
11434       return SDValue();
11435   }
11436 
11437   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
11438   EVT MemVT = LoadSDN->getMemoryVT();
11439   // Check if memory operand is the same type as the vector element.
11440   if (MemVT != VT.getVectorElementType())
11441     return SDValue();
11442 
11443   // Check if there are other uses. If so, do not combine as it will introduce
11444   // an extra load.
11445   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
11446        ++UI) {
11447     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
11448       continue;
11449     if (*UI != N)
11450       return SDValue();
11451   }
11452 
11453   SDValue Addr = LD->getOperand(1);
11454   SDValue Vector = N->getOperand(0);
11455   // Search for a use of the address operand that is an increment.
11456   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
11457        Addr.getNode()->use_end(); UI != UE; ++UI) {
11458     SDNode *User = *UI;
11459     if (User->getOpcode() != ISD::ADD
11460         || UI.getUse().getResNo() != Addr.getResNo())
11461       continue;
11462 
11463     // If the increment is a constant, it must match the memory ref size.
11464     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11465     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11466       uint32_t IncVal = CInc->getZExtValue();
11467       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
11468       if (IncVal != NumBytes)
11469         continue;
11470       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11471     }
11472 
11473     // To avoid cycle construction make sure that neither the load nor the add
11474     // are predecessors to each other or the Vector.
11475     SmallPtrSet<const SDNode *, 32> Visited;
11476     SmallVector<const SDNode *, 16> Worklist;
11477     Visited.insert(Addr.getNode());
11478     Worklist.push_back(User);
11479     Worklist.push_back(LD);
11480     Worklist.push_back(Vector.getNode());
11481     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
11482         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11483       continue;
11484 
11485     SmallVector<SDValue, 8> Ops;
11486     Ops.push_back(LD->getOperand(0));  // Chain
11487     if (IsLaneOp) {
11488       Ops.push_back(Vector);           // The vector to be inserted
11489       Ops.push_back(Lane);             // The lane to be inserted in the vector
11490     }
11491     Ops.push_back(Addr);
11492     Ops.push_back(Inc);
11493 
11494     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
11495     SDVTList SDTys = DAG.getVTList(Tys);
11496     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
11497     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
11498                                            MemVT,
11499                                            LoadSDN->getMemOperand());
11500 
11501     // Update the uses.
11502     SDValue NewResults[] = {
11503         SDValue(LD, 0),            // The result of load
11504         SDValue(UpdN.getNode(), 2) // Chain
11505     };
11506     DCI.CombineTo(LD, NewResults);
11507     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
11508     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
11509 
11510     break;
11511   }
11512   return SDValue();
11513 }
11514 
11515 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
11516 /// address translation.
11517 static bool performTBISimplification(SDValue Addr,
11518                                      TargetLowering::DAGCombinerInfo &DCI,
11519                                      SelectionDAG &DAG) {
11520   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
11521   KnownBits Known;
11522   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11523                                         !DCI.isBeforeLegalizeOps());
11524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11525   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
11526     DCI.CommitTargetLoweringOpt(TLO);
11527     return true;
11528   }
11529   return false;
11530 }
11531 
11532 static SDValue performSTORECombine(SDNode *N,
11533                                    TargetLowering::DAGCombinerInfo &DCI,
11534                                    SelectionDAG &DAG,
11535                                    const AArch64Subtarget *Subtarget) {
11536   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11537     return Split;
11538 
11539   if (Subtarget->supportsAddressTopByteIgnored() &&
11540       performTBISimplification(N->getOperand(2), DCI, DAG))
11541     return SDValue(N, 0);
11542 
11543   return SDValue();
11544 }
11545 
11546 
11547 /// Target-specific DAG combine function for NEON load/store intrinsics
11548 /// to merge base address updates.
11549 static SDValue performNEONPostLDSTCombine(SDNode *N,
11550                                           TargetLowering::DAGCombinerInfo &DCI,
11551                                           SelectionDAG &DAG) {
11552   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11553     return SDValue();
11554 
11555   unsigned AddrOpIdx = N->getNumOperands() - 1;
11556   SDValue Addr = N->getOperand(AddrOpIdx);
11557 
11558   // Search for a use of the address operand that is an increment.
11559   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11560        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11561     SDNode *User = *UI;
11562     if (User->getOpcode() != ISD::ADD ||
11563         UI.getUse().getResNo() != Addr.getResNo())
11564       continue;
11565 
11566     // Check that the add is independent of the load/store.  Otherwise, folding
11567     // it would create a cycle.
11568     SmallPtrSet<const SDNode *, 32> Visited;
11569     SmallVector<const SDNode *, 16> Worklist;
11570     Visited.insert(Addr.getNode());
11571     Worklist.push_back(N);
11572     Worklist.push_back(User);
11573     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11574         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11575       continue;
11576 
11577     // Find the new opcode for the updating load/store.
11578     bool IsStore = false;
11579     bool IsLaneOp = false;
11580     bool IsDupOp = false;
11581     unsigned NewOpc = 0;
11582     unsigned NumVecs = 0;
11583     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11584     switch (IntNo) {
11585     default: llvm_unreachable("unexpected intrinsic for Neon base update");
11586     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
11587       NumVecs = 2; break;
11588     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
11589       NumVecs = 3; break;
11590     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
11591       NumVecs = 4; break;
11592     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
11593       NumVecs = 2; IsStore = true; break;
11594     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
11595       NumVecs = 3; IsStore = true; break;
11596     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
11597       NumVecs = 4; IsStore = true; break;
11598     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
11599       NumVecs = 2; break;
11600     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
11601       NumVecs = 3; break;
11602     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
11603       NumVecs = 4; break;
11604     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
11605       NumVecs = 2; IsStore = true; break;
11606     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
11607       NumVecs = 3; IsStore = true; break;
11608     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
11609       NumVecs = 4; IsStore = true; break;
11610     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
11611       NumVecs = 2; IsDupOp = true; break;
11612     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
11613       NumVecs = 3; IsDupOp = true; break;
11614     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
11615       NumVecs = 4; IsDupOp = true; break;
11616     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
11617       NumVecs = 2; IsLaneOp = true; break;
11618     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
11619       NumVecs = 3; IsLaneOp = true; break;
11620     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
11621       NumVecs = 4; IsLaneOp = true; break;
11622     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
11623       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
11624     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
11625       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
11626     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
11627       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
11628     }
11629 
11630     EVT VecTy;
11631     if (IsStore)
11632       VecTy = N->getOperand(2).getValueType();
11633     else
11634       VecTy = N->getValueType(0);
11635 
11636     // If the increment is a constant, it must match the memory ref size.
11637     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11638     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11639       uint32_t IncVal = CInc->getZExtValue();
11640       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11641       if (IsLaneOp || IsDupOp)
11642         NumBytes /= VecTy.getVectorNumElements();
11643       if (IncVal != NumBytes)
11644         continue;
11645       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11646     }
11647     SmallVector<SDValue, 8> Ops;
11648     Ops.push_back(N->getOperand(0)); // Incoming chain
11649     // Load lane and store have vector list as input.
11650     if (IsLaneOp || IsStore)
11651       for (unsigned i = 2; i < AddrOpIdx; ++i)
11652         Ops.push_back(N->getOperand(i));
11653     Ops.push_back(Addr); // Base register
11654     Ops.push_back(Inc);
11655 
11656     // Return Types.
11657     EVT Tys[6];
11658     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11659     unsigned n;
11660     for (n = 0; n < NumResultVecs; ++n)
11661       Tys[n] = VecTy;
11662     Tys[n++] = MVT::i64;  // Type of write back register
11663     Tys[n] = MVT::Other;  // Type of the chain
11664     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
11665 
11666     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11667     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11668                                            MemInt->getMemoryVT(),
11669                                            MemInt->getMemOperand());
11670 
11671     // Update the uses.
11672     std::vector<SDValue> NewResults;
11673     for (unsigned i = 0; i < NumResultVecs; ++i) {
11674       NewResults.push_back(SDValue(UpdN.getNode(), i));
11675     }
11676     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11677     DCI.CombineTo(N, NewResults);
11678     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11679 
11680     break;
11681   }
11682   return SDValue();
11683 }
11684 
11685 // Checks to see if the value is the prescribed width and returns information
11686 // about its extension mode.
11687 static
11688 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11689   ExtType = ISD::NON_EXTLOAD;
11690   switch(V.getNode()->getOpcode()) {
11691   default:
11692     return false;
11693   case ISD::LOAD: {
11694     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11695     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11696        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11697       ExtType = LoadNode->getExtensionType();
11698       return true;
11699     }
11700     return false;
11701   }
11702   case ISD::AssertSext: {
11703     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11704     if ((TypeNode->getVT() == MVT::i8 && width == 8)
11705        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11706       ExtType = ISD::SEXTLOAD;
11707       return true;
11708     }
11709     return false;
11710   }
11711   case ISD::AssertZext: {
11712     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11713     if ((TypeNode->getVT() == MVT::i8 && width == 8)
11714        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11715       ExtType = ISD::ZEXTLOAD;
11716       return true;
11717     }
11718     return false;
11719   }
11720   case ISD::Constant:
11721   case ISD::TargetConstant: {
11722     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11723            1LL << (width - 1);
11724   }
11725   }
11726 
11727   return true;
11728 }
11729 
11730 // This function does a whole lot of voodoo to determine if the tests are
11731 // equivalent without and with a mask. Essentially what happens is that given a
11732 // DAG resembling:
11733 //
11734 //  +-------------+ +-------------+ +-------------+ +-------------+
11735 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
11736 //  +-------------+ +-------------+ +-------------+ +-------------+
11737 //           |           |           |               |
11738 //           V           V           |    +----------+
11739 //          +-------------+  +----+  |    |
11740 //          |     ADD     |  |0xff|  |    |
11741 //          +-------------+  +----+  |    |
11742 //                  |           |    |    |
11743 //                  V           V    |    |
11744 //                 +-------------+   |    |
11745 //                 |     AND     |   |    |
11746 //                 +-------------+   |    |
11747 //                      |            |    |
11748 //                      +-----+      |    |
11749 //                            |      |    |
11750 //                            V      V    V
11751 //                           +-------------+
11752 //                           |     CMP     |
11753 //                           +-------------+
11754 //
11755 // The AND node may be safely removed for some combinations of inputs. In
11756 // particular we need to take into account the extension type of the Input,
11757 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
11758 // width of the input (this can work for any width inputs, the above graph is
11759 // specific to 8 bits.
11760 //
11761 // The specific equations were worked out by generating output tables for each
11762 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11763 // problem was simplified by working with 4 bit inputs, which means we only
11764 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11765 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11766 // patterns present in both extensions (0,7). For every distinct set of
11767 // AddConstant and CompConstants bit patterns we can consider the masked and
11768 // unmasked versions to be equivalent if the result of this function is true for
11769 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11770 //
11771 //   sub      w8, w0, w1
11772 //   and      w10, w8, #0x0f
11773 //   cmp      w8, w2
11774 //   cset     w9, AArch64CC
11775 //   cmp      w10, w2
11776 //   cset     w11, AArch64CC
11777 //   cmp      w9, w11
11778 //   cset     w0, eq
11779 //   ret
11780 //
11781 // Since the above function shows when the outputs are equivalent it defines
11782 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11783 // would be expensive to run during compiles. The equations below were written
11784 // in a test harness that confirmed they gave equivalent outputs to the above
11785 // for all inputs function, so they can be used determine if the removal is
11786 // legal instead.
11787 //
11788 // isEquivalentMaskless() is the code for testing if the AND can be removed
11789 // factored out of the DAG recognition as the DAG can take several forms.
11790 
11791 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11792                                  ISD::LoadExtType ExtType, int AddConstant,
11793                                  int CompConstant) {
11794   // By being careful about our equations and only writing the in term
11795   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11796   // make them generally applicable to all bit widths.
11797   int MaxUInt = (1 << width);
11798 
11799   // For the purposes of these comparisons sign extending the type is
11800   // equivalent to zero extending the add and displacing it by half the integer
11801   // width. Provided we are careful and make sure our equations are valid over
11802   // the whole range we can just adjust the input and avoid writing equations
11803   // for sign extended inputs.
11804   if (ExtType == ISD::SEXTLOAD)
11805     AddConstant -= (1 << (width-1));
11806 
11807   switch(CC) {
11808   case AArch64CC::LE:
11809   case AArch64CC::GT:
11810     if ((AddConstant == 0) ||
11811         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11812         (AddConstant >= 0 && CompConstant < 0) ||
11813         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11814       return true;
11815     break;
11816   case AArch64CC::LT:
11817   case AArch64CC::GE:
11818     if ((AddConstant == 0) ||
11819         (AddConstant >= 0 && CompConstant <= 0) ||
11820         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11821       return true;
11822     break;
11823   case AArch64CC::HI:
11824   case AArch64CC::LS:
11825     if ((AddConstant >= 0 && CompConstant < 0) ||
11826        (AddConstant <= 0 && CompConstant >= -1 &&
11827         CompConstant < AddConstant + MaxUInt))
11828       return true;
11829    break;
11830   case AArch64CC::PL:
11831   case AArch64CC::MI:
11832     if ((AddConstant == 0) ||
11833         (AddConstant > 0 && CompConstant <= 0) ||
11834         (AddConstant < 0 && CompConstant <= AddConstant))
11835       return true;
11836     break;
11837   case AArch64CC::LO:
11838   case AArch64CC::HS:
11839     if ((AddConstant >= 0 && CompConstant <= 0) ||
11840         (AddConstant <= 0 && CompConstant >= 0 &&
11841          CompConstant <= AddConstant + MaxUInt))
11842       return true;
11843     break;
11844   case AArch64CC::EQ:
11845   case AArch64CC::NE:
11846     if ((AddConstant > 0 && CompConstant < 0) ||
11847         (AddConstant < 0 && CompConstant >= 0 &&
11848          CompConstant < AddConstant + MaxUInt) ||
11849         (AddConstant >= 0 && CompConstant >= 0 &&
11850          CompConstant >= AddConstant) ||
11851         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11852       return true;
11853     break;
11854   case AArch64CC::VS:
11855   case AArch64CC::VC:
11856   case AArch64CC::AL:
11857   case AArch64CC::NV:
11858     return true;
11859   case AArch64CC::Invalid:
11860     break;
11861   }
11862 
11863   return false;
11864 }
11865 
11866 static
11867 SDValue performCONDCombine(SDNode *N,
11868                            TargetLowering::DAGCombinerInfo &DCI,
11869                            SelectionDAG &DAG, unsigned CCIndex,
11870                            unsigned CmpIndex) {
11871   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11872   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11873   unsigned CondOpcode = SubsNode->getOpcode();
11874 
11875   if (CondOpcode != AArch64ISD::SUBS)
11876     return SDValue();
11877 
11878   // There is a SUBS feeding this condition. Is it fed by a mask we can
11879   // use?
11880 
11881   SDNode *AndNode = SubsNode->getOperand(0).getNode();
11882   unsigned MaskBits = 0;
11883 
11884   if (AndNode->getOpcode() != ISD::AND)
11885     return SDValue();
11886 
11887   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11888     uint32_t CNV = CN->getZExtValue();
11889     if (CNV == 255)
11890       MaskBits = 8;
11891     else if (CNV == 65535)
11892       MaskBits = 16;
11893   }
11894 
11895   if (!MaskBits)
11896     return SDValue();
11897 
11898   SDValue AddValue = AndNode->getOperand(0);
11899 
11900   if (AddValue.getOpcode() != ISD::ADD)
11901     return SDValue();
11902 
11903   // The basic dag structure is correct, grab the inputs and validate them.
11904 
11905   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11906   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11907   SDValue SubsInputValue = SubsNode->getOperand(1);
11908 
11909   // The mask is present and the provenance of all the values is a smaller type,
11910   // lets see if the mask is superfluous.
11911 
11912   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11913       !isa<ConstantSDNode>(SubsInputValue.getNode()))
11914     return SDValue();
11915 
11916   ISD::LoadExtType ExtType;
11917 
11918   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11919       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11920       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11921     return SDValue();
11922 
11923   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11924                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11925                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11926     return SDValue();
11927 
11928   // The AND is not necessary, remove it.
11929 
11930   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11931                                SubsNode->getValueType(1));
11932   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11933 
11934   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11935   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11936 
11937   return SDValue(N, 0);
11938 }
11939 
11940 // Optimize compare with zero and branch.
11941 static SDValue performBRCONDCombine(SDNode *N,
11942                                     TargetLowering::DAGCombinerInfo &DCI,
11943                                     SelectionDAG &DAG) {
11944   MachineFunction &MF = DAG.getMachineFunction();
11945   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11946   // will not be produced, as they are conditional branch instructions that do
11947   // not set flags.
11948   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11949     return SDValue();
11950 
11951   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11952     N = NV.getNode();
11953   SDValue Chain = N->getOperand(0);
11954   SDValue Dest = N->getOperand(1);
11955   SDValue CCVal = N->getOperand(2);
11956   SDValue Cmp = N->getOperand(3);
11957 
11958   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11959   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11960   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11961     return SDValue();
11962 
11963   unsigned CmpOpc = Cmp.getOpcode();
11964   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11965     return SDValue();
11966 
11967   // Only attempt folding if there is only one use of the flag and no use of the
11968   // value.
11969   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11970     return SDValue();
11971 
11972   SDValue LHS = Cmp.getOperand(0);
11973   SDValue RHS = Cmp.getOperand(1);
11974 
11975   assert(LHS.getValueType() == RHS.getValueType() &&
11976          "Expected the value type to be the same for both operands!");
11977   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11978     return SDValue();
11979 
11980   if (isNullConstant(LHS))
11981     std::swap(LHS, RHS);
11982 
11983   if (!isNullConstant(RHS))
11984     return SDValue();
11985 
11986   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11987       LHS.getOpcode() == ISD::SRL)
11988     return SDValue();
11989 
11990   // Fold the compare into the branch instruction.
11991   SDValue BR;
11992   if (CC == AArch64CC::EQ)
11993     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11994   else
11995     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11996 
11997   // Do not add new nodes to DAG combiner worklist.
11998   DCI.CombineTo(N, BR, false);
11999 
12000   return SDValue();
12001 }
12002 
12003 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
12004 // as well as whether the test should be inverted.  This code is required to
12005 // catch these cases (as opposed to standard dag combines) because
12006 // AArch64ISD::TBZ is matched during legalization.
12007 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
12008                                  SelectionDAG &DAG) {
12009 
12010   if (!Op->hasOneUse())
12011     return Op;
12012 
12013   // We don't handle undef/constant-fold cases below, as they should have
12014   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
12015   // etc.)
12016 
12017   // (tbz (trunc x), b) -> (tbz x, b)
12018   // This case is just here to enable more of the below cases to be caught.
12019   if (Op->getOpcode() == ISD::TRUNCATE &&
12020       Bit < Op->getValueType(0).getSizeInBits()) {
12021     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12022   }
12023 
12024   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
12025   if (Op->getOpcode() == ISD::ANY_EXTEND &&
12026       Bit < Op->getOperand(0).getValueSizeInBits()) {
12027     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12028   }
12029 
12030   if (Op->getNumOperands() != 2)
12031     return Op;
12032 
12033   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12034   if (!C)
12035     return Op;
12036 
12037   switch (Op->getOpcode()) {
12038   default:
12039     return Op;
12040 
12041   // (tbz (and x, m), b) -> (tbz x, b)
12042   case ISD::AND:
12043     if ((C->getZExtValue() >> Bit) & 1)
12044       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12045     return Op;
12046 
12047   // (tbz (shl x, c), b) -> (tbz x, b-c)
12048   case ISD::SHL:
12049     if (C->getZExtValue() <= Bit &&
12050         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12051       Bit = Bit - C->getZExtValue();
12052       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12053     }
12054     return Op;
12055 
12056   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
12057   case ISD::SRA:
12058     Bit = Bit + C->getZExtValue();
12059     if (Bit >= Op->getValueType(0).getSizeInBits())
12060       Bit = Op->getValueType(0).getSizeInBits() - 1;
12061     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12062 
12063   // (tbz (srl x, c), b) -> (tbz x, b+c)
12064   case ISD::SRL:
12065     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12066       Bit = Bit + C->getZExtValue();
12067       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12068     }
12069     return Op;
12070 
12071   // (tbz (xor x, -1), b) -> (tbnz x, b)
12072   case ISD::XOR:
12073     if ((C->getZExtValue() >> Bit) & 1)
12074       Invert = !Invert;
12075     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12076   }
12077 }
12078 
12079 // Optimize test single bit zero/non-zero and branch.
12080 static SDValue performTBZCombine(SDNode *N,
12081                                  TargetLowering::DAGCombinerInfo &DCI,
12082                                  SelectionDAG &DAG) {
12083   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12084   bool Invert = false;
12085   SDValue TestSrc = N->getOperand(1);
12086   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
12087 
12088   if (TestSrc == NewTestSrc)
12089     return SDValue();
12090 
12091   unsigned NewOpc = N->getOpcode();
12092   if (Invert) {
12093     if (NewOpc == AArch64ISD::TBZ)
12094       NewOpc = AArch64ISD::TBNZ;
12095     else {
12096       assert(NewOpc == AArch64ISD::TBNZ);
12097       NewOpc = AArch64ISD::TBZ;
12098     }
12099   }
12100 
12101   SDLoc DL(N);
12102   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
12103                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
12104 }
12105 
12106 // vselect (v1i1 setcc) ->
12107 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
12108 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
12109 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
12110 // such VSELECT.
12111 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
12112   SDValue N0 = N->getOperand(0);
12113   EVT CCVT = N0.getValueType();
12114 
12115   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
12116       CCVT.getVectorElementType() != MVT::i1)
12117     return SDValue();
12118 
12119   EVT ResVT = N->getValueType(0);
12120   EVT CmpVT = N0.getOperand(0).getValueType();
12121   // Only combine when the result type is of the same size as the compared
12122   // operands.
12123   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
12124     return SDValue();
12125 
12126   SDValue IfTrue = N->getOperand(1);
12127   SDValue IfFalse = N->getOperand(2);
12128   SDValue SetCC =
12129       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
12130                    N0.getOperand(0), N0.getOperand(1),
12131                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
12132   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
12133                      IfTrue, IfFalse);
12134 }
12135 
12136 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
12137 /// the compare-mask instructions rather than going via NZCV, even if LHS and
12138 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
12139 /// with a vector one followed by a DUP shuffle on the result.
12140 static SDValue performSelectCombine(SDNode *N,
12141                                     TargetLowering::DAGCombinerInfo &DCI) {
12142   SelectionDAG &DAG = DCI.DAG;
12143   SDValue N0 = N->getOperand(0);
12144   EVT ResVT = N->getValueType(0);
12145 
12146   if (N0.getOpcode() != ISD::SETCC)
12147     return SDValue();
12148 
12149   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
12150   // scalar SetCCResultType. We also don't expect vectors, because we assume
12151   // that selects fed by vector SETCCs are canonicalized to VSELECT.
12152   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
12153          "Scalar-SETCC feeding SELECT has unexpected result type!");
12154 
12155   // If NumMaskElts == 0, the comparison is larger than select result. The
12156   // largest real NEON comparison is 64-bits per lane, which means the result is
12157   // at most 32-bits and an illegal vector. Just bail out for now.
12158   EVT SrcVT = N0.getOperand(0).getValueType();
12159 
12160   // Don't try to do this optimization when the setcc itself has i1 operands.
12161   // There are no legal vectors of i1, so this would be pointless.
12162   if (SrcVT == MVT::i1)
12163     return SDValue();
12164 
12165   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
12166   if (!ResVT.isVector() || NumMaskElts == 0)
12167     return SDValue();
12168 
12169   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
12170   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
12171 
12172   // Also bail out if the vector CCVT isn't the same size as ResVT.
12173   // This can happen if the SETCC operand size doesn't divide the ResVT size
12174   // (e.g., f64 vs v3f32).
12175   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
12176     return SDValue();
12177 
12178   // Make sure we didn't create illegal types, if we're not supposed to.
12179   assert(DCI.isBeforeLegalize() ||
12180          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
12181 
12182   // First perform a vector comparison, where lane 0 is the one we're interested
12183   // in.
12184   SDLoc DL(N0);
12185   SDValue LHS =
12186       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
12187   SDValue RHS =
12188       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
12189   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
12190 
12191   // Now duplicate the comparison mask we want across all other lanes.
12192   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
12193   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
12194   Mask = DAG.getNode(ISD::BITCAST, DL,
12195                      ResVT.changeVectorElementTypeToInteger(), Mask);
12196 
12197   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
12198 }
12199 
12200 /// Get rid of unnecessary NVCASTs (that don't change the type).
12201 static SDValue performNVCASTCombine(SDNode *N) {
12202   if (N->getValueType(0) == N->getOperand(0).getValueType())
12203     return N->getOperand(0);
12204 
12205   return SDValue();
12206 }
12207 
12208 // If all users of the globaladdr are of the form (globaladdr + constant), find
12209 // the smallest constant, fold it into the globaladdr's offset and rewrite the
12210 // globaladdr as (globaladdr + constant) - constant.
12211 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
12212                                            const AArch64Subtarget *Subtarget,
12213                                            const TargetMachine &TM) {
12214   auto *GN = cast<GlobalAddressSDNode>(N);
12215   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
12216       AArch64II::MO_NO_FLAG)
12217     return SDValue();
12218 
12219   uint64_t MinOffset = -1ull;
12220   for (SDNode *N : GN->uses()) {
12221     if (N->getOpcode() != ISD::ADD)
12222       return SDValue();
12223     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
12224     if (!C)
12225       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12226     if (!C)
12227       return SDValue();
12228     MinOffset = std::min(MinOffset, C->getZExtValue());
12229   }
12230   uint64_t Offset = MinOffset + GN->getOffset();
12231 
12232   // Require that the new offset is larger than the existing one. Otherwise, we
12233   // can end up oscillating between two possible DAGs, for example,
12234   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
12235   if (Offset <= uint64_t(GN->getOffset()))
12236     return SDValue();
12237 
12238   // Check whether folding this offset is legal. It must not go out of bounds of
12239   // the referenced object to avoid violating the code model, and must be
12240   // smaller than 2^21 because this is the largest offset expressible in all
12241   // object formats.
12242   //
12243   // This check also prevents us from folding negative offsets, which will end
12244   // up being treated in the same way as large positive ones. They could also
12245   // cause code model violations, and aren't really common enough to matter.
12246   if (Offset >= (1 << 21))
12247     return SDValue();
12248 
12249   const GlobalValue *GV = GN->getGlobal();
12250   Type *T = GV->getValueType();
12251   if (!T->isSized() ||
12252       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
12253     return SDValue();
12254 
12255   SDLoc DL(GN);
12256   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
12257   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
12258                      DAG.getConstant(MinOffset, DL, MVT::i64));
12259 }
12260 
12261 // Returns an SVE type that ContentTy can be trivially sign or zero extended
12262 // into.
12263 static MVT getSVEContainerType(EVT ContentTy) {
12264   assert(ContentTy.isSimple() && "No SVE containers for extended types");
12265 
12266   switch (ContentTy.getSimpleVT().SimpleTy) {
12267   default:
12268     llvm_unreachable("No known SVE container for this MVT type");
12269   case MVT::nxv2i8:
12270   case MVT::nxv2i16:
12271   case MVT::nxv2i32:
12272   case MVT::nxv2i64:
12273   case MVT::nxv2f32:
12274   case MVT::nxv2f64:
12275     return MVT::nxv2i64;
12276   case MVT::nxv4i8:
12277   case MVT::nxv4i16:
12278   case MVT::nxv4i32:
12279   case MVT::nxv4f32:
12280     return MVT::nxv4i32;
12281   }
12282 }
12283 
12284 static SDValue performST1ScatterCombine(SDNode *N, SelectionDAG &DAG,
12285                                         unsigned Opcode,
12286                                         bool OnlyPackedOffsets = true) {
12287   const SDValue Src = N->getOperand(2);
12288   const EVT SrcVT = Src->getValueType(0);
12289   assert(SrcVT.isScalableVector() &&
12290          "Scatter stores are only possible for SVE vectors");
12291 
12292   SDLoc DL(N);
12293   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
12294 
12295   // Make sure that source data will fit into an SVE register
12296   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12297     return SDValue();
12298 
12299   // For FPs, ACLE only supports _packed_ single and double precision types.
12300   if (SrcElVT.isFloatingPoint())
12301     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
12302       return SDValue();
12303 
12304   // Depending on the addressing mode, this is either a pointer or a vector of
12305   // pointers (that fits into one register)
12306   const SDValue Base = N->getOperand(4);
12307   // Depending on the addressing mode, this is either a single offset or a
12308   // vector of offsets  (that fits into one register)
12309   SDValue Offset = N->getOperand(5);
12310 
12311   auto &TLI = DAG.getTargetLoweringInfo();
12312   if (!TLI.isTypeLegal(Base.getValueType()))
12313     return SDValue();
12314 
12315   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
12316   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12317   // nxv2i64. Legalize accordingly.
12318   if (!OnlyPackedOffsets &&
12319       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12320     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12321 
12322   if (!TLI.isTypeLegal(Offset.getValueType()))
12323     return SDValue();
12324 
12325   // Source value type that is representable in hardware
12326   EVT HwSrcVt = getSVEContainerType(SrcVT);
12327 
12328   // Keep the original type of the input data to store - this is needed to
12329   // differentiate between ST1B, ST1H, ST1W and ST1D. For FP values we want the
12330   // integer equivalent, so just use HwSrcVt.
12331   SDValue InputVT = DAG.getValueType(SrcVT);
12332   if (SrcVT.isFloatingPoint())
12333     InputVT = DAG.getValueType(HwSrcVt);
12334 
12335   SDVTList VTs = DAG.getVTList(MVT::Other);
12336   SDValue SrcNew;
12337 
12338   if (Src.getValueType().isFloatingPoint())
12339     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
12340   else
12341     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
12342 
12343   SDValue Ops[] = {N->getOperand(0), // Chain
12344                    SrcNew,
12345                    N->getOperand(3), // Pg
12346                    Base,
12347                    Offset,
12348                    InputVT};
12349 
12350   return DAG.getNode(Opcode, DL, VTs, Ops);
12351 }
12352 
12353 static SDValue performLD1GatherCombine(SDNode *N, SelectionDAG &DAG,
12354                                        unsigned Opcode,
12355                                        bool OnlyPackedOffsets = true) {
12356   EVT RetVT = N->getValueType(0);
12357   assert(RetVT.isScalableVector() &&
12358          "Gather loads are only possible for SVE vectors");
12359   SDLoc DL(N);
12360 
12361   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12362     return SDValue();
12363 
12364   // Depending on the addressing mode, this is either a pointer or a vector of
12365   // pointers (that fits into one register)
12366   const SDValue Base = N->getOperand(3);
12367   // Depending on the addressing mode, this is either a single offset or a
12368   // vector of offsets  (that fits into one register)
12369   SDValue Offset = N->getOperand(4);
12370 
12371   auto &TLI = DAG.getTargetLoweringInfo();
12372   if (!TLI.isTypeLegal(Base.getValueType()))
12373     return SDValue();
12374 
12375   // Some gather load variants allow unpacked offsets, but only as nxv2i32
12376   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12377   // nxv2i64. Legalize accordingly.
12378   if (!OnlyPackedOffsets &&
12379       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12380     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12381 
12382   // Return value type that is representable in hardware
12383   EVT HwRetVt = getSVEContainerType(RetVT);
12384 
12385   // Keep the original output value type around - this will better inform
12386   // optimisations (e.g. instruction folding when load is followed by
12387   // zext/sext). This will only be used for ints, so the value for FPs
12388   // doesn't matter.
12389   SDValue OutVT = DAG.getValueType(RetVT);
12390   if (RetVT.isFloatingPoint())
12391     OutVT = DAG.getValueType(HwRetVt);
12392 
12393   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
12394   SDValue Ops[] = {N->getOperand(0), // Chain
12395                    N->getOperand(2), // Pg
12396                    Base, Offset, OutVT};
12397 
12398   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
12399   SDValue LoadChain = SDValue(Load.getNode(), 1);
12400 
12401   if (RetVT.isInteger() && (RetVT != HwRetVt))
12402     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
12403 
12404   // If the original return value was FP, bitcast accordingly. Doing it here
12405   // means that we can avoid adding TableGen patterns for FPs.
12406   if (RetVT.isFloatingPoint())
12407     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
12408 
12409   return DAG.getMergeValues({Load, LoadChain}, DL);
12410 }
12411 
12412 
12413 static SDValue
12414 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12415                               SelectionDAG &DAG) {
12416   if (DCI.isBeforeLegalizeOps())
12417     return SDValue();
12418 
12419   SDValue Src = N->getOperand(0);
12420   unsigned Opc = Src->getOpcode();
12421 
12422   // Gather load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
12423   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
12424   unsigned NewOpc;
12425   switch (Opc) {
12426   case AArch64ISD::GLD1:
12427     NewOpc = AArch64ISD::GLD1S;
12428     break;
12429   case AArch64ISD::GLD1_SCALED:
12430     NewOpc = AArch64ISD::GLD1S_SCALED;
12431     break;
12432   case AArch64ISD::GLD1_SXTW:
12433     NewOpc = AArch64ISD::GLD1S_SXTW;
12434     break;
12435   case AArch64ISD::GLD1_SXTW_SCALED:
12436     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED;
12437     break;
12438   case AArch64ISD::GLD1_UXTW:
12439     NewOpc = AArch64ISD::GLD1S_UXTW;
12440     break;
12441   case AArch64ISD::GLD1_UXTW_SCALED:
12442     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED;
12443     break;
12444   case AArch64ISD::GLD1_IMM:
12445     NewOpc = AArch64ISD::GLD1S_IMM;
12446     break;
12447   default:
12448     return SDValue();
12449   }
12450 
12451   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12452   EVT GLD1SrcMemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
12453 
12454   if ((SignExtSrcVT != GLD1SrcMemVT) || !Src.hasOneUse())
12455     return SDValue();
12456 
12457   EVT DstVT = N->getValueType(0);
12458   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
12459   SDValue Ops[] = {Src->getOperand(0), Src->getOperand(1), Src->getOperand(2),
12460                    Src->getOperand(3), Src->getOperand(4)};
12461 
12462   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
12463   DCI.CombineTo(N, ExtLoad);
12464   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
12465 
12466   // Return N so it doesn't get rechecked
12467   return SDValue(N, 0);
12468 }
12469 
12470 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
12471                                                  DAGCombinerInfo &DCI) const {
12472   SelectionDAG &DAG = DCI.DAG;
12473   switch (N->getOpcode()) {
12474   default:
12475     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
12476     break;
12477   case ISD::ADD:
12478   case ISD::SUB:
12479     return performAddSubLongCombine(N, DCI, DAG);
12480   case ISD::XOR:
12481     return performXorCombine(N, DAG, DCI, Subtarget);
12482   case ISD::MUL:
12483     return performMulCombine(N, DAG, DCI, Subtarget);
12484   case ISD::SINT_TO_FP:
12485   case ISD::UINT_TO_FP:
12486     return performIntToFpCombine(N, DAG, Subtarget);
12487   case ISD::FP_TO_SINT:
12488   case ISD::FP_TO_UINT:
12489     return performFpToIntCombine(N, DAG, DCI, Subtarget);
12490   case ISD::FDIV:
12491     return performFDivCombine(N, DAG, DCI, Subtarget);
12492   case ISD::OR:
12493     return performORCombine(N, DCI, Subtarget);
12494   case ISD::AND:
12495     return performANDCombine(N, DCI);
12496   case ISD::SRL:
12497     return performSRLCombine(N, DCI);
12498   case ISD::INTRINSIC_WO_CHAIN:
12499     return performIntrinsicCombine(N, DCI, Subtarget);
12500   case ISD::ANY_EXTEND:
12501   case ISD::ZERO_EXTEND:
12502   case ISD::SIGN_EXTEND:
12503     return performExtendCombine(N, DCI, DAG);
12504   case ISD::SIGN_EXTEND_INREG:
12505     return performSignExtendInRegCombine(N, DCI, DAG);
12506   case ISD::CONCAT_VECTORS:
12507     return performConcatVectorsCombine(N, DCI, DAG);
12508   case ISD::SELECT:
12509     return performSelectCombine(N, DCI);
12510   case ISD::VSELECT:
12511     return performVSelectCombine(N, DCI.DAG);
12512   case ISD::LOAD:
12513     if (performTBISimplification(N->getOperand(1), DCI, DAG))
12514       return SDValue(N, 0);
12515     break;
12516   case ISD::STORE:
12517     return performSTORECombine(N, DCI, DAG, Subtarget);
12518   case AArch64ISD::BRCOND:
12519     return performBRCONDCombine(N, DCI, DAG);
12520   case AArch64ISD::TBNZ:
12521   case AArch64ISD::TBZ:
12522     return performTBZCombine(N, DCI, DAG);
12523   case AArch64ISD::CSEL:
12524     return performCONDCombine(N, DCI, DAG, 2, 3);
12525   case AArch64ISD::DUP:
12526     return performPostLD1Combine(N, DCI, false);
12527   case AArch64ISD::NVCAST:
12528     return performNVCASTCombine(N);
12529   case ISD::INSERT_VECTOR_ELT:
12530     return performPostLD1Combine(N, DCI, true);
12531   case ISD::INTRINSIC_VOID:
12532   case ISD::INTRINSIC_W_CHAIN:
12533     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12534     case Intrinsic::aarch64_neon_ld2:
12535     case Intrinsic::aarch64_neon_ld3:
12536     case Intrinsic::aarch64_neon_ld4:
12537     case Intrinsic::aarch64_neon_ld1x2:
12538     case Intrinsic::aarch64_neon_ld1x3:
12539     case Intrinsic::aarch64_neon_ld1x4:
12540     case Intrinsic::aarch64_neon_ld2lane:
12541     case Intrinsic::aarch64_neon_ld3lane:
12542     case Intrinsic::aarch64_neon_ld4lane:
12543     case Intrinsic::aarch64_neon_ld2r:
12544     case Intrinsic::aarch64_neon_ld3r:
12545     case Intrinsic::aarch64_neon_ld4r:
12546     case Intrinsic::aarch64_neon_st2:
12547     case Intrinsic::aarch64_neon_st3:
12548     case Intrinsic::aarch64_neon_st4:
12549     case Intrinsic::aarch64_neon_st1x2:
12550     case Intrinsic::aarch64_neon_st1x3:
12551     case Intrinsic::aarch64_neon_st1x4:
12552     case Intrinsic::aarch64_neon_st2lane:
12553     case Intrinsic::aarch64_neon_st3lane:
12554     case Intrinsic::aarch64_neon_st4lane:
12555       return performNEONPostLDSTCombine(N, DCI, DAG);
12556     case Intrinsic::aarch64_sve_ldnt1:
12557       return performLDNT1Combine(N, DAG);
12558     case Intrinsic::aarch64_sve_stnt1:
12559       return performSTNT1Combine(N, DAG);
12560     case Intrinsic::aarch64_sve_ld1_gather:
12561       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1);
12562     case Intrinsic::aarch64_sve_ld1_gather_index:
12563       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SCALED);
12564     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
12565       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW,
12566                                       /*OnlyPackedOffsets=*/false);
12567     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
12568       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW,
12569                                       /*OnlyPackedOffsets=*/false);
12570     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
12571       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED,
12572                                       /*OnlyPackedOffsets=*/false);
12573     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
12574       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED,
12575                                       /*OnlyPackedOffsets=*/false);
12576     case Intrinsic::aarch64_sve_ld1_gather_imm:
12577       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_IMM);
12578     case Intrinsic::aarch64_sve_st1_scatter:
12579       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1);
12580     case Intrinsic::aarch64_sve_st1_scatter_index:
12581       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SCALED);
12582     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
12583       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW,
12584                                       /*OnlyPackedOffsets=*/false);
12585     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
12586       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW,
12587                                       /*OnlyPackedOffsets=*/false);
12588     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
12589       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED,
12590                                       /*OnlyPackedOffsets=*/false);
12591     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
12592       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED,
12593                                       /*OnlyPackedOffsets=*/false);
12594     case Intrinsic::aarch64_sve_st1_scatter_imm:
12595       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_IMM);
12596     default:
12597       break;
12598     }
12599     break;
12600   case ISD::GlobalAddress:
12601     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
12602   }
12603   return SDValue();
12604 }
12605 
12606 // Check if the return value is used as only a return value, as otherwise
12607 // we can't perform a tail-call. In particular, we need to check for
12608 // target ISD nodes that are returns and any other "odd" constructs
12609 // that the generic analysis code won't necessarily catch.
12610 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
12611                                                SDValue &Chain) const {
12612   if (N->getNumValues() != 1)
12613     return false;
12614   if (!N->hasNUsesOfValue(1, 0))
12615     return false;
12616 
12617   SDValue TCChain = Chain;
12618   SDNode *Copy = *N->use_begin();
12619   if (Copy->getOpcode() == ISD::CopyToReg) {
12620     // If the copy has a glue operand, we conservatively assume it isn't safe to
12621     // perform a tail call.
12622     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
12623         MVT::Glue)
12624       return false;
12625     TCChain = Copy->getOperand(0);
12626   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
12627     return false;
12628 
12629   bool HasRet = false;
12630   for (SDNode *Node : Copy->uses()) {
12631     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
12632       return false;
12633     HasRet = true;
12634   }
12635 
12636   if (!HasRet)
12637     return false;
12638 
12639   Chain = TCChain;
12640   return true;
12641 }
12642 
12643 // Return whether the an instruction can potentially be optimized to a tail
12644 // call. This will cause the optimizers to attempt to move, or duplicate,
12645 // return instructions to help enable tail call optimizations for this
12646 // instruction.
12647 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
12648   return CI->isTailCall();
12649 }
12650 
12651 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
12652                                                    SDValue &Offset,
12653                                                    ISD::MemIndexedMode &AM,
12654                                                    bool &IsInc,
12655                                                    SelectionDAG &DAG) const {
12656   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
12657     return false;
12658 
12659   Base = Op->getOperand(0);
12660   // All of the indexed addressing mode instructions take a signed
12661   // 9 bit immediate offset.
12662   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
12663     int64_t RHSC = RHS->getSExtValue();
12664     if (Op->getOpcode() == ISD::SUB)
12665       RHSC = -(uint64_t)RHSC;
12666     if (!isInt<9>(RHSC))
12667       return false;
12668     IsInc = (Op->getOpcode() == ISD::ADD);
12669     Offset = Op->getOperand(1);
12670     return true;
12671   }
12672   return false;
12673 }
12674 
12675 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12676                                                       SDValue &Offset,
12677                                                       ISD::MemIndexedMode &AM,
12678                                                       SelectionDAG &DAG) const {
12679   EVT VT;
12680   SDValue Ptr;
12681   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12682     VT = LD->getMemoryVT();
12683     Ptr = LD->getBasePtr();
12684   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12685     VT = ST->getMemoryVT();
12686     Ptr = ST->getBasePtr();
12687   } else
12688     return false;
12689 
12690   bool IsInc;
12691   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
12692     return false;
12693   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
12694   return true;
12695 }
12696 
12697 bool AArch64TargetLowering::getPostIndexedAddressParts(
12698     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
12699     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
12700   EVT VT;
12701   SDValue Ptr;
12702   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12703     VT = LD->getMemoryVT();
12704     Ptr = LD->getBasePtr();
12705   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12706     VT = ST->getMemoryVT();
12707     Ptr = ST->getBasePtr();
12708   } else
12709     return false;
12710 
12711   bool IsInc;
12712   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
12713     return false;
12714   // Post-indexing updates the base, so it's not a valid transform
12715   // if that's not the same as the load's pointer.
12716   if (Ptr != Base)
12717     return false;
12718   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
12719   return true;
12720 }
12721 
12722 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
12723                                   SelectionDAG &DAG) {
12724   SDLoc DL(N);
12725   SDValue Op = N->getOperand(0);
12726 
12727   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
12728     return;
12729 
12730   Op = SDValue(
12731       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
12732                          DAG.getUNDEF(MVT::i32), Op,
12733                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
12734       0);
12735   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
12736   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
12737 }
12738 
12739 static void ReplaceReductionResults(SDNode *N,
12740                                     SmallVectorImpl<SDValue> &Results,
12741                                     SelectionDAG &DAG, unsigned InterOp,
12742                                     unsigned AcrossOp) {
12743   EVT LoVT, HiVT;
12744   SDValue Lo, Hi;
12745   SDLoc dl(N);
12746   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
12747   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
12748   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
12749   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
12750   Results.push_back(SplitVal);
12751 }
12752 
12753 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
12754   SDLoc DL(N);
12755   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
12756   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
12757                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
12758                                        DAG.getConstant(64, DL, MVT::i64)));
12759   return std::make_pair(Lo, Hi);
12760 }
12761 
12762 // Create an even/odd pair of X registers holding integer value V.
12763 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
12764   SDLoc dl(V.getNode());
12765   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
12766   SDValue VHi = DAG.getAnyExtOrTrunc(
12767       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
12768       dl, MVT::i64);
12769   if (DAG.getDataLayout().isBigEndian())
12770     std::swap (VLo, VHi);
12771   SDValue RegClass =
12772       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
12773   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
12774   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
12775   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
12776   return SDValue(
12777       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
12778 }
12779 
12780 static void ReplaceCMP_SWAP_128Results(SDNode *N,
12781                                        SmallVectorImpl<SDValue> &Results,
12782                                        SelectionDAG &DAG,
12783                                        const AArch64Subtarget *Subtarget) {
12784   assert(N->getValueType(0) == MVT::i128 &&
12785          "AtomicCmpSwap on types less than 128 should be legal");
12786 
12787   if (Subtarget->hasLSE()) {
12788     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
12789     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
12790     SDValue Ops[] = {
12791         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
12792         createGPRPairNode(DAG, N->getOperand(3)), // Store value
12793         N->getOperand(1), // Ptr
12794         N->getOperand(0), // Chain in
12795     };
12796 
12797     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12798 
12799     unsigned Opcode;
12800     switch (MemOp->getOrdering()) {
12801     case AtomicOrdering::Monotonic:
12802       Opcode = AArch64::CASPX;
12803       break;
12804     case AtomicOrdering::Acquire:
12805       Opcode = AArch64::CASPAX;
12806       break;
12807     case AtomicOrdering::Release:
12808       Opcode = AArch64::CASPLX;
12809       break;
12810     case AtomicOrdering::AcquireRelease:
12811     case AtomicOrdering::SequentiallyConsistent:
12812       Opcode = AArch64::CASPALX;
12813       break;
12814     default:
12815       llvm_unreachable("Unexpected ordering!");
12816     }
12817 
12818     MachineSDNode *CmpSwap = DAG.getMachineNode(
12819         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
12820     DAG.setNodeMemRefs(CmpSwap, {MemOp});
12821 
12822     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
12823     if (DAG.getDataLayout().isBigEndian())
12824       std::swap(SubReg1, SubReg2);
12825     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
12826                                                  SDValue(CmpSwap, 0)));
12827     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
12828                                                  SDValue(CmpSwap, 0)));
12829     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
12830     return;
12831   }
12832 
12833   auto Desired = splitInt128(N->getOperand(2), DAG);
12834   auto New = splitInt128(N->getOperand(3), DAG);
12835   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
12836                    New.first,        New.second,    N->getOperand(0)};
12837   SDNode *CmpSwap = DAG.getMachineNode(
12838       AArch64::CMP_SWAP_128, SDLoc(N),
12839       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
12840 
12841   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12842   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
12843 
12844   Results.push_back(SDValue(CmpSwap, 0));
12845   Results.push_back(SDValue(CmpSwap, 1));
12846   Results.push_back(SDValue(CmpSwap, 3));
12847 }
12848 
12849 void AArch64TargetLowering::ReplaceNodeResults(
12850     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
12851   switch (N->getOpcode()) {
12852   default:
12853     llvm_unreachable("Don't know how to custom expand this");
12854   case ISD::BITCAST:
12855     ReplaceBITCASTResults(N, Results, DAG);
12856     return;
12857   case ISD::VECREDUCE_ADD:
12858   case ISD::VECREDUCE_SMAX:
12859   case ISD::VECREDUCE_SMIN:
12860   case ISD::VECREDUCE_UMAX:
12861   case ISD::VECREDUCE_UMIN:
12862     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
12863     return;
12864 
12865   case AArch64ISD::SADDV:
12866     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
12867     return;
12868   case AArch64ISD::UADDV:
12869     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
12870     return;
12871   case AArch64ISD::SMINV:
12872     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
12873     return;
12874   case AArch64ISD::UMINV:
12875     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
12876     return;
12877   case AArch64ISD::SMAXV:
12878     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
12879     return;
12880   case AArch64ISD::UMAXV:
12881     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
12882     return;
12883   case ISD::FP_TO_UINT:
12884   case ISD::FP_TO_SINT:
12885     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
12886     // Let normal code take care of it by not adding anything to Results.
12887     return;
12888   case ISD::ATOMIC_CMP_SWAP:
12889     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
12890     return;
12891   case ISD::LOAD: {
12892     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
12893            "unexpected load's value type");
12894     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
12895     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
12896       // Non-volatile loads are optimized later in AArch64's load/store
12897       // optimizer.
12898       return;
12899     }
12900 
12901     SDValue Result = DAG.getMemIntrinsicNode(
12902         AArch64ISD::LDP, SDLoc(N),
12903         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
12904         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
12905         LoadNode->getMemOperand());
12906 
12907     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
12908                                Result.getValue(0), Result.getValue(1));
12909     Results.append({Pair, Result.getValue(2) /* Chain */});
12910     return;
12911   }
12912   case ISD::INTRINSIC_WO_CHAIN: {
12913     EVT VT = N->getValueType(0);
12914     assert((VT == MVT::i8 || VT == MVT::i16) &&
12915            "custom lowering for unexpected type");
12916 
12917     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
12918     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12919     switch (IntID) {
12920     default:
12921       return;
12922     case Intrinsic::aarch64_sve_clasta_n: {
12923       SDLoc DL(N);
12924       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
12925       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
12926                            N->getOperand(1), Op2, N->getOperand(3));
12927       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
12928       return;
12929     }
12930     case Intrinsic::aarch64_sve_clastb_n: {
12931       SDLoc DL(N);
12932       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
12933       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
12934                            N->getOperand(1), Op2, N->getOperand(3));
12935       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
12936       return;
12937     }
12938     case Intrinsic::aarch64_sve_lasta: {
12939       SDLoc DL(N);
12940       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
12941                            N->getOperand(1), N->getOperand(2));
12942       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
12943       return;
12944     }
12945     case Intrinsic::aarch64_sve_lastb: {
12946       SDLoc DL(N);
12947       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
12948                            N->getOperand(1), N->getOperand(2));
12949       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
12950       return;
12951     }
12952     }
12953   }
12954   }
12955 }
12956 
12957 bool AArch64TargetLowering::useLoadStackGuardNode() const {
12958   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
12959     return TargetLowering::useLoadStackGuardNode();
12960   return true;
12961 }
12962 
12963 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
12964   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12965   // reciprocal if there are three or more FDIVs.
12966   return 3;
12967 }
12968 
12969 TargetLoweringBase::LegalizeTypeAction
12970 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
12971   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
12972   // v4i16, v2i32 instead of to promote.
12973   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
12974       VT == MVT::v1f32)
12975     return TypeWidenVector;
12976 
12977   return TargetLoweringBase::getPreferredVectorAction(VT);
12978 }
12979 
12980 // Loads and stores less than 128-bits are already atomic; ones above that
12981 // are doomed anyway, so defer to the default libcall and blame the OS when
12982 // things go wrong.
12983 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12984   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12985   return Size == 128;
12986 }
12987 
12988 // Loads and stores less than 128-bits are already atomic; ones above that
12989 // are doomed anyway, so defer to the default libcall and blame the OS when
12990 // things go wrong.
12991 TargetLowering::AtomicExpansionKind
12992 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12993   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12994   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
12995 }
12996 
12997 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
12998 TargetLowering::AtomicExpansionKind
12999 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13000   if (AI->isFloatingPointOperation())
13001     return AtomicExpansionKind::CmpXChg;
13002 
13003   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13004   if (Size > 128) return AtomicExpansionKind::None;
13005   // Nand not supported in LSE.
13006   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
13007   // Leave 128 bits to LLSC.
13008   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
13009 }
13010 
13011 TargetLowering::AtomicExpansionKind
13012 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
13013     AtomicCmpXchgInst *AI) const {
13014   // If subtarget has LSE, leave cmpxchg intact for codegen.
13015   if (Subtarget->hasLSE())
13016     return AtomicExpansionKind::None;
13017   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13018   // implement cmpxchg without spilling. If the address being exchanged is also
13019   // on the stack and close enough to the spill slot, this can lead to a
13020   // situation where the monitor always gets cleared and the atomic operation
13021   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13022   if (getTargetMachine().getOptLevel() == 0)
13023     return AtomicExpansionKind::None;
13024   return AtomicExpansionKind::LLSC;
13025 }
13026 
13027 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13028                                              AtomicOrdering Ord) const {
13029   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13030   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13031   bool IsAcquire = isAcquireOrStronger(Ord);
13032 
13033   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
13034   // intrinsic must return {i64, i64} and we have to recombine them into a
13035   // single i128 here.
13036   if (ValTy->getPrimitiveSizeInBits() == 128) {
13037     Intrinsic::ID Int =
13038         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
13039     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
13040 
13041     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13042     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
13043 
13044     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13045     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13046     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13047     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13048     return Builder.CreateOr(
13049         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
13050   }
13051 
13052   Type *Tys[] = { Addr->getType() };
13053   Intrinsic::ID Int =
13054       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
13055   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
13056 
13057   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
13058 
13059   const DataLayout &DL = M->getDataLayout();
13060   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
13061   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
13062 
13063   return Builder.CreateBitCast(Trunc, EltTy);
13064 }
13065 
13066 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13067     IRBuilder<> &Builder) const {
13068   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13069   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
13070 }
13071 
13072 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
13073                                                    Value *Val, Value *Addr,
13074                                                    AtomicOrdering Ord) const {
13075   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13076   bool IsRelease = isReleaseOrStronger(Ord);
13077 
13078   // Since the intrinsics must have legal type, the i128 intrinsics take two
13079   // parameters: "i64, i64". We must marshal Val into the appropriate form
13080   // before the call.
13081   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
13082     Intrinsic::ID Int =
13083         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
13084     Function *Stxr = Intrinsic::getDeclaration(M, Int);
13085     Type *Int64Ty = Type::getInt64Ty(M->getContext());
13086 
13087     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
13088     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
13089     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13090     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
13091   }
13092 
13093   Intrinsic::ID Int =
13094       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
13095   Type *Tys[] = { Addr->getType() };
13096   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
13097 
13098   const DataLayout &DL = M->getDataLayout();
13099   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
13100   Val = Builder.CreateBitCast(Val, IntValTy);
13101 
13102   return Builder.CreateCall(Stxr,
13103                             {Builder.CreateZExtOrBitCast(
13104                                  Val, Stxr->getFunctionType()->getParamType(0)),
13105                              Addr});
13106 }
13107 
13108 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
13109     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13110   return Ty->isArrayTy();
13111 }
13112 
13113 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
13114                                                             EVT) const {
13115   return false;
13116 }
13117 
13118 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
13119   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
13120   Function *ThreadPointerFunc =
13121       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
13122   return IRB.CreatePointerCast(
13123       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
13124                              Offset),
13125       IRB.getInt8PtrTy()->getPointerTo(0));
13126 }
13127 
13128 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
13129   // Android provides a fixed TLS slot for the stack cookie. See the definition
13130   // of TLS_SLOT_STACK_GUARD in
13131   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13132   if (Subtarget->isTargetAndroid())
13133     return UseTlsOffset(IRB, 0x28);
13134 
13135   // Fuchsia is similar.
13136   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
13137   if (Subtarget->isTargetFuchsia())
13138     return UseTlsOffset(IRB, -0x10);
13139 
13140   return TargetLowering::getIRStackGuard(IRB);
13141 }
13142 
13143 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
13144   // MSVC CRT provides functionalities for stack protection.
13145   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
13146     // MSVC CRT has a global variable holding security cookie.
13147     M.getOrInsertGlobal("__security_cookie",
13148                         Type::getInt8PtrTy(M.getContext()));
13149 
13150     // MSVC CRT has a function to validate security cookie.
13151     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
13152         "__security_check_cookie", Type::getVoidTy(M.getContext()),
13153         Type::getInt8PtrTy(M.getContext()));
13154     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
13155       F->setCallingConv(CallingConv::Win64);
13156       F->addAttribute(1, Attribute::AttrKind::InReg);
13157     }
13158     return;
13159   }
13160   TargetLowering::insertSSPDeclarations(M);
13161 }
13162 
13163 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
13164   // MSVC CRT has a global variable holding security cookie.
13165   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13166     return M.getGlobalVariable("__security_cookie");
13167   return TargetLowering::getSDagStackGuard(M);
13168 }
13169 
13170 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
13171   // MSVC CRT has a function to validate security cookie.
13172   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13173     return M.getFunction("__security_check_cookie");
13174   return TargetLowering::getSSPStackGuardCheck(M);
13175 }
13176 
13177 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
13178   // Android provides a fixed TLS slot for the SafeStack pointer. See the
13179   // definition of TLS_SLOT_SAFESTACK in
13180   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13181   if (Subtarget->isTargetAndroid())
13182     return UseTlsOffset(IRB, 0x48);
13183 
13184   // Fuchsia is similar.
13185   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
13186   if (Subtarget->isTargetFuchsia())
13187     return UseTlsOffset(IRB, -0x8);
13188 
13189   return TargetLowering::getSafeStackPointerLocation(IRB);
13190 }
13191 
13192 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
13193     const Instruction &AndI) const {
13194   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
13195   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
13196   // may be beneficial to sink in other cases, but we would have to check that
13197   // the cmp would not get folded into the br to form a cbz for these to be
13198   // beneficial.
13199   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
13200   if (!Mask)
13201     return false;
13202   return Mask->getValue().isPowerOf2();
13203 }
13204 
13205 bool AArch64TargetLowering::
13206     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13207         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
13208         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
13209         SelectionDAG &DAG) const {
13210   // Does baseline recommend not to perform the fold by default?
13211   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13212           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
13213     return false;
13214   // Else, if this is a vector shift, prefer 'shl'.
13215   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
13216 }
13217 
13218 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
13219                                               SDNode *N) const {
13220   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
13221       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
13222     return false;
13223   return true;
13224 }
13225 
13226 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13227   // Update IsSplitCSR in AArch64unctionInfo.
13228   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
13229   AFI->setIsSplitCSR(true);
13230 }
13231 
13232 void AArch64TargetLowering::insertCopiesSplitCSR(
13233     MachineBasicBlock *Entry,
13234     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13235   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13236   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13237   if (!IStart)
13238     return;
13239 
13240   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13241   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13242   MachineBasicBlock::iterator MBBI = Entry->begin();
13243   for (const MCPhysReg *I = IStart; *I; ++I) {
13244     const TargetRegisterClass *RC = nullptr;
13245     if (AArch64::GPR64RegClass.contains(*I))
13246       RC = &AArch64::GPR64RegClass;
13247     else if (AArch64::FPR64RegClass.contains(*I))
13248       RC = &AArch64::FPR64RegClass;
13249     else
13250       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13251 
13252     Register NewVR = MRI->createVirtualRegister(RC);
13253     // Create copy from CSR to a virtual register.
13254     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13255     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13256     // nounwind. If we want to generalize this later, we may need to emit
13257     // CFI pseudo-instructions.
13258     assert(Entry->getParent()->getFunction().hasFnAttribute(
13259                Attribute::NoUnwind) &&
13260            "Function should be nounwind in insertCopiesSplitCSR!");
13261     Entry->addLiveIn(*I);
13262     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13263         .addReg(*I);
13264 
13265     // Insert the copy-back instructions right before the terminator.
13266     for (auto *Exit : Exits)
13267       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13268               TII->get(TargetOpcode::COPY), *I)
13269           .addReg(NewVR);
13270   }
13271 }
13272 
13273 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
13274   // Integer division on AArch64 is expensive. However, when aggressively
13275   // optimizing for code size, we prefer to use a div instruction, as it is
13276   // usually smaller than the alternative sequence.
13277   // The exception to this is vector division. Since AArch64 doesn't have vector
13278   // integer division, leaving the division as-is is a loss even in terms of
13279   // size, because it will have to be scalarized, while the alternative code
13280   // sequence can be performed in vector form.
13281   bool OptSize =
13282       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
13283   return OptSize && !VT.isVector();
13284 }
13285 
13286 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13287   // We want inc-of-add for scalars and sub-of-not for vectors.
13288   return VT.isScalarInteger();
13289 }
13290 
13291 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
13292   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
13293 }
13294 
13295 unsigned
13296 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
13297   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
13298     return getPointerTy(DL).getSizeInBits();
13299 
13300   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
13301 }
13302 
13303 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
13304   MF.getFrameInfo().computeMaxCallFrameSize(MF);
13305   TargetLoweringBase::finalizeLowering(MF);
13306 }
13307 
13308 // Unlike X86, we let frame lowering assign offsets to all catch objects.
13309 bool AArch64TargetLowering::needsFixedCatchObjects() const {
13310   return false;
13311 }
13312