1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.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/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetCallingConv.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/OperandTraits.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/Use.h"
63 #include "llvm/IR/Value.h"
64 #include "llvm/MC/MCRegisterInfo.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CodeGen.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MachineValueType.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <algorithm>
78 #include <bitset>
79 #include <cassert>
80 #include <cctype>
81 #include <cstdint>
82 #include <cstdlib>
83 #include <iterator>
84 #include <limits>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "aarch64-lower"
92 
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
96 
97 static cl::opt<bool>
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99                            cl::desc("Allow AArch64 SLI/SRI formation"),
100                            cl::init(false));
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120                                              const AArch64Subtarget &STI)
121     : TargetLowering(TM), Subtarget(&STI) {
122   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123   // we have to make something up. Arbitrarily, choose ZeroOrOne.
124   setBooleanContents(ZeroOrOneBooleanContent);
125   // When comparing vectors the result sets the different elements in the
126   // vector to all-one or all-zero.
127   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128 
129   // Set up the register classes.
130   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132 
133   if (Subtarget->hasFPARMv8()) {
134     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138   }
139 
140   if (Subtarget->hasNEON()) {
141     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143     // Someone set us up the NEON.
144     addDRTypeForNEON(MVT::v2f32);
145     addDRTypeForNEON(MVT::v8i8);
146     addDRTypeForNEON(MVT::v4i16);
147     addDRTypeForNEON(MVT::v2i32);
148     addDRTypeForNEON(MVT::v1i64);
149     addDRTypeForNEON(MVT::v1f64);
150     addDRTypeForNEON(MVT::v4f16);
151 
152     addQRTypeForNEON(MVT::v4f32);
153     addQRTypeForNEON(MVT::v2f64);
154     addQRTypeForNEON(MVT::v16i8);
155     addQRTypeForNEON(MVT::v8i16);
156     addQRTypeForNEON(MVT::v4i32);
157     addQRTypeForNEON(MVT::v2i64);
158     addQRTypeForNEON(MVT::v8f16);
159   }
160 
161   // Compute derived properties from the register classes
162   computeRegisterProperties(Subtarget->getRegisterInfo());
163 
164   // Provide all sorts of operation actions
165   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167   setOperationAction(ISD::SETCC, MVT::i32, Custom);
168   setOperationAction(ISD::SETCC, MVT::i64, Custom);
169   setOperationAction(ISD::SETCC, MVT::f16, Custom);
170   setOperationAction(ISD::SETCC, MVT::f32, Custom);
171   setOperationAction(ISD::SETCC, MVT::f64, Custom);
172   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
173   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
174   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
175   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
176   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
177   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
178   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
179   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
180   setOperationAction(ISD::SELECT, MVT::i32, Custom);
181   setOperationAction(ISD::SELECT, MVT::i64, Custom);
182   setOperationAction(ISD::SELECT, MVT::f16, Custom);
183   setOperationAction(ISD::SELECT, MVT::f32, Custom);
184   setOperationAction(ISD::SELECT, MVT::f64, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
186   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
187   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
188   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
189   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
190   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
191   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
192 
193   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
194   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
195   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
196 
197   setOperationAction(ISD::FREM, MVT::f32, Expand);
198   setOperationAction(ISD::FREM, MVT::f64, Expand);
199   setOperationAction(ISD::FREM, MVT::f80, Expand);
200 
201   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
202 
203   // Custom lowering hooks are needed for XOR
204   // to fold it into CSINC/CSINV.
205   setOperationAction(ISD::XOR, MVT::i32, Custom);
206   setOperationAction(ISD::XOR, MVT::i64, Custom);
207 
208   // Virtually no operation on f128 is legal, but LLVM can't expand them when
209   // there's a valid register class, so we need custom operations in most cases.
210   setOperationAction(ISD::FABS, MVT::f128, Expand);
211   setOperationAction(ISD::FADD, MVT::f128, Custom);
212   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
213   setOperationAction(ISD::FCOS, MVT::f128, Expand);
214   setOperationAction(ISD::FDIV, MVT::f128, Custom);
215   setOperationAction(ISD::FMA, MVT::f128, Expand);
216   setOperationAction(ISD::FMUL, MVT::f128, Custom);
217   setOperationAction(ISD::FNEG, MVT::f128, Expand);
218   setOperationAction(ISD::FPOW, MVT::f128, Expand);
219   setOperationAction(ISD::FREM, MVT::f128, Expand);
220   setOperationAction(ISD::FRINT, MVT::f128, Expand);
221   setOperationAction(ISD::FSIN, MVT::f128, Expand);
222   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
223   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
224   setOperationAction(ISD::FSUB, MVT::f128, Custom);
225   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
226   setOperationAction(ISD::SETCC, MVT::f128, Custom);
227   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
228   setOperationAction(ISD::SELECT, MVT::f128, Custom);
229   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
230   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
231 
232   // Lowering for many of the conversions is actually specified by the non-f128
233   // type. The LowerXXX function will be trivial when f128 isn't involved.
234   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
235   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
236   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
237   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
238   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
239   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
240   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
241   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
242   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
243   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
244   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
245   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
246   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
247   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
248 
249   // Variable arguments.
250   setOperationAction(ISD::VASTART, MVT::Other, Custom);
251   setOperationAction(ISD::VAARG, MVT::Other, Custom);
252   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
253   setOperationAction(ISD::VAEND, MVT::Other, Expand);
254 
255   // Variable-sized objects.
256   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
258 
259   if (Subtarget->isTargetWindows())
260     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
261   else
262     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
263 
264   // Constant pool entries
265   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
266 
267   // BlockAddress
268   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
269 
270   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
271   setOperationAction(ISD::ADDC, MVT::i32, Custom);
272   setOperationAction(ISD::ADDE, MVT::i32, Custom);
273   setOperationAction(ISD::SUBC, MVT::i32, Custom);
274   setOperationAction(ISD::SUBE, MVT::i32, Custom);
275   setOperationAction(ISD::ADDC, MVT::i64, Custom);
276   setOperationAction(ISD::ADDE, MVT::i64, Custom);
277   setOperationAction(ISD::SUBC, MVT::i64, Custom);
278   setOperationAction(ISD::SUBE, MVT::i64, Custom);
279 
280   // AArch64 lacks both left-rotate and popcount instructions.
281   setOperationAction(ISD::ROTL, MVT::i32, Expand);
282   setOperationAction(ISD::ROTL, MVT::i64, Expand);
283   for (MVT VT : MVT::vector_valuetypes()) {
284     setOperationAction(ISD::ROTL, VT, Expand);
285     setOperationAction(ISD::ROTR, VT, Expand);
286   }
287 
288   // AArch64 doesn't have {U|S}MUL_LOHI.
289   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
290   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
291 
292   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
293   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
294 
295   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
296   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
297   for (MVT VT : MVT::vector_valuetypes()) {
298     setOperationAction(ISD::SDIVREM, VT, Expand);
299     setOperationAction(ISD::UDIVREM, VT, Expand);
300   }
301   setOperationAction(ISD::SREM, MVT::i32, Expand);
302   setOperationAction(ISD::SREM, MVT::i64, Expand);
303   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
304   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
305   setOperationAction(ISD::UREM, MVT::i32, Expand);
306   setOperationAction(ISD::UREM, MVT::i64, Expand);
307 
308   // Custom lower Add/Sub/Mul with overflow.
309   setOperationAction(ISD::SADDO, MVT::i32, Custom);
310   setOperationAction(ISD::SADDO, MVT::i64, Custom);
311   setOperationAction(ISD::UADDO, MVT::i32, Custom);
312   setOperationAction(ISD::UADDO, MVT::i64, Custom);
313   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
314   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
315   setOperationAction(ISD::USUBO, MVT::i32, Custom);
316   setOperationAction(ISD::USUBO, MVT::i64, Custom);
317   setOperationAction(ISD::SMULO, MVT::i32, Custom);
318   setOperationAction(ISD::SMULO, MVT::i64, Custom);
319   setOperationAction(ISD::UMULO, MVT::i32, Custom);
320   setOperationAction(ISD::UMULO, MVT::i64, Custom);
321 
322   setOperationAction(ISD::FSIN, MVT::f32, Expand);
323   setOperationAction(ISD::FSIN, MVT::f64, Expand);
324   setOperationAction(ISD::FCOS, MVT::f32, Expand);
325   setOperationAction(ISD::FCOS, MVT::f64, Expand);
326   setOperationAction(ISD::FPOW, MVT::f32, Expand);
327   setOperationAction(ISD::FPOW, MVT::f64, Expand);
328   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
330   if (Subtarget->hasFullFP16())
331     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
332   else
333     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
334 
335   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
336   setOperationAction(ISD::FREM,    MVT::v4f16, Promote);
337   setOperationAction(ISD::FREM,    MVT::v8f16, Promote);
338   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
339   setOperationAction(ISD::FPOW,    MVT::v4f16, Promote);
340   setOperationAction(ISD::FPOW,    MVT::v8f16, Promote);
341   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
342   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
343   setOperationAction(ISD::FCOS,    MVT::v4f16, Promote);
344   setOperationAction(ISD::FCOS,    MVT::v8f16, Promote);
345   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
346   setOperationAction(ISD::FSIN,    MVT::v4f16, Promote);
347   setOperationAction(ISD::FSIN,    MVT::v8f16, Promote);
348   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
349   setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
350   setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
351   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
352   setOperationAction(ISD::FEXP,    MVT::v4f16, Promote);
353   setOperationAction(ISD::FEXP,    MVT::v8f16, Promote);
354   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
355   setOperationAction(ISD::FEXP2,   MVT::v4f16, Promote);
356   setOperationAction(ISD::FEXP2,   MVT::v8f16, Promote);
357   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
358   setOperationAction(ISD::FLOG,    MVT::v4f16, Promote);
359   setOperationAction(ISD::FLOG,    MVT::v8f16, Promote);
360   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
361   setOperationAction(ISD::FLOG2,   MVT::v4f16, Promote);
362   setOperationAction(ISD::FLOG2,   MVT::v8f16, Promote);
363   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
364   setOperationAction(ISD::FLOG10,  MVT::v4f16, Promote);
365   setOperationAction(ISD::FLOG10,  MVT::v8f16, Promote);
366 
367   if (!Subtarget->hasFullFP16()) {
368     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
369     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
370     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
371     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
372     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
373     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
374     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
375     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
376     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
377     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
378     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
379     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
380     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
381     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
382     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
383     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
384     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
385     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
386     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
387     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
388     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
389     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
390 
391     // promote v4f16 to v4f32 when that is known to be safe.
392     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
393     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
394     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
395     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
396     setOperationAction(ISD::FP_EXTEND,   MVT::v4f16, Promote);
397     setOperationAction(ISD::FP_ROUND,    MVT::v4f16, Promote);
398     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
399     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
400     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
401     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
402     AddPromotedToType(ISD::FP_EXTEND,    MVT::v4f16, MVT::v4f32);
403     AddPromotedToType(ISD::FP_ROUND,     MVT::v4f16, MVT::v4f32);
404 
405     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
406     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
407     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
408     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
409     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
410     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
411     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
412     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
413     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
414     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
415     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
416     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
417     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
418     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
419     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
420 
421     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
422     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
423     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
424     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
425     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
426     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
427     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
428     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
429     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
430     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
431     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
432     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
433     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
434     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
435     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
436     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
437     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
438     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
439     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
440     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
441   }
442 
443   // AArch64 has implementations of a lot of rounding-like FP operations.
444   for (MVT Ty : {MVT::f32, MVT::f64}) {
445     setOperationAction(ISD::FFLOOR, Ty, Legal);
446     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
447     setOperationAction(ISD::FCEIL, Ty, Legal);
448     setOperationAction(ISD::FRINT, Ty, Legal);
449     setOperationAction(ISD::FTRUNC, Ty, Legal);
450     setOperationAction(ISD::FROUND, Ty, Legal);
451     setOperationAction(ISD::FMINNUM, Ty, Legal);
452     setOperationAction(ISD::FMAXNUM, Ty, Legal);
453     setOperationAction(ISD::FMINIMUM, Ty, Legal);
454     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
455   }
456 
457   if (Subtarget->hasFullFP16()) {
458     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
459     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
460     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
461     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
462     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
463     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
464     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
465     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
466     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
467     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
468   }
469 
470   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
471 
472   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
473 
474   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
475   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
476   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
477   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
478   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
479 
480   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
481   // This requires the Performance Monitors extension.
482   if (Subtarget->hasPerfMon())
483     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
484 
485   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
486       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
487     // Issue __sincos_stret if available.
488     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
489     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
490   } else {
491     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
492     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
493   }
494 
495   // Make floating-point constants legal for the large code model, so they don't
496   // become loads from the constant pool.
497   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
498     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
499     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
500   }
501 
502   // AArch64 does not have floating-point extending loads, i1 sign-extending
503   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
504   for (MVT VT : MVT::fp_valuetypes()) {
505     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
506     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
507     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
508     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
509   }
510   for (MVT VT : MVT::integer_valuetypes())
511     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
512 
513   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
514   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
515   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
516   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
517   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
518   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
519   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
520 
521   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
522   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
523 
524   // Indexed loads and stores are supported.
525   for (unsigned im = (unsigned)ISD::PRE_INC;
526        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
527     setIndexedLoadAction(im, MVT::i8, Legal);
528     setIndexedLoadAction(im, MVT::i16, Legal);
529     setIndexedLoadAction(im, MVT::i32, Legal);
530     setIndexedLoadAction(im, MVT::i64, Legal);
531     setIndexedLoadAction(im, MVT::f64, Legal);
532     setIndexedLoadAction(im, MVT::f32, Legal);
533     setIndexedLoadAction(im, MVT::f16, Legal);
534     setIndexedStoreAction(im, MVT::i8, Legal);
535     setIndexedStoreAction(im, MVT::i16, Legal);
536     setIndexedStoreAction(im, MVT::i32, Legal);
537     setIndexedStoreAction(im, MVT::i64, Legal);
538     setIndexedStoreAction(im, MVT::f64, Legal);
539     setIndexedStoreAction(im, MVT::f32, Legal);
540     setIndexedStoreAction(im, MVT::f16, Legal);
541   }
542 
543   // Trap.
544   setOperationAction(ISD::TRAP, MVT::Other, Legal);
545 
546   // We combine OR nodes for bitfield operations.
547   setTargetDAGCombine(ISD::OR);
548 
549   // Vector add and sub nodes may conceal a high-half opportunity.
550   // Also, try to fold ADD into CSINC/CSINV..
551   setTargetDAGCombine(ISD::ADD);
552   setTargetDAGCombine(ISD::SUB);
553   setTargetDAGCombine(ISD::SRL);
554   setTargetDAGCombine(ISD::XOR);
555   setTargetDAGCombine(ISD::SINT_TO_FP);
556   setTargetDAGCombine(ISD::UINT_TO_FP);
557 
558   setTargetDAGCombine(ISD::FP_TO_SINT);
559   setTargetDAGCombine(ISD::FP_TO_UINT);
560   setTargetDAGCombine(ISD::FDIV);
561 
562   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563 
564   setTargetDAGCombine(ISD::ANY_EXTEND);
565   setTargetDAGCombine(ISD::ZERO_EXTEND);
566   setTargetDAGCombine(ISD::SIGN_EXTEND);
567   setTargetDAGCombine(ISD::BITCAST);
568   setTargetDAGCombine(ISD::CONCAT_VECTORS);
569   setTargetDAGCombine(ISD::STORE);
570   if (Subtarget->supportsAddressTopByteIgnored())
571     setTargetDAGCombine(ISD::LOAD);
572 
573   setTargetDAGCombine(ISD::MUL);
574 
575   setTargetDAGCombine(ISD::SELECT);
576   setTargetDAGCombine(ISD::VSELECT);
577 
578   setTargetDAGCombine(ISD::INTRINSIC_VOID);
579   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
581 
582   setTargetDAGCombine(ISD::GlobalAddress);
583 
584   // In case of strict alignment, avoid an excessive number of byte wide stores.
585   MaxStoresPerMemsetOptSize = 8;
586   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
587                        ? MaxStoresPerMemsetOptSize : 32;
588 
589   MaxGluedStoresPerMemcpy = 4;
590   MaxStoresPerMemcpyOptSize = 4;
591   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
592                        ? MaxStoresPerMemcpyOptSize : 16;
593 
594   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
595 
596   setStackPointerRegisterToSaveRestore(AArch64::SP);
597 
598   setSchedulingPreference(Sched::Hybrid);
599 
600   EnableExtLdPromotion = true;
601 
602   // Set required alignment.
603   setMinFunctionAlignment(2);
604   // Set preferred alignments.
605   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
606   setPrefLoopAlignment(STI.getPrefLoopAlignment());
607 
608   // Only change the limit for entries in a jump table if specified by
609   // the subtarget, but not at the command line.
610   unsigned MaxJT = STI.getMaximumJumpTableSize();
611   if (MaxJT && getMaximumJumpTableSize() == 0)
612     setMaximumJumpTableSize(MaxJT);
613 
614   setHasExtractBitsInsn(true);
615 
616   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
617 
618   if (Subtarget->hasNEON()) {
619     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
620     // silliness like this:
621     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
622     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
623     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
624     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
625     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
626     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
627     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
628     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
629     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
630     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
631     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
632     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
633     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
634     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
635     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
636     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
637     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
638     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
639     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
641     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
642     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
643     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
644     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
645     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
646 
647     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
648     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
649     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
650     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
651     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
652 
653     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
654 
655     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
656     // elements smaller than i32, so promote the input to i32 first.
657     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
658     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
659     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
660     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
661     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
662     // -> v8f16 conversions.
663     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
664     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
665     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
666     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
667     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
668     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
669     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
670     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
671     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
672     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
673     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
674     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
675     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
676 
677     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
678     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
679 
680     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
681     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
682     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
683     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
684     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
685     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
686     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
687     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
688 
689     // AArch64 doesn't have MUL.2d:
690     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
691     // Custom handling for some quad-vector types to detect MULL.
692     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
693     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
694     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
695 
696     // Vector reductions
697     for (MVT VT : MVT::integer_valuetypes()) {
698       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
699       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
700       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
701       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
702       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
703     }
704     for (MVT VT : MVT::fp_valuetypes()) {
705       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
706       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
707     }
708 
709     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
710     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
711     // Likewise, narrowing and extending vector loads/stores aren't handled
712     // directly.
713     for (MVT VT : MVT::vector_valuetypes()) {
714       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
715 
716       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
717         setOperationAction(ISD::MULHS, VT, Custom);
718         setOperationAction(ISD::MULHU, VT, Custom);
719       } else {
720         setOperationAction(ISD::MULHS, VT, Expand);
721         setOperationAction(ISD::MULHU, VT, Expand);
722       }
723       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
724       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
725 
726       setOperationAction(ISD::BSWAP, VT, Expand);
727 
728       for (MVT InnerVT : MVT::vector_valuetypes()) {
729         setTruncStoreAction(VT, InnerVT, Expand);
730         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
731         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
732         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
733       }
734     }
735 
736     // AArch64 has implementations of a lot of rounding-like FP operations.
737     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
738       setOperationAction(ISD::FFLOOR, Ty, Legal);
739       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
740       setOperationAction(ISD::FCEIL, Ty, Legal);
741       setOperationAction(ISD::FRINT, Ty, Legal);
742       setOperationAction(ISD::FTRUNC, Ty, Legal);
743       setOperationAction(ISD::FROUND, Ty, Legal);
744     }
745 
746     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
747   }
748 
749   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
750 }
751 
752 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
753   assert(VT.isVector() && "VT should be a vector type");
754 
755   if (VT.isFloatingPoint()) {
756     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
757     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
758     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
759   }
760 
761   // Mark vector float intrinsics as expand.
762   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
763     setOperationAction(ISD::FSIN, VT, Expand);
764     setOperationAction(ISD::FCOS, VT, Expand);
765     setOperationAction(ISD::FPOW, VT, Expand);
766     setOperationAction(ISD::FLOG, VT, Expand);
767     setOperationAction(ISD::FLOG2, VT, Expand);
768     setOperationAction(ISD::FLOG10, VT, Expand);
769     setOperationAction(ISD::FEXP, VT, Expand);
770     setOperationAction(ISD::FEXP2, VT, Expand);
771 
772     // But we do support custom-lowering for FCOPYSIGN.
773     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
774   }
775 
776   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
777   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
778   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
779   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
780   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
781   setOperationAction(ISD::SRA, VT, Custom);
782   setOperationAction(ISD::SRL, VT, Custom);
783   setOperationAction(ISD::SHL, VT, Custom);
784   setOperationAction(ISD::AND, VT, Custom);
785   setOperationAction(ISD::OR, VT, Custom);
786   setOperationAction(ISD::SETCC, VT, Custom);
787   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
788 
789   setOperationAction(ISD::SELECT, VT, Expand);
790   setOperationAction(ISD::SELECT_CC, VT, Expand);
791   setOperationAction(ISD::VSELECT, VT, Expand);
792   for (MVT InnerVT : MVT::all_valuetypes())
793     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
794 
795   // CNT supports only B element sizes, then use UADDLP to widen.
796   if (VT != MVT::v8i8 && VT != MVT::v16i8)
797     setOperationAction(ISD::CTPOP, VT, Custom);
798 
799   setOperationAction(ISD::UDIV, VT, Expand);
800   setOperationAction(ISD::SDIV, VT, Expand);
801   setOperationAction(ISD::UREM, VT, Expand);
802   setOperationAction(ISD::SREM, VT, Expand);
803   setOperationAction(ISD::FREM, VT, Expand);
804 
805   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
806   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
807 
808   if (!VT.isFloatingPoint())
809     setOperationAction(ISD::ABS, VT, Legal);
810 
811   // [SU][MIN|MAX] are available for all NEON types apart from i64.
812   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
813     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
814       setOperationAction(Opcode, VT, Legal);
815 
816   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
817   if (VT.isFloatingPoint() &&
818       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
819     for (unsigned Opcode :
820          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
821       setOperationAction(Opcode, VT, Legal);
822 
823   if (Subtarget->isLittleEndian()) {
824     for (unsigned im = (unsigned)ISD::PRE_INC;
825          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
826       setIndexedLoadAction(im, VT, Legal);
827       setIndexedStoreAction(im, VT, Legal);
828     }
829   }
830 }
831 
832 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
833   addRegisterClass(VT, &AArch64::FPR64RegClass);
834   addTypeForNEON(VT, MVT::v2i32);
835 }
836 
837 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
838   addRegisterClass(VT, &AArch64::FPR128RegClass);
839   addTypeForNEON(VT, MVT::v4i32);
840 }
841 
842 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
843                                               EVT VT) const {
844   if (!VT.isVector())
845     return MVT::i32;
846   return VT.changeVectorElementTypeToInteger();
847 }
848 
849 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
850                                const APInt &Demanded,
851                                TargetLowering::TargetLoweringOpt &TLO,
852                                unsigned NewOpc) {
853   uint64_t OldImm = Imm, NewImm, Enc;
854   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
855 
856   // Return if the immediate is already all zeros, all ones, a bimm32 or a
857   // bimm64.
858   if (Imm == 0 || Imm == Mask ||
859       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
860     return false;
861 
862   unsigned EltSize = Size;
863   uint64_t DemandedBits = Demanded.getZExtValue();
864 
865   // Clear bits that are not demanded.
866   Imm &= DemandedBits;
867 
868   while (true) {
869     // The goal here is to set the non-demanded bits in a way that minimizes
870     // the number of switching between 0 and 1. In order to achieve this goal,
871     // we set the non-demanded bits to the value of the preceding demanded bits.
872     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
873     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
874     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
875     // The final result is 0b11000011.
876     uint64_t NonDemandedBits = ~DemandedBits;
877     uint64_t InvertedImm = ~Imm & DemandedBits;
878     uint64_t RotatedImm =
879         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
880         NonDemandedBits;
881     uint64_t Sum = RotatedImm + NonDemandedBits;
882     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
883     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
884     NewImm = (Imm | Ones) & Mask;
885 
886     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
887     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
888     // we halve the element size and continue the search.
889     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
890       break;
891 
892     // We cannot shrink the element size any further if it is 2-bits.
893     if (EltSize == 2)
894       return false;
895 
896     EltSize /= 2;
897     Mask >>= EltSize;
898     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
899 
900     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
901     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
902       return false;
903 
904     // Merge the upper and lower halves of Imm and DemandedBits.
905     Imm |= Hi;
906     DemandedBits |= DemandedBitsHi;
907   }
908 
909   ++NumOptimizedImms;
910 
911   // Replicate the element across the register width.
912   while (EltSize < Size) {
913     NewImm |= NewImm << EltSize;
914     EltSize *= 2;
915   }
916 
917   (void)OldImm;
918   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
919          "demanded bits should never be altered");
920   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
921 
922   // Create the new constant immediate node.
923   EVT VT = Op.getValueType();
924   SDLoc DL(Op);
925   SDValue New;
926 
927   // If the new constant immediate is all-zeros or all-ones, let the target
928   // independent DAG combine optimize this node.
929   if (NewImm == 0 || NewImm == OrigMask) {
930     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
931                           TLO.DAG.getConstant(NewImm, DL, VT));
932   // Otherwise, create a machine node so that target independent DAG combine
933   // doesn't undo this optimization.
934   } else {
935     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
936     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
937     New = SDValue(
938         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
939   }
940 
941   return TLO.CombineTo(Op, New);
942 }
943 
944 bool AArch64TargetLowering::targetShrinkDemandedConstant(
945     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
946   // Delay this optimization to as late as possible.
947   if (!TLO.LegalOps)
948     return false;
949 
950   if (!EnableOptimizeLogicalImm)
951     return false;
952 
953   EVT VT = Op.getValueType();
954   if (VT.isVector())
955     return false;
956 
957   unsigned Size = VT.getSizeInBits();
958   assert((Size == 32 || Size == 64) &&
959          "i32 or i64 is expected after legalization.");
960 
961   // Exit early if we demand all bits.
962   if (Demanded.countPopulation() == Size)
963     return false;
964 
965   unsigned NewOpc;
966   switch (Op.getOpcode()) {
967   default:
968     return false;
969   case ISD::AND:
970     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
971     break;
972   case ISD::OR:
973     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
974     break;
975   case ISD::XOR:
976     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
977     break;
978   }
979   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
980   if (!C)
981     return false;
982   uint64_t Imm = C->getZExtValue();
983   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
984 }
985 
986 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
987 /// Mask are known to be either zero or one and return them Known.
988 void AArch64TargetLowering::computeKnownBitsForTargetNode(
989     const SDValue Op, KnownBits &Known,
990     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
991   switch (Op.getOpcode()) {
992   default:
993     break;
994   case AArch64ISD::CSEL: {
995     KnownBits Known2;
996     DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
997     DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
998     Known.Zero &= Known2.Zero;
999     Known.One &= Known2.One;
1000     break;
1001   }
1002   case ISD::INTRINSIC_W_CHAIN: {
1003     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1004     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1005     switch (IntID) {
1006     default: return;
1007     case Intrinsic::aarch64_ldaxr:
1008     case Intrinsic::aarch64_ldxr: {
1009       unsigned BitWidth = Known.getBitWidth();
1010       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1011       unsigned MemBits = VT.getScalarSizeInBits();
1012       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1013       return;
1014     }
1015     }
1016     break;
1017   }
1018   case ISD::INTRINSIC_WO_CHAIN:
1019   case ISD::INTRINSIC_VOID: {
1020     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021     switch (IntNo) {
1022     default:
1023       break;
1024     case Intrinsic::aarch64_neon_umaxv:
1025     case Intrinsic::aarch64_neon_uminv: {
1026       // Figure out the datatype of the vector operand. The UMINV instruction
1027       // will zero extend the result, so we can mark as known zero all the
1028       // bits larger than the element datatype. 32-bit or larget doesn't need
1029       // this as those are legal types and will be handled by isel directly.
1030       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1031       unsigned BitWidth = Known.getBitWidth();
1032       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1033         assert(BitWidth >= 8 && "Unexpected width!");
1034         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1035         Known.Zero |= Mask;
1036       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1037         assert(BitWidth >= 16 && "Unexpected width!");
1038         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1039         Known.Zero |= Mask;
1040       }
1041       break;
1042     } break;
1043     }
1044   }
1045   }
1046 }
1047 
1048 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1049                                                   EVT) const {
1050   return MVT::i64;
1051 }
1052 
1053 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1054                                                            unsigned AddrSpace,
1055                                                            unsigned Align,
1056                                                            bool *Fast) const {
1057   if (Subtarget->requiresStrictAlign())
1058     return false;
1059 
1060   if (Fast) {
1061     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1062     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1063             // See comments in performSTORECombine() for more details about
1064             // these conditions.
1065 
1066             // Code that uses clang vector extensions can mark that it
1067             // wants unaligned accesses to be treated as fast by
1068             // underspecifying alignment to be 1 or 2.
1069             Align <= 2 ||
1070 
1071             // Disregard v2i64. Memcpy lowering produces those and splitting
1072             // them regresses performance on micro-benchmarks and olden/bh.
1073             VT == MVT::v2i64;
1074   }
1075   return true;
1076 }
1077 
1078 FastISel *
1079 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1080                                       const TargetLibraryInfo *libInfo) const {
1081   return AArch64::createFastISel(funcInfo, libInfo);
1082 }
1083 
1084 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1085   switch ((AArch64ISD::NodeType)Opcode) {
1086   case AArch64ISD::FIRST_NUMBER:      break;
1087   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1088   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1089   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1090   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1091   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1092   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1093   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1094   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1095   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1096   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1097   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1098   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1099   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1100   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1101   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1102   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1103   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1104   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1105   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1106   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1107   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1108   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1109   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1110   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1111   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1112   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1113   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1114   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1115   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1116   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1117   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1118   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1119   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1120   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1121   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1122   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1123   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1124   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1125   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1126   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1127   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1128   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1129   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1130   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1131   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1132   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1133   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1134   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1135   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1136   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1137   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1138   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1139   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1140   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1141   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1142   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1143   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1144   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1145   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1146   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1147   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1148   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1149   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1150   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1151   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1152   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1153   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1154   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1155   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1156   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1157   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1158   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1159   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1160   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1161   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1162   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1163   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1164   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1165   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1166   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1167   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1168   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1169   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1170   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1171   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1172   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1173   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1174   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1175   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1176   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1177   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1178   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1179   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1180   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1181   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1182   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1183   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1184   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1185   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1186   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1187   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1188   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1189   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1190   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1191   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1192   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1193   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1194   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1195   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1196   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1197   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1198   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1199   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1200   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1201   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1202   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1203   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1204   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1205   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1206   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1207   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1208   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1209   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1210   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1211   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1212   }
1213   return nullptr;
1214 }
1215 
1216 MachineBasicBlock *
1217 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1218                                     MachineBasicBlock *MBB) const {
1219   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1220   // phi node:
1221 
1222   // OrigBB:
1223   //     [... previous instrs leading to comparison ...]
1224   //     b.ne TrueBB
1225   //     b EndBB
1226   // TrueBB:
1227   //     ; Fallthrough
1228   // EndBB:
1229   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1230 
1231   MachineFunction *MF = MBB->getParent();
1232   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1233   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1234   DebugLoc DL = MI.getDebugLoc();
1235   MachineFunction::iterator It = ++MBB->getIterator();
1236 
1237   unsigned DestReg = MI.getOperand(0).getReg();
1238   unsigned IfTrueReg = MI.getOperand(1).getReg();
1239   unsigned IfFalseReg = MI.getOperand(2).getReg();
1240   unsigned CondCode = MI.getOperand(3).getImm();
1241   bool NZCVKilled = MI.getOperand(4).isKill();
1242 
1243   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245   MF->insert(It, TrueBB);
1246   MF->insert(It, EndBB);
1247 
1248   // Transfer rest of current basic-block to EndBB
1249   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1250                 MBB->end());
1251   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1252 
1253   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1254   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1255   MBB->addSuccessor(TrueBB);
1256   MBB->addSuccessor(EndBB);
1257 
1258   // TrueBB falls through to the end.
1259   TrueBB->addSuccessor(EndBB);
1260 
1261   if (!NZCVKilled) {
1262     TrueBB->addLiveIn(AArch64::NZCV);
1263     EndBB->addLiveIn(AArch64::NZCV);
1264   }
1265 
1266   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1267       .addReg(IfTrueReg)
1268       .addMBB(TrueBB)
1269       .addReg(IfFalseReg)
1270       .addMBB(MBB);
1271 
1272   MI.eraseFromParent();
1273   return EndBB;
1274 }
1275 
1276 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1277     MachineInstr &MI, MachineBasicBlock *BB) const {
1278   switch (MI.getOpcode()) {
1279   default:
1280 #ifndef NDEBUG
1281     MI.dump();
1282 #endif
1283     llvm_unreachable("Unexpected instruction for custom inserter!");
1284 
1285   case AArch64::F128CSEL:
1286     return EmitF128CSEL(MI, BB);
1287 
1288   case TargetOpcode::STACKMAP:
1289   case TargetOpcode::PATCHPOINT:
1290     return emitPatchPoint(MI, BB);
1291   }
1292 }
1293 
1294 //===----------------------------------------------------------------------===//
1295 // AArch64 Lowering private implementation.
1296 //===----------------------------------------------------------------------===//
1297 
1298 //===----------------------------------------------------------------------===//
1299 // Lowering Code
1300 //===----------------------------------------------------------------------===//
1301 
1302 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1303 /// CC
1304 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1305   switch (CC) {
1306   default:
1307     llvm_unreachable("Unknown condition code!");
1308   case ISD::SETNE:
1309     return AArch64CC::NE;
1310   case ISD::SETEQ:
1311     return AArch64CC::EQ;
1312   case ISD::SETGT:
1313     return AArch64CC::GT;
1314   case ISD::SETGE:
1315     return AArch64CC::GE;
1316   case ISD::SETLT:
1317     return AArch64CC::LT;
1318   case ISD::SETLE:
1319     return AArch64CC::LE;
1320   case ISD::SETUGT:
1321     return AArch64CC::HI;
1322   case ISD::SETUGE:
1323     return AArch64CC::HS;
1324   case ISD::SETULT:
1325     return AArch64CC::LO;
1326   case ISD::SETULE:
1327     return AArch64CC::LS;
1328   }
1329 }
1330 
1331 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1332 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1333                                   AArch64CC::CondCode &CondCode,
1334                                   AArch64CC::CondCode &CondCode2) {
1335   CondCode2 = AArch64CC::AL;
1336   switch (CC) {
1337   default:
1338     llvm_unreachable("Unknown FP condition!");
1339   case ISD::SETEQ:
1340   case ISD::SETOEQ:
1341     CondCode = AArch64CC::EQ;
1342     break;
1343   case ISD::SETGT:
1344   case ISD::SETOGT:
1345     CondCode = AArch64CC::GT;
1346     break;
1347   case ISD::SETGE:
1348   case ISD::SETOGE:
1349     CondCode = AArch64CC::GE;
1350     break;
1351   case ISD::SETOLT:
1352     CondCode = AArch64CC::MI;
1353     break;
1354   case ISD::SETOLE:
1355     CondCode = AArch64CC::LS;
1356     break;
1357   case ISD::SETONE:
1358     CondCode = AArch64CC::MI;
1359     CondCode2 = AArch64CC::GT;
1360     break;
1361   case ISD::SETO:
1362     CondCode = AArch64CC::VC;
1363     break;
1364   case ISD::SETUO:
1365     CondCode = AArch64CC::VS;
1366     break;
1367   case ISD::SETUEQ:
1368     CondCode = AArch64CC::EQ;
1369     CondCode2 = AArch64CC::VS;
1370     break;
1371   case ISD::SETUGT:
1372     CondCode = AArch64CC::HI;
1373     break;
1374   case ISD::SETUGE:
1375     CondCode = AArch64CC::PL;
1376     break;
1377   case ISD::SETLT:
1378   case ISD::SETULT:
1379     CondCode = AArch64CC::LT;
1380     break;
1381   case ISD::SETLE:
1382   case ISD::SETULE:
1383     CondCode = AArch64CC::LE;
1384     break;
1385   case ISD::SETNE:
1386   case ISD::SETUNE:
1387     CondCode = AArch64CC::NE;
1388     break;
1389   }
1390 }
1391 
1392 /// Convert a DAG fp condition code to an AArch64 CC.
1393 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1394 /// should be AND'ed instead of OR'ed.
1395 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1396                                      AArch64CC::CondCode &CondCode,
1397                                      AArch64CC::CondCode &CondCode2) {
1398   CondCode2 = AArch64CC::AL;
1399   switch (CC) {
1400   default:
1401     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1402     assert(CondCode2 == AArch64CC::AL);
1403     break;
1404   case ISD::SETONE:
1405     // (a one b)
1406     // == ((a olt b) || (a ogt b))
1407     // == ((a ord b) && (a une b))
1408     CondCode = AArch64CC::VC;
1409     CondCode2 = AArch64CC::NE;
1410     break;
1411   case ISD::SETUEQ:
1412     // (a ueq b)
1413     // == ((a uno b) || (a oeq b))
1414     // == ((a ule b) && (a uge b))
1415     CondCode = AArch64CC::PL;
1416     CondCode2 = AArch64CC::LE;
1417     break;
1418   }
1419 }
1420 
1421 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1422 /// CC usable with the vector instructions. Fewer operations are available
1423 /// without a real NZCV register, so we have to use less efficient combinations
1424 /// to get the same effect.
1425 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1426                                         AArch64CC::CondCode &CondCode,
1427                                         AArch64CC::CondCode &CondCode2,
1428                                         bool &Invert) {
1429   Invert = false;
1430   switch (CC) {
1431   default:
1432     // Mostly the scalar mappings work fine.
1433     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1434     break;
1435   case ISD::SETUO:
1436     Invert = true;
1437     LLVM_FALLTHROUGH;
1438   case ISD::SETO:
1439     CondCode = AArch64CC::MI;
1440     CondCode2 = AArch64CC::GE;
1441     break;
1442   case ISD::SETUEQ:
1443   case ISD::SETULT:
1444   case ISD::SETULE:
1445   case ISD::SETUGT:
1446   case ISD::SETUGE:
1447     // All of the compare-mask comparisons are ordered, but we can switch
1448     // between the two by a double inversion. E.g. ULE == !OGT.
1449     Invert = true;
1450     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1451     break;
1452   }
1453 }
1454 
1455 static bool isLegalArithImmed(uint64_t C) {
1456   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1457   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1458   LLVM_DEBUG(dbgs() << "Is imm " << C
1459                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1460   return IsLegal;
1461 }
1462 
1463 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1464 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1465 // can be set differently by this operation. It comes down to whether
1466 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1467 // everything is fine. If not then the optimization is wrong. Thus general
1468 // comparisons are only valid if op2 != 0.
1469 //
1470 // So, finally, the only LLVM-native comparisons that don't mention C and V
1471 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1472 // the absence of information about op2.
1473 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1474   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1475          (CC == ISD::SETEQ || CC == ISD::SETNE);
1476 }
1477 
1478 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1479                               const SDLoc &dl, SelectionDAG &DAG) {
1480   EVT VT = LHS.getValueType();
1481   const bool FullFP16 =
1482     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1483 
1484   if (VT.isFloatingPoint()) {
1485     assert(VT != MVT::f128);
1486     if (VT == MVT::f16 && !FullFP16) {
1487       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1488       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1489       VT = MVT::f32;
1490     }
1491     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1492   }
1493 
1494   // The CMP instruction is just an alias for SUBS, and representing it as
1495   // SUBS means that it's possible to get CSE with subtract operations.
1496   // A later phase can perform the optimization of setting the destination
1497   // register to WZR/XZR if it ends up being unused.
1498   unsigned Opcode = AArch64ISD::SUBS;
1499 
1500   if (isCMN(RHS, CC)) {
1501     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1502     Opcode = AArch64ISD::ADDS;
1503     RHS = RHS.getOperand(1);
1504   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1505              !isUnsignedIntSetCC(CC)) {
1506     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1507     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1508     // of the signed comparisons.
1509     Opcode = AArch64ISD::ANDS;
1510     RHS = LHS.getOperand(1);
1511     LHS = LHS.getOperand(0);
1512   }
1513 
1514   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1515       .getValue(1);
1516 }
1517 
1518 /// \defgroup AArch64CCMP CMP;CCMP matching
1519 ///
1520 /// These functions deal with the formation of CMP;CCMP;... sequences.
1521 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1522 /// a comparison. They set the NZCV flags to a predefined value if their
1523 /// predicate is false. This allows to express arbitrary conjunctions, for
1524 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1525 /// expressed as:
1526 ///   cmp A
1527 ///   ccmp B, inv(CB), CA
1528 ///   check for CB flags
1529 ///
1530 /// In general we can create code for arbitrary "... (and (and A B) C)"
1531 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1532 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1533 /// negation operations:
1534 /// We can negate the results of a single comparison by inverting the flags
1535 /// used when the predicate fails and inverting the flags tested in the next
1536 /// instruction; We can also negate the results of the whole previous
1537 /// conditional compare sequence by inverting the flags tested in the next
1538 /// instruction. However there is no way to negate the result of a partial
1539 /// sequence.
1540 ///
1541 /// Therefore on encountering an "or" expression we can negate the subtree on
1542 /// one side and have to be able to push the negate to the leafs of the subtree
1543 /// on the other side (see also the comments in code). As complete example:
1544 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1545 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1546 /// is transformed to
1547 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1548 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1549 /// and implemented as:
1550 ///   cmp C
1551 ///   ccmp D, inv(CD), CC
1552 ///   ccmp A, CA, inv(CD)
1553 ///   ccmp B, CB, inv(CA)
1554 ///   check for CB flags
1555 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1556 /// by conditional compare sequences.
1557 /// @{
1558 
1559 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1560 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1561                                          ISD::CondCode CC, SDValue CCOp,
1562                                          AArch64CC::CondCode Predicate,
1563                                          AArch64CC::CondCode OutCC,
1564                                          const SDLoc &DL, SelectionDAG &DAG) {
1565   unsigned Opcode = 0;
1566   const bool FullFP16 =
1567     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1568 
1569   if (LHS.getValueType().isFloatingPoint()) {
1570     assert(LHS.getValueType() != MVT::f128);
1571     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1572       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1573       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1574     }
1575     Opcode = AArch64ISD::FCCMP;
1576   } else if (RHS.getOpcode() == ISD::SUB) {
1577     SDValue SubOp0 = RHS.getOperand(0);
1578     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1579       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1580       Opcode = AArch64ISD::CCMN;
1581       RHS = RHS.getOperand(1);
1582     }
1583   }
1584   if (Opcode == 0)
1585     Opcode = AArch64ISD::CCMP;
1586 
1587   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1588   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1589   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1590   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1591   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1592 }
1593 
1594 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1595 /// CanPushNegate is set to true if we can push a negate operation through
1596 /// the tree in a was that we are left with AND operations and negate operations
1597 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1598 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1599 /// brought into such a form.
1600 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1601                                          unsigned Depth = 0) {
1602   if (!Val.hasOneUse())
1603     return false;
1604   unsigned Opcode = Val->getOpcode();
1605   if (Opcode == ISD::SETCC) {
1606     if (Val->getOperand(0).getValueType() == MVT::f128)
1607       return false;
1608     CanNegate = true;
1609     return true;
1610   }
1611   // Protect against exponential runtime and stack overflow.
1612   if (Depth > 6)
1613     return false;
1614   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1615     SDValue O0 = Val->getOperand(0);
1616     SDValue O1 = Val->getOperand(1);
1617     bool CanNegateL;
1618     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1619       return false;
1620     bool CanNegateR;
1621     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1622       return false;
1623 
1624     if (Opcode == ISD::OR) {
1625       // For an OR expression we need to be able to negate at least one side or
1626       // we cannot do the transformation at all.
1627       if (!CanNegateL && !CanNegateR)
1628         return false;
1629       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1630       // can negate the x and y subtrees.
1631       CanNegate = CanNegateL && CanNegateR;
1632     } else {
1633       // If the operands are OR expressions then we finally need to negate their
1634       // outputs, we can only do that for the operand with emitted last by
1635       // negating OutCC, not for both operands.
1636       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1637       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1638       if (NeedsNegOutL && NeedsNegOutR)
1639         return false;
1640       // We cannot negate an AND operation (it would become an OR),
1641       CanNegate = false;
1642     }
1643     return true;
1644   }
1645   return false;
1646 }
1647 
1648 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1649 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1650 /// Tries to transform the given i1 producing node @p Val to a series compare
1651 /// and conditional compare operations. @returns an NZCV flags producing node
1652 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1653 /// transformation was not possible.
1654 /// On recursive invocations @p PushNegate may be set to true to have negation
1655 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1656 /// for the comparisons in the current subtree; @p Depth limits the search
1657 /// depth to avoid stack overflow.
1658 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1659     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1660     AArch64CC::CondCode Predicate) {
1661   // We're at a tree leaf, produce a conditional comparison operation.
1662   unsigned Opcode = Val->getOpcode();
1663   if (Opcode == ISD::SETCC) {
1664     SDValue LHS = Val->getOperand(0);
1665     SDValue RHS = Val->getOperand(1);
1666     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1667     bool isInteger = LHS.getValueType().isInteger();
1668     if (Negate)
1669       CC = getSetCCInverse(CC, isInteger);
1670     SDLoc DL(Val);
1671     // Determine OutCC and handle FP special case.
1672     if (isInteger) {
1673       OutCC = changeIntCCToAArch64CC(CC);
1674     } else {
1675       assert(LHS.getValueType().isFloatingPoint());
1676       AArch64CC::CondCode ExtraCC;
1677       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1678       // Some floating point conditions can't be tested with a single condition
1679       // code. Construct an additional comparison in this case.
1680       if (ExtraCC != AArch64CC::AL) {
1681         SDValue ExtraCmp;
1682         if (!CCOp.getNode())
1683           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1684         else
1685           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1686                                                ExtraCC, DL, DAG);
1687         CCOp = ExtraCmp;
1688         Predicate = ExtraCC;
1689       }
1690     }
1691 
1692     // Produce a normal comparison if we are first in the chain
1693     if (!CCOp)
1694       return emitComparison(LHS, RHS, CC, DL, DAG);
1695     // Otherwise produce a ccmp.
1696     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1697                                      DAG);
1698   }
1699   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1700          "Valid conjunction/disjunction tree");
1701 
1702   // Check if both sides can be transformed.
1703   SDValue LHS = Val->getOperand(0);
1704   SDValue RHS = Val->getOperand(1);
1705 
1706   // In case of an OR we need to negate our operands and the result.
1707   // (A v B) <=> not(not(A) ^ not(B))
1708   bool NegateOpsAndResult = Opcode == ISD::OR;
1709   // We can negate the results of all previous operations by inverting the
1710   // predicate flags giving us a free negation for one side. The other side
1711   // must be negatable by itself.
1712   if (NegateOpsAndResult) {
1713     // See which side we can negate.
1714     bool CanNegateL;
1715     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1716     assert(isValidL && "Valid conjunction/disjunction tree");
1717     (void)isValidL;
1718 
1719 #ifndef NDEBUG
1720     bool CanNegateR;
1721     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1722     assert(isValidR && "Valid conjunction/disjunction tree");
1723     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1724 #endif
1725 
1726     // Order the side which we cannot negate to RHS so we can emit it first.
1727     if (!CanNegateL)
1728       std::swap(LHS, RHS);
1729   } else {
1730     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1731     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1732            "Valid conjunction/disjunction tree");
1733     // Order the side where we need to negate the output flags to RHS so it
1734     // gets emitted first.
1735     if (NeedsNegOutL)
1736       std::swap(LHS, RHS);
1737   }
1738 
1739   // Emit RHS. If we want to negate the tree we only need to push a negate
1740   // through if we are already in a PushNegate case, otherwise we can negate
1741   // the "flags to test" afterwards.
1742   AArch64CC::CondCode RHSCC;
1743   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1744                                                    CCOp, Predicate);
1745   if (NegateOpsAndResult && !Negate)
1746     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1747   // Emit LHS. We may need to negate it.
1748   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1749                                                    NegateOpsAndResult, CmpR,
1750                                                    RHSCC);
1751   // If we transformed an OR to and AND then we have to negate the result
1752   // (or absorb the Negate parameter).
1753   if (NegateOpsAndResult && !Negate)
1754     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1755   return CmpL;
1756 }
1757 
1758 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1759 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1760 /// \see emitConjunctionDisjunctionTreeRec().
1761 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1762                                               AArch64CC::CondCode &OutCC) {
1763   bool CanNegate;
1764   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1765     return SDValue();
1766 
1767   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1768                                            AArch64CC::AL);
1769 }
1770 
1771 /// @}
1772 
1773 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1774 /// extension operations.
1775 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1776   auto isSupportedExtend = [&](SDValue V) {
1777     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1778       return true;
1779 
1780     if (V.getOpcode() == ISD::AND)
1781       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1782         uint64_t Mask = MaskCst->getZExtValue();
1783         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1784       }
1785 
1786     return false;
1787   };
1788 
1789   if (!Op.hasOneUse())
1790     return 0;
1791 
1792   if (isSupportedExtend(Op))
1793     return 1;
1794 
1795   unsigned Opc = Op.getOpcode();
1796   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1797     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1798       uint64_t Shift = ShiftCst->getZExtValue();
1799       if (isSupportedExtend(Op.getOperand(0)))
1800         return (Shift <= 4) ? 2 : 1;
1801       EVT VT = Op.getValueType();
1802       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1803         return 1;
1804     }
1805 
1806   return 0;
1807 }
1808 
1809 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1810                              SDValue &AArch64cc, SelectionDAG &DAG,
1811                              const SDLoc &dl) {
1812   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1813     EVT VT = RHS.getValueType();
1814     uint64_t C = RHSC->getZExtValue();
1815     if (!isLegalArithImmed(C)) {
1816       // Constant does not fit, try adjusting it by one?
1817       switch (CC) {
1818       default:
1819         break;
1820       case ISD::SETLT:
1821       case ISD::SETGE:
1822         if ((VT == MVT::i32 && C != 0x80000000 &&
1823              isLegalArithImmed((uint32_t)(C - 1))) ||
1824             (VT == MVT::i64 && C != 0x80000000ULL &&
1825              isLegalArithImmed(C - 1ULL))) {
1826           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1827           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1828           RHS = DAG.getConstant(C, dl, VT);
1829         }
1830         break;
1831       case ISD::SETULT:
1832       case ISD::SETUGE:
1833         if ((VT == MVT::i32 && C != 0 &&
1834              isLegalArithImmed((uint32_t)(C - 1))) ||
1835             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1836           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1837           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1838           RHS = DAG.getConstant(C, dl, VT);
1839         }
1840         break;
1841       case ISD::SETLE:
1842       case ISD::SETGT:
1843         if ((VT == MVT::i32 && C != INT32_MAX &&
1844              isLegalArithImmed((uint32_t)(C + 1))) ||
1845             (VT == MVT::i64 && C != INT64_MAX &&
1846              isLegalArithImmed(C + 1ULL))) {
1847           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1848           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1849           RHS = DAG.getConstant(C, dl, VT);
1850         }
1851         break;
1852       case ISD::SETULE:
1853       case ISD::SETUGT:
1854         if ((VT == MVT::i32 && C != UINT32_MAX &&
1855              isLegalArithImmed((uint32_t)(C + 1))) ||
1856             (VT == MVT::i64 && C != UINT64_MAX &&
1857              isLegalArithImmed(C + 1ULL))) {
1858           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1859           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1860           RHS = DAG.getConstant(C, dl, VT);
1861         }
1862         break;
1863       }
1864     }
1865   }
1866 
1867   // Comparisons are canonicalized so that the RHS operand is simpler than the
1868   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1869   // can fold some shift+extend operations on the RHS operand, so swap the
1870   // operands if that can be done.
1871   //
1872   // For example:
1873   //    lsl     w13, w11, #1
1874   //    cmp     w13, w12
1875   // can be turned into:
1876   //    cmp     w12, w11, lsl #1
1877   if (!isa<ConstantSDNode>(RHS) ||
1878       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1879     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1880 
1881     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1882       std::swap(LHS, RHS);
1883       CC = ISD::getSetCCSwappedOperands(CC);
1884     }
1885   }
1886 
1887   SDValue Cmp;
1888   AArch64CC::CondCode AArch64CC;
1889   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1890     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1891 
1892     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1893     // For the i8 operand, the largest immediate is 255, so this can be easily
1894     // encoded in the compare instruction. For the i16 operand, however, the
1895     // largest immediate cannot be encoded in the compare.
1896     // Therefore, use a sign extending load and cmn to avoid materializing the
1897     // -1 constant. For example,
1898     // movz w1, #65535
1899     // ldrh w0, [x0, #0]
1900     // cmp w0, w1
1901     // >
1902     // ldrsh w0, [x0, #0]
1903     // cmn w0, #1
1904     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1905     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1906     // ensure both the LHS and RHS are truly zero extended and to make sure the
1907     // transformation is profitable.
1908     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1909         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1910         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1911         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1912       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1913       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1914         SDValue SExt =
1915             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1916                         DAG.getValueType(MVT::i16));
1917         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1918                                                    RHS.getValueType()),
1919                              CC, dl, DAG);
1920         AArch64CC = changeIntCCToAArch64CC(CC);
1921       }
1922     }
1923 
1924     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1925       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1926         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1927           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1928       }
1929     }
1930   }
1931 
1932   if (!Cmp) {
1933     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1934     AArch64CC = changeIntCCToAArch64CC(CC);
1935   }
1936   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1937   return Cmp;
1938 }
1939 
1940 static std::pair<SDValue, SDValue>
1941 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1942   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1943          "Unsupported value type");
1944   SDValue Value, Overflow;
1945   SDLoc DL(Op);
1946   SDValue LHS = Op.getOperand(0);
1947   SDValue RHS = Op.getOperand(1);
1948   unsigned Opc = 0;
1949   switch (Op.getOpcode()) {
1950   default:
1951     llvm_unreachable("Unknown overflow instruction!");
1952   case ISD::SADDO:
1953     Opc = AArch64ISD::ADDS;
1954     CC = AArch64CC::VS;
1955     break;
1956   case ISD::UADDO:
1957     Opc = AArch64ISD::ADDS;
1958     CC = AArch64CC::HS;
1959     break;
1960   case ISD::SSUBO:
1961     Opc = AArch64ISD::SUBS;
1962     CC = AArch64CC::VS;
1963     break;
1964   case ISD::USUBO:
1965     Opc = AArch64ISD::SUBS;
1966     CC = AArch64CC::LO;
1967     break;
1968   // Multiply needs a little bit extra work.
1969   case ISD::SMULO:
1970   case ISD::UMULO: {
1971     CC = AArch64CC::NE;
1972     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1973     if (Op.getValueType() == MVT::i32) {
1974       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1975       // For a 32 bit multiply with overflow check we want the instruction
1976       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1977       // need to generate the following pattern:
1978       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1979       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1980       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1981       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1982       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1983                                 DAG.getConstant(0, DL, MVT::i64));
1984       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1985       // operation. We need to clear out the upper 32 bits, because we used a
1986       // widening multiply that wrote all 64 bits. In the end this should be a
1987       // noop.
1988       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1989       if (IsSigned) {
1990         // The signed overflow check requires more than just a simple check for
1991         // any bit set in the upper 32 bits of the result. These bits could be
1992         // just the sign bits of a negative number. To perform the overflow
1993         // check we have to arithmetic shift right the 32nd bit of the result by
1994         // 31 bits. Then we compare the result to the upper 32 bits.
1995         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1996                                         DAG.getConstant(32, DL, MVT::i64));
1997         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1998         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1999                                         DAG.getConstant(31, DL, MVT::i64));
2000         // It is important that LowerBits is last, otherwise the arithmetic
2001         // shift will not be folded into the compare (SUBS).
2002         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2003         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2004                        .getValue(1);
2005       } else {
2006         // The overflow check for unsigned multiply is easy. We only need to
2007         // check if any of the upper 32 bits are set. This can be done with a
2008         // CMP (shifted register). For that we need to generate the following
2009         // pattern:
2010         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2011         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2012                                         DAG.getConstant(32, DL, MVT::i64));
2013         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2014         Overflow =
2015             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2016                         DAG.getConstant(0, DL, MVT::i64),
2017                         UpperBits).getValue(1);
2018       }
2019       break;
2020     }
2021     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2022     // For the 64 bit multiply
2023     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2024     if (IsSigned) {
2025       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2026       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2027                                       DAG.getConstant(63, DL, MVT::i64));
2028       // It is important that LowerBits is last, otherwise the arithmetic
2029       // shift will not be folded into the compare (SUBS).
2030       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2031       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2032                      .getValue(1);
2033     } else {
2034       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2035       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2036       Overflow =
2037           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2038                       DAG.getConstant(0, DL, MVT::i64),
2039                       UpperBits).getValue(1);
2040     }
2041     break;
2042   }
2043   } // switch (...)
2044 
2045   if (Opc) {
2046     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2047 
2048     // Emit the AArch64 operation with overflow check.
2049     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2050     Overflow = Value.getValue(1);
2051   }
2052   return std::make_pair(Value, Overflow);
2053 }
2054 
2055 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2056                                              RTLIB::Libcall Call) const {
2057   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2058   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
2059 }
2060 
2061 // Returns true if the given Op is the overflow flag result of an overflow
2062 // intrinsic operation.
2063 static bool isOverflowIntrOpRes(SDValue Op) {
2064   unsigned Opc = Op.getOpcode();
2065   return (Op.getResNo() == 1 &&
2066           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2067            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2068 }
2069 
2070 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2071   SDValue Sel = Op.getOperand(0);
2072   SDValue Other = Op.getOperand(1);
2073   SDLoc dl(Sel);
2074 
2075   // If the operand is an overflow checking operation, invert the condition
2076   // code and kill the Not operation. I.e., transform:
2077   // (xor (overflow_op_bool, 1))
2078   //   -->
2079   // (csel 1, 0, invert(cc), overflow_op_bool)
2080   // ... which later gets transformed to just a cset instruction with an
2081   // inverted condition code, rather than a cset + eor sequence.
2082   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2083     // Only lower legal XALUO ops.
2084     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2085       return SDValue();
2086 
2087     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2088     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2089     AArch64CC::CondCode CC;
2090     SDValue Value, Overflow;
2091     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2092     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2093     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2094                        CCVal, Overflow);
2095   }
2096   // If neither operand is a SELECT_CC, give up.
2097   if (Sel.getOpcode() != ISD::SELECT_CC)
2098     std::swap(Sel, Other);
2099   if (Sel.getOpcode() != ISD::SELECT_CC)
2100     return Op;
2101 
2102   // The folding we want to perform is:
2103   // (xor x, (select_cc a, b, cc, 0, -1) )
2104   //   -->
2105   // (csel x, (xor x, -1), cc ...)
2106   //
2107   // The latter will get matched to a CSINV instruction.
2108 
2109   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2110   SDValue LHS = Sel.getOperand(0);
2111   SDValue RHS = Sel.getOperand(1);
2112   SDValue TVal = Sel.getOperand(2);
2113   SDValue FVal = Sel.getOperand(3);
2114 
2115   // FIXME: This could be generalized to non-integer comparisons.
2116   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2117     return Op;
2118 
2119   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2120   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2121 
2122   // The values aren't constants, this isn't the pattern we're looking for.
2123   if (!CFVal || !CTVal)
2124     return Op;
2125 
2126   // We can commute the SELECT_CC by inverting the condition.  This
2127   // might be needed to make this fit into a CSINV pattern.
2128   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2129     std::swap(TVal, FVal);
2130     std::swap(CTVal, CFVal);
2131     CC = ISD::getSetCCInverse(CC, true);
2132   }
2133 
2134   // If the constants line up, perform the transform!
2135   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2136     SDValue CCVal;
2137     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2138 
2139     FVal = Other;
2140     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2141                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2142 
2143     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2144                        CCVal, Cmp);
2145   }
2146 
2147   return Op;
2148 }
2149 
2150 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2151   EVT VT = Op.getValueType();
2152 
2153   // Let legalize expand this if it isn't a legal type yet.
2154   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2155     return SDValue();
2156 
2157   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2158 
2159   unsigned Opc;
2160   bool ExtraOp = false;
2161   switch (Op.getOpcode()) {
2162   default:
2163     llvm_unreachable("Invalid code");
2164   case ISD::ADDC:
2165     Opc = AArch64ISD::ADDS;
2166     break;
2167   case ISD::SUBC:
2168     Opc = AArch64ISD::SUBS;
2169     break;
2170   case ISD::ADDE:
2171     Opc = AArch64ISD::ADCS;
2172     ExtraOp = true;
2173     break;
2174   case ISD::SUBE:
2175     Opc = AArch64ISD::SBCS;
2176     ExtraOp = true;
2177     break;
2178   }
2179 
2180   if (!ExtraOp)
2181     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2182   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2183                      Op.getOperand(2));
2184 }
2185 
2186 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2187   // Let legalize expand this if it isn't a legal type yet.
2188   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2189     return SDValue();
2190 
2191   SDLoc dl(Op);
2192   AArch64CC::CondCode CC;
2193   // The actual operation that sets the overflow or carry flag.
2194   SDValue Value, Overflow;
2195   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2196 
2197   // We use 0 and 1 as false and true values.
2198   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2199   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2200 
2201   // We use an inverted condition, because the conditional select is inverted
2202   // too. This will allow it to be selected to a single instruction:
2203   // CSINC Wd, WZR, WZR, invert(cond).
2204   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2205   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2206                          CCVal, Overflow);
2207 
2208   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2209   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2210 }
2211 
2212 // Prefetch operands are:
2213 // 1: Address to prefetch
2214 // 2: bool isWrite
2215 // 3: int locality (0 = no locality ... 3 = extreme locality)
2216 // 4: bool isDataCache
2217 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2218   SDLoc DL(Op);
2219   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2220   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2221   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2222 
2223   bool IsStream = !Locality;
2224   // When the locality number is set
2225   if (Locality) {
2226     // The front-end should have filtered out the out-of-range values
2227     assert(Locality <= 3 && "Prefetch locality out-of-range");
2228     // The locality degree is the opposite of the cache speed.
2229     // Put the number the other way around.
2230     // The encoding starts at 0 for level 1
2231     Locality = 3 - Locality;
2232   }
2233 
2234   // built the mask value encoding the expected behavior.
2235   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2236                    (!IsData << 3) |     // IsDataCache bit
2237                    (Locality << 1) |    // Cache level bits
2238                    (unsigned)IsStream;  // Stream bit
2239   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2240                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2241 }
2242 
2243 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2244                                               SelectionDAG &DAG) const {
2245   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2246 
2247   RTLIB::Libcall LC;
2248   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2249 
2250   return LowerF128Call(Op, DAG, LC);
2251 }
2252 
2253 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2254                                              SelectionDAG &DAG) const {
2255   if (Op.getOperand(0).getValueType() != MVT::f128) {
2256     // It's legal except when f128 is involved
2257     return Op;
2258   }
2259 
2260   RTLIB::Libcall LC;
2261   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2262 
2263   // FP_ROUND node has a second operand indicating whether it is known to be
2264   // precise. That doesn't take part in the LibCall so we can't directly use
2265   // LowerF128Call.
2266   SDValue SrcVal = Op.getOperand(0);
2267   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2268                      SDLoc(Op)).first;
2269 }
2270 
2271 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2272   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2273   // Any additional optimization in this function should be recorded
2274   // in the cost tables.
2275   EVT InVT = Op.getOperand(0).getValueType();
2276   EVT VT = Op.getValueType();
2277   unsigned NumElts = InVT.getVectorNumElements();
2278 
2279   // f16 vectors are promoted to f32 before a conversion.
2280   if (InVT.getVectorElementType() == MVT::f16) {
2281     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2282     SDLoc dl(Op);
2283     return DAG.getNode(
2284         Op.getOpcode(), dl, Op.getValueType(),
2285         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2286   }
2287 
2288   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2289     SDLoc dl(Op);
2290     SDValue Cv =
2291         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2292                     Op.getOperand(0));
2293     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2294   }
2295 
2296   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2297     SDLoc dl(Op);
2298     MVT ExtVT =
2299         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2300                          VT.getVectorNumElements());
2301     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2302     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2303   }
2304 
2305   // Type changing conversions are illegal.
2306   return Op;
2307 }
2308 
2309 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2310                                               SelectionDAG &DAG) const {
2311   if (Op.getOperand(0).getValueType().isVector())
2312     return LowerVectorFP_TO_INT(Op, DAG);
2313 
2314   // f16 conversions are promoted to f32 when full fp16 is not supported.
2315   if (Op.getOperand(0).getValueType() == MVT::f16 &&
2316       !Subtarget->hasFullFP16()) {
2317     SDLoc dl(Op);
2318     return DAG.getNode(
2319         Op.getOpcode(), dl, Op.getValueType(),
2320         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2321   }
2322 
2323   if (Op.getOperand(0).getValueType() != MVT::f128) {
2324     // It's legal except when f128 is involved
2325     return Op;
2326   }
2327 
2328   RTLIB::Libcall LC;
2329   if (Op.getOpcode() == ISD::FP_TO_SINT)
2330     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2331   else
2332     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2333 
2334   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2335   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2336 }
2337 
2338 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2339   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2340   // Any additional optimization in this function should be recorded
2341   // in the cost tables.
2342   EVT VT = Op.getValueType();
2343   SDLoc dl(Op);
2344   SDValue In = Op.getOperand(0);
2345   EVT InVT = In.getValueType();
2346 
2347   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2348     MVT CastVT =
2349         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2350                          InVT.getVectorNumElements());
2351     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2352     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2353   }
2354 
2355   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2356     unsigned CastOpc =
2357         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2358     EVT CastVT = VT.changeVectorElementTypeToInteger();
2359     In = DAG.getNode(CastOpc, dl, CastVT, In);
2360     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2361   }
2362 
2363   return Op;
2364 }
2365 
2366 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2367                                             SelectionDAG &DAG) const {
2368   if (Op.getValueType().isVector())
2369     return LowerVectorINT_TO_FP(Op, DAG);
2370 
2371   // f16 conversions are promoted to f32 when full fp16 is not supported.
2372   if (Op.getValueType() == MVT::f16 &&
2373       !Subtarget->hasFullFP16()) {
2374     SDLoc dl(Op);
2375     return DAG.getNode(
2376         ISD::FP_ROUND, dl, MVT::f16,
2377         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2378         DAG.getIntPtrConstant(0, dl));
2379   }
2380 
2381   // i128 conversions are libcalls.
2382   if (Op.getOperand(0).getValueType() == MVT::i128)
2383     return SDValue();
2384 
2385   // Other conversions are legal, unless it's to the completely software-based
2386   // fp128.
2387   if (Op.getValueType() != MVT::f128)
2388     return Op;
2389 
2390   RTLIB::Libcall LC;
2391   if (Op.getOpcode() == ISD::SINT_TO_FP)
2392     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2393   else
2394     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2395 
2396   return LowerF128Call(Op, DAG, LC);
2397 }
2398 
2399 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2400                                             SelectionDAG &DAG) const {
2401   // For iOS, we want to call an alternative entry point: __sincos_stret,
2402   // which returns the values in two S / D registers.
2403   SDLoc dl(Op);
2404   SDValue Arg = Op.getOperand(0);
2405   EVT ArgVT = Arg.getValueType();
2406   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2407 
2408   ArgListTy Args;
2409   ArgListEntry Entry;
2410 
2411   Entry.Node = Arg;
2412   Entry.Ty = ArgTy;
2413   Entry.IsSExt = false;
2414   Entry.IsZExt = false;
2415   Args.push_back(Entry);
2416 
2417   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2418                                         : RTLIB::SINCOS_STRET_F32;
2419   const char *LibcallName = getLibcallName(LC);
2420   SDValue Callee =
2421       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2422 
2423   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2424   TargetLowering::CallLoweringInfo CLI(DAG);
2425   CLI.setDebugLoc(dl)
2426       .setChain(DAG.getEntryNode())
2427       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2428 
2429   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2430   return CallResult.first;
2431 }
2432 
2433 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2434   if (Op.getValueType() != MVT::f16)
2435     return SDValue();
2436 
2437   assert(Op.getOperand(0).getValueType() == MVT::i16);
2438   SDLoc DL(Op);
2439 
2440   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2441   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2442   return SDValue(
2443       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2444                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2445       0);
2446 }
2447 
2448 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2449   if (OrigVT.getSizeInBits() >= 64)
2450     return OrigVT;
2451 
2452   assert(OrigVT.isSimple() && "Expecting a simple value type");
2453 
2454   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2455   switch (OrigSimpleTy) {
2456   default: llvm_unreachable("Unexpected Vector Type");
2457   case MVT::v2i8:
2458   case MVT::v2i16:
2459      return MVT::v2i32;
2460   case MVT::v4i8:
2461     return  MVT::v4i16;
2462   }
2463 }
2464 
2465 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2466                                                  const EVT &OrigTy,
2467                                                  const EVT &ExtTy,
2468                                                  unsigned ExtOpcode) {
2469   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2470   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2471   // 64-bits we need to insert a new extension so that it will be 64-bits.
2472   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2473   if (OrigTy.getSizeInBits() >= 64)
2474     return N;
2475 
2476   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2477   EVT NewVT = getExtensionTo64Bits(OrigTy);
2478 
2479   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2480 }
2481 
2482 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2483                                    bool isSigned) {
2484   EVT VT = N->getValueType(0);
2485 
2486   if (N->getOpcode() != ISD::BUILD_VECTOR)
2487     return false;
2488 
2489   for (const SDValue &Elt : N->op_values()) {
2490     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2491       unsigned EltSize = VT.getScalarSizeInBits();
2492       unsigned HalfSize = EltSize / 2;
2493       if (isSigned) {
2494         if (!isIntN(HalfSize, C->getSExtValue()))
2495           return false;
2496       } else {
2497         if (!isUIntN(HalfSize, C->getZExtValue()))
2498           return false;
2499       }
2500       continue;
2501     }
2502     return false;
2503   }
2504 
2505   return true;
2506 }
2507 
2508 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2509   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2510     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2511                                              N->getOperand(0)->getValueType(0),
2512                                              N->getValueType(0),
2513                                              N->getOpcode());
2514 
2515   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2516   EVT VT = N->getValueType(0);
2517   SDLoc dl(N);
2518   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2519   unsigned NumElts = VT.getVectorNumElements();
2520   MVT TruncVT = MVT::getIntegerVT(EltSize);
2521   SmallVector<SDValue, 8> Ops;
2522   for (unsigned i = 0; i != NumElts; ++i) {
2523     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2524     const APInt &CInt = C->getAPIntValue();
2525     // Element types smaller than 32 bits are not legal, so use i32 elements.
2526     // The values are implicitly truncated so sext vs. zext doesn't matter.
2527     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2528   }
2529   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2530 }
2531 
2532 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2533   return N->getOpcode() == ISD::SIGN_EXTEND ||
2534          isExtendedBUILD_VECTOR(N, DAG, true);
2535 }
2536 
2537 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2538   return N->getOpcode() == ISD::ZERO_EXTEND ||
2539          isExtendedBUILD_VECTOR(N, DAG, false);
2540 }
2541 
2542 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2543   unsigned Opcode = N->getOpcode();
2544   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2545     SDNode *N0 = N->getOperand(0).getNode();
2546     SDNode *N1 = N->getOperand(1).getNode();
2547     return N0->hasOneUse() && N1->hasOneUse() &&
2548       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2549   }
2550   return false;
2551 }
2552 
2553 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2554   unsigned Opcode = N->getOpcode();
2555   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2556     SDNode *N0 = N->getOperand(0).getNode();
2557     SDNode *N1 = N->getOperand(1).getNode();
2558     return N0->hasOneUse() && N1->hasOneUse() &&
2559       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2560   }
2561   return false;
2562 }
2563 
2564 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2565                                                 SelectionDAG &DAG) const {
2566   // The rounding mode is in bits 23:22 of the FPSCR.
2567   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2568   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2569   // so that the shift + and get folded into a bitfield extract.
2570   SDLoc dl(Op);
2571 
2572   SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2573                                 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2574                                                 MVT::i64));
2575   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2576   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2577                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2578   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2579                               DAG.getConstant(22, dl, MVT::i32));
2580   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2581                      DAG.getConstant(3, dl, MVT::i32));
2582 }
2583 
2584 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2585   // Multiplications are only custom-lowered for 128-bit vectors so that
2586   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2587   EVT VT = Op.getValueType();
2588   assert(VT.is128BitVector() && VT.isInteger() &&
2589          "unexpected type for custom-lowering ISD::MUL");
2590   SDNode *N0 = Op.getOperand(0).getNode();
2591   SDNode *N1 = Op.getOperand(1).getNode();
2592   unsigned NewOpc = 0;
2593   bool isMLA = false;
2594   bool isN0SExt = isSignExtended(N0, DAG);
2595   bool isN1SExt = isSignExtended(N1, DAG);
2596   if (isN0SExt && isN1SExt)
2597     NewOpc = AArch64ISD::SMULL;
2598   else {
2599     bool isN0ZExt = isZeroExtended(N0, DAG);
2600     bool isN1ZExt = isZeroExtended(N1, DAG);
2601     if (isN0ZExt && isN1ZExt)
2602       NewOpc = AArch64ISD::UMULL;
2603     else if (isN1SExt || isN1ZExt) {
2604       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2605       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2606       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2607         NewOpc = AArch64ISD::SMULL;
2608         isMLA = true;
2609       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2610         NewOpc =  AArch64ISD::UMULL;
2611         isMLA = true;
2612       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2613         std::swap(N0, N1);
2614         NewOpc =  AArch64ISD::UMULL;
2615         isMLA = true;
2616       }
2617     }
2618 
2619     if (!NewOpc) {
2620       if (VT == MVT::v2i64)
2621         // Fall through to expand this.  It is not legal.
2622         return SDValue();
2623       else
2624         // Other vector multiplications are legal.
2625         return Op;
2626     }
2627   }
2628 
2629   // Legalize to a S/UMULL instruction
2630   SDLoc DL(Op);
2631   SDValue Op0;
2632   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2633   if (!isMLA) {
2634     Op0 = skipExtensionForVectorMULL(N0, DAG);
2635     assert(Op0.getValueType().is64BitVector() &&
2636            Op1.getValueType().is64BitVector() &&
2637            "unexpected types for extended operands to VMULL");
2638     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2639   }
2640   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2641   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2642   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2643   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2644   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2645   EVT Op1VT = Op1.getValueType();
2646   return DAG.getNode(N0->getOpcode(), DL, VT,
2647                      DAG.getNode(NewOpc, DL, VT,
2648                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2649                      DAG.getNode(NewOpc, DL, VT,
2650                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2651 }
2652 
2653 // Lower vector multiply high (ISD::MULHS and ISD::MULHU).
2654 static SDValue LowerMULH(SDValue Op, SelectionDAG &DAG) {
2655   // Multiplications are only custom-lowered for 128-bit vectors so that
2656   // {S,U}MULL{2} can be detected.  Otherwise v2i64 multiplications are not
2657   // legal.
2658   EVT VT = Op.getValueType();
2659   assert(VT.is128BitVector() && VT.isInteger() &&
2660          "unexpected type for custom-lowering ISD::MULH{U,S}");
2661 
2662   SDValue V0 = Op.getOperand(0);
2663   SDValue V1 = Op.getOperand(1);
2664 
2665   SDLoc DL(Op);
2666 
2667   EVT ExtractVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
2668 
2669   // We turn (V0 mulhs/mulhu V1) to:
2670   //
2671   // (uzp2 (smull (extract_subvector (ExtractVT V128:V0, (i64 0)),
2672   //              (extract_subvector (ExtractVT V128:V1, (i64 0))))),
2673   //       (smull (extract_subvector (ExtractVT V128:V0, (i64 VMull2Idx)),
2674   //              (extract_subvector (ExtractVT V128:V2, (i64 VMull2Idx))))))
2675   //
2676   // Where ExtractVT is a subvector with half number of elements, and
2677   // VMullIdx2 is the index of the middle element (the high part).
2678   //
2679   // The vector hight part extract and multiply will be matched against
2680   // {S,U}MULL{v16i8_v8i16,v8i16_v4i32,v4i32_v2i64} which in turn will
2681   // issue a {s}mull2 instruction.
2682   //
2683   // This basically multiply the lower subvector with '{s,u}mull', the high
2684   // subvector with '{s,u}mull2', and shuffle both results high part in
2685   // resulting vector.
2686   unsigned Mull2VectorIdx = VT.getVectorNumElements () / 2;
2687   SDValue VMullIdx = DAG.getConstant(0, DL, MVT::i64);
2688   SDValue VMull2Idx = DAG.getConstant(Mull2VectorIdx, DL, MVT::i64);
2689 
2690   SDValue VMullV0 =
2691     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMullIdx);
2692   SDValue VMullV1 =
2693     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMullIdx);
2694 
2695   SDValue VMull2V0 =
2696     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMull2Idx);
2697   SDValue VMull2V1 =
2698     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMull2Idx);
2699 
2700   unsigned MullOpc = Op.getOpcode() == ISD::MULHS ? AArch64ISD::SMULL
2701                                                   : AArch64ISD::UMULL;
2702 
2703   EVT MullVT = ExtractVT.widenIntegerVectorElementType(*DAG.getContext());
2704   SDValue Mull  = DAG.getNode(MullOpc, DL, MullVT, VMullV0, VMullV1);
2705   SDValue Mull2 = DAG.getNode(MullOpc, DL, MullVT, VMull2V0, VMull2V1);
2706 
2707   Mull  = DAG.getNode(ISD::BITCAST, DL, VT, Mull);
2708   Mull2 = DAG.getNode(ISD::BITCAST, DL, VT, Mull2);
2709 
2710   return DAG.getNode(AArch64ISD::UZP2, DL, VT, Mull, Mull2);
2711 }
2712 
2713 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2714                                                      SelectionDAG &DAG) const {
2715   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2716   SDLoc dl(Op);
2717   switch (IntNo) {
2718   default: return SDValue();    // Don't custom lower most intrinsics.
2719   case Intrinsic::thread_pointer: {
2720     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2722   }
2723   case Intrinsic::aarch64_neon_abs:
2724     return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2725                        Op.getOperand(1));
2726   case Intrinsic::aarch64_neon_smax:
2727     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2728                        Op.getOperand(1), Op.getOperand(2));
2729   case Intrinsic::aarch64_neon_umax:
2730     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2731                        Op.getOperand(1), Op.getOperand(2));
2732   case Intrinsic::aarch64_neon_smin:
2733     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2734                        Op.getOperand(1), Op.getOperand(2));
2735   case Intrinsic::aarch64_neon_umin:
2736     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2737                        Op.getOperand(1), Op.getOperand(2));
2738   }
2739 }
2740 
2741 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2742 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2743                                         EVT VT, EVT MemVT,
2744                                         SelectionDAG &DAG) {
2745   assert(VT.isVector() && "VT should be a vector type");
2746   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2747 
2748   SDValue Value = ST->getValue();
2749 
2750   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2751   // the word lane which represent the v4i8 subvector.  It optimizes the store
2752   // to:
2753   //
2754   //   xtn  v0.8b, v0.8h
2755   //   str  s0, [x0]
2756 
2757   SDValue Undef = DAG.getUNDEF(MVT::i16);
2758   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2759                                         {Undef, Undef, Undef, Undef});
2760 
2761   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2762                                  Value, UndefVec);
2763   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2764 
2765   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2766   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2767                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
2768 
2769   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2770                       ST->getBasePtr(), ST->getMemOperand());
2771 }
2772 
2773 // Custom lowering for any store, vector or scalar and/or default or with
2774 // a truncate operations.  Currently only custom lower truncate operation
2775 // from vector v4i16 to v4i8.
2776 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2777                                           SelectionDAG &DAG) const {
2778   SDLoc Dl(Op);
2779   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2780   assert (StoreNode && "Can only custom lower store nodes");
2781 
2782   SDValue Value = StoreNode->getValue();
2783 
2784   EVT VT = Value.getValueType();
2785   EVT MemVT = StoreNode->getMemoryVT();
2786 
2787   assert (VT.isVector() && "Can only custom lower vector store types");
2788 
2789   unsigned AS = StoreNode->getAddressSpace();
2790   unsigned Align = StoreNode->getAlignment();
2791   if (Align < MemVT.getStoreSize() &&
2792       !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2793     return scalarizeVectorStore(StoreNode, DAG);
2794   }
2795 
2796   if (StoreNode->isTruncatingStore()) {
2797     return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2798   }
2799 
2800   return SDValue();
2801 }
2802 
2803 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2804                                               SelectionDAG &DAG) const {
2805   LLVM_DEBUG(dbgs() << "Custom lowering: ");
2806   LLVM_DEBUG(Op.dump());
2807 
2808   switch (Op.getOpcode()) {
2809   default:
2810     llvm_unreachable("unimplemented operand");
2811     return SDValue();
2812   case ISD::BITCAST:
2813     return LowerBITCAST(Op, DAG);
2814   case ISD::GlobalAddress:
2815     return LowerGlobalAddress(Op, DAG);
2816   case ISD::GlobalTLSAddress:
2817     return LowerGlobalTLSAddress(Op, DAG);
2818   case ISD::SETCC:
2819     return LowerSETCC(Op, DAG);
2820   case ISD::BR_CC:
2821     return LowerBR_CC(Op, DAG);
2822   case ISD::SELECT:
2823     return LowerSELECT(Op, DAG);
2824   case ISD::SELECT_CC:
2825     return LowerSELECT_CC(Op, DAG);
2826   case ISD::JumpTable:
2827     return LowerJumpTable(Op, DAG);
2828   case ISD::BR_JT:
2829     return LowerBR_JT(Op, DAG);
2830   case ISD::ConstantPool:
2831     return LowerConstantPool(Op, DAG);
2832   case ISD::BlockAddress:
2833     return LowerBlockAddress(Op, DAG);
2834   case ISD::VASTART:
2835     return LowerVASTART(Op, DAG);
2836   case ISD::VACOPY:
2837     return LowerVACOPY(Op, DAG);
2838   case ISD::VAARG:
2839     return LowerVAARG(Op, DAG);
2840   case ISD::ADDC:
2841   case ISD::ADDE:
2842   case ISD::SUBC:
2843   case ISD::SUBE:
2844     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2845   case ISD::SADDO:
2846   case ISD::UADDO:
2847   case ISD::SSUBO:
2848   case ISD::USUBO:
2849   case ISD::SMULO:
2850   case ISD::UMULO:
2851     return LowerXALUO(Op, DAG);
2852   case ISD::FADD:
2853     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2854   case ISD::FSUB:
2855     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2856   case ISD::FMUL:
2857     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2858   case ISD::FDIV:
2859     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2860   case ISD::FP_ROUND:
2861     return LowerFP_ROUND(Op, DAG);
2862   case ISD::FP_EXTEND:
2863     return LowerFP_EXTEND(Op, DAG);
2864   case ISD::FRAMEADDR:
2865     return LowerFRAMEADDR(Op, DAG);
2866   case ISD::RETURNADDR:
2867     return LowerRETURNADDR(Op, DAG);
2868   case ISD::INSERT_VECTOR_ELT:
2869     return LowerINSERT_VECTOR_ELT(Op, DAG);
2870   case ISD::EXTRACT_VECTOR_ELT:
2871     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2872   case ISD::BUILD_VECTOR:
2873     return LowerBUILD_VECTOR(Op, DAG);
2874   case ISD::VECTOR_SHUFFLE:
2875     return LowerVECTOR_SHUFFLE(Op, DAG);
2876   case ISD::EXTRACT_SUBVECTOR:
2877     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2878   case ISD::SRA:
2879   case ISD::SRL:
2880   case ISD::SHL:
2881     return LowerVectorSRA_SRL_SHL(Op, DAG);
2882   case ISD::SHL_PARTS:
2883     return LowerShiftLeftParts(Op, DAG);
2884   case ISD::SRL_PARTS:
2885   case ISD::SRA_PARTS:
2886     return LowerShiftRightParts(Op, DAG);
2887   case ISD::CTPOP:
2888     return LowerCTPOP(Op, DAG);
2889   case ISD::FCOPYSIGN:
2890     return LowerFCOPYSIGN(Op, DAG);
2891   case ISD::AND:
2892     return LowerVectorAND(Op, DAG);
2893   case ISD::OR:
2894     return LowerVectorOR(Op, DAG);
2895   case ISD::XOR:
2896     return LowerXOR(Op, DAG);
2897   case ISD::PREFETCH:
2898     return LowerPREFETCH(Op, DAG);
2899   case ISD::SINT_TO_FP:
2900   case ISD::UINT_TO_FP:
2901     return LowerINT_TO_FP(Op, DAG);
2902   case ISD::FP_TO_SINT:
2903   case ISD::FP_TO_UINT:
2904     return LowerFP_TO_INT(Op, DAG);
2905   case ISD::FSINCOS:
2906     return LowerFSINCOS(Op, DAG);
2907   case ISD::FLT_ROUNDS_:
2908     return LowerFLT_ROUNDS_(Op, DAG);
2909   case ISD::MUL:
2910     return LowerMUL(Op, DAG);
2911   case ISD::MULHS:
2912   case ISD::MULHU:
2913     return LowerMULH(Op, DAG);
2914   case ISD::INTRINSIC_WO_CHAIN:
2915     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2916   case ISD::STORE:
2917     return LowerSTORE(Op, DAG);
2918   case ISD::VECREDUCE_ADD:
2919   case ISD::VECREDUCE_SMAX:
2920   case ISD::VECREDUCE_SMIN:
2921   case ISD::VECREDUCE_UMAX:
2922   case ISD::VECREDUCE_UMIN:
2923   case ISD::VECREDUCE_FMAX:
2924   case ISD::VECREDUCE_FMIN:
2925     return LowerVECREDUCE(Op, DAG);
2926   case ISD::ATOMIC_LOAD_SUB:
2927     return LowerATOMIC_LOAD_SUB(Op, DAG);
2928   case ISD::ATOMIC_LOAD_AND:
2929     return LowerATOMIC_LOAD_AND(Op, DAG);
2930   case ISD::DYNAMIC_STACKALLOC:
2931     return LowerDYNAMIC_STACKALLOC(Op, DAG);
2932   }
2933 }
2934 
2935 //===----------------------------------------------------------------------===//
2936 //                      Calling Convention Implementation
2937 //===----------------------------------------------------------------------===//
2938 
2939 #include "AArch64GenCallingConv.inc"
2940 
2941 /// Selects the correct CCAssignFn for a given CallingConvention value.
2942 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2943                                                      bool IsVarArg) const {
2944   switch (CC) {
2945   default:
2946     report_fatal_error("Unsupported calling convention.");
2947   case CallingConv::WebKit_JS:
2948     return CC_AArch64_WebKit_JS;
2949   case CallingConv::GHC:
2950     return CC_AArch64_GHC;
2951   case CallingConv::C:
2952   case CallingConv::Fast:
2953   case CallingConv::PreserveMost:
2954   case CallingConv::CXX_FAST_TLS:
2955   case CallingConv::Swift:
2956     if (Subtarget->isTargetWindows() && IsVarArg)
2957       return CC_AArch64_Win64_VarArg;
2958     if (!Subtarget->isTargetDarwin())
2959       return CC_AArch64_AAPCS;
2960     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2961   case CallingConv::Win64:
2962     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2963   case CallingConv::AArch64_VectorCall:
2964     return CC_AArch64_AAPCS;
2965   }
2966 }
2967 
2968 CCAssignFn *
2969 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2970   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2971                                       : RetCC_AArch64_AAPCS;
2972 }
2973 
2974 SDValue AArch64TargetLowering::LowerFormalArguments(
2975     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2976     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2977     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2978   MachineFunction &MF = DAG.getMachineFunction();
2979   MachineFrameInfo &MFI = MF.getFrameInfo();
2980   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2981 
2982   // Assign locations to all of the incoming arguments.
2983   SmallVector<CCValAssign, 16> ArgLocs;
2984   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2985                  *DAG.getContext());
2986 
2987   // At this point, Ins[].VT may already be promoted to i32. To correctly
2988   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2989   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2990   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2991   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2992   // LocVT.
2993   unsigned NumArgs = Ins.size();
2994   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
2995   unsigned CurArgIdx = 0;
2996   for (unsigned i = 0; i != NumArgs; ++i) {
2997     MVT ValVT = Ins[i].VT;
2998     if (Ins[i].isOrigArg()) {
2999       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3000       CurArgIdx = Ins[i].getOrigArgIndex();
3001 
3002       // Get type of the original argument.
3003       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3004                                   /*AllowUnknown*/ true);
3005       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3006       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3007       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3008         ValVT = MVT::i8;
3009       else if (ActualMVT == MVT::i16)
3010         ValVT = MVT::i16;
3011     }
3012     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3013     bool Res =
3014         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3015     assert(!Res && "Call operand has unhandled type");
3016     (void)Res;
3017   }
3018   assert(ArgLocs.size() == Ins.size());
3019   SmallVector<SDValue, 16> ArgValues;
3020   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3021     CCValAssign &VA = ArgLocs[i];
3022 
3023     if (Ins[i].Flags.isByVal()) {
3024       // Byval is used for HFAs in the PCS, but the system should work in a
3025       // non-compliant manner for larger structs.
3026       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3027       int Size = Ins[i].Flags.getByValSize();
3028       unsigned NumRegs = (Size + 7) / 8;
3029 
3030       // FIXME: This works on big-endian for composite byvals, which are the common
3031       // case. It should also work for fundamental types too.
3032       unsigned FrameIdx =
3033         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3034       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3035       InVals.push_back(FrameIdxN);
3036 
3037       continue;
3038     }
3039 
3040     if (VA.isRegLoc()) {
3041       // Arguments stored in registers.
3042       EVT RegVT = VA.getLocVT();
3043 
3044       SDValue ArgValue;
3045       const TargetRegisterClass *RC;
3046 
3047       if (RegVT == MVT::i32)
3048         RC = &AArch64::GPR32RegClass;
3049       else if (RegVT == MVT::i64)
3050         RC = &AArch64::GPR64RegClass;
3051       else if (RegVT == MVT::f16)
3052         RC = &AArch64::FPR16RegClass;
3053       else if (RegVT == MVT::f32)
3054         RC = &AArch64::FPR32RegClass;
3055       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3056         RC = &AArch64::FPR64RegClass;
3057       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3058         RC = &AArch64::FPR128RegClass;
3059       else
3060         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3061 
3062       // Transform the arguments in physical registers into virtual ones.
3063       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3064       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3065 
3066       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3067       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3068       // truncate to the right size.
3069       switch (VA.getLocInfo()) {
3070       default:
3071         llvm_unreachable("Unknown loc info!");
3072       case CCValAssign::Full:
3073         break;
3074       case CCValAssign::BCvt:
3075         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3076         break;
3077       case CCValAssign::AExt:
3078       case CCValAssign::SExt:
3079       case CCValAssign::ZExt:
3080         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3081         // nodes after our lowering.
3082         assert(RegVT == Ins[i].VT && "incorrect register location selected");
3083         break;
3084       }
3085 
3086       InVals.push_back(ArgValue);
3087 
3088     } else { // VA.isRegLoc()
3089       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3090       unsigned ArgOffset = VA.getLocMemOffset();
3091       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3092 
3093       uint32_t BEAlign = 0;
3094       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3095           !Ins[i].Flags.isInConsecutiveRegs())
3096         BEAlign = 8 - ArgSize;
3097 
3098       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3099 
3100       // Create load nodes to retrieve arguments from the stack.
3101       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3102       SDValue ArgValue;
3103 
3104       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3105       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3106       MVT MemVT = VA.getValVT();
3107 
3108       switch (VA.getLocInfo()) {
3109       default:
3110         break;
3111       case CCValAssign::BCvt:
3112         MemVT = VA.getLocVT();
3113         break;
3114       case CCValAssign::SExt:
3115         ExtType = ISD::SEXTLOAD;
3116         break;
3117       case CCValAssign::ZExt:
3118         ExtType = ISD::ZEXTLOAD;
3119         break;
3120       case CCValAssign::AExt:
3121         ExtType = ISD::EXTLOAD;
3122         break;
3123       }
3124 
3125       ArgValue = DAG.getExtLoad(
3126           ExtType, DL, VA.getLocVT(), Chain, FIN,
3127           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3128           MemVT);
3129 
3130       InVals.push_back(ArgValue);
3131     }
3132   }
3133 
3134   // varargs
3135   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3136   if (isVarArg) {
3137     if (!Subtarget->isTargetDarwin() || IsWin64) {
3138       // The AAPCS variadic function ABI is identical to the non-variadic
3139       // one. As a result there may be more arguments in registers and we should
3140       // save them for future reference.
3141       // Win64 variadic functions also pass arguments in registers, but all float
3142       // arguments are passed in integer registers.
3143       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3144     }
3145 
3146     // This will point to the next argument passed via stack.
3147     unsigned StackOffset = CCInfo.getNextStackOffset();
3148     // We currently pass all varargs at 8-byte alignment.
3149     StackOffset = ((StackOffset + 7) & ~7);
3150     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3151   }
3152 
3153   unsigned StackArgSize = CCInfo.getNextStackOffset();
3154   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3155   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3156     // This is a non-standard ABI so by fiat I say we're allowed to make full
3157     // use of the stack area to be popped, which must be aligned to 16 bytes in
3158     // any case:
3159     StackArgSize = alignTo(StackArgSize, 16);
3160 
3161     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3162     // a multiple of 16.
3163     FuncInfo->setArgumentStackToRestore(StackArgSize);
3164 
3165     // This realignment carries over to the available bytes below. Our own
3166     // callers will guarantee the space is free by giving an aligned value to
3167     // CALLSEQ_START.
3168   }
3169   // Even if we're not expected to free up the space, it's useful to know how
3170   // much is there while considering tail calls (because we can reuse it).
3171   FuncInfo->setBytesInStackArgArea(StackArgSize);
3172 
3173   if (Subtarget->hasCustomCallingConv())
3174     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3175 
3176   return Chain;
3177 }
3178 
3179 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3180                                                 SelectionDAG &DAG,
3181                                                 const SDLoc &DL,
3182                                                 SDValue &Chain) const {
3183   MachineFunction &MF = DAG.getMachineFunction();
3184   MachineFrameInfo &MFI = MF.getFrameInfo();
3185   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3186   auto PtrVT = getPointerTy(DAG.getDataLayout());
3187   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3188 
3189   SmallVector<SDValue, 8> MemOps;
3190 
3191   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3192                                           AArch64::X3, AArch64::X4, AArch64::X5,
3193                                           AArch64::X6, AArch64::X7 };
3194   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3195   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3196 
3197   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3198   int GPRIdx = 0;
3199   if (GPRSaveSize != 0) {
3200     if (IsWin64) {
3201       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3202       if (GPRSaveSize & 15)
3203         // The extra size here, if triggered, will always be 8.
3204         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3205     } else
3206       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3207 
3208     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3209 
3210     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3211       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3212       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3213       SDValue Store = DAG.getStore(
3214           Val.getValue(1), DL, Val, FIN,
3215           IsWin64
3216               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3217                                                   GPRIdx,
3218                                                   (i - FirstVariadicGPR) * 8)
3219               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3220       MemOps.push_back(Store);
3221       FIN =
3222           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3223     }
3224   }
3225   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3226   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3227 
3228   if (Subtarget->hasFPARMv8() && !IsWin64) {
3229     static const MCPhysReg FPRArgRegs[] = {
3230         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3231         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3232     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3233     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3234 
3235     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3236     int FPRIdx = 0;
3237     if (FPRSaveSize != 0) {
3238       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3239 
3240       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3241 
3242       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3243         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3244         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3245 
3246         SDValue Store = DAG.getStore(
3247             Val.getValue(1), DL, Val, FIN,
3248             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3249         MemOps.push_back(Store);
3250         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3251                           DAG.getConstant(16, DL, PtrVT));
3252       }
3253     }
3254     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3255     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3256   }
3257 
3258   if (!MemOps.empty()) {
3259     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3260   }
3261 }
3262 
3263 /// LowerCallResult - Lower the result values of a call into the
3264 /// appropriate copies out of appropriate physical registers.
3265 SDValue AArch64TargetLowering::LowerCallResult(
3266     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3267     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3268     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3269     SDValue ThisVal) const {
3270   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3271                           ? RetCC_AArch64_WebKit_JS
3272                           : RetCC_AArch64_AAPCS;
3273   // Assign locations to each value returned by this call.
3274   SmallVector<CCValAssign, 16> RVLocs;
3275   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3276                  *DAG.getContext());
3277   CCInfo.AnalyzeCallResult(Ins, RetCC);
3278 
3279   // Copy all of the result registers out of their specified physreg.
3280   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3281     CCValAssign VA = RVLocs[i];
3282 
3283     // Pass 'this' value directly from the argument to return value, to avoid
3284     // reg unit interference
3285     if (i == 0 && isThisReturn) {
3286       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3287              "unexpected return calling convention register assignment");
3288       InVals.push_back(ThisVal);
3289       continue;
3290     }
3291 
3292     SDValue Val =
3293         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3294     Chain = Val.getValue(1);
3295     InFlag = Val.getValue(2);
3296 
3297     switch (VA.getLocInfo()) {
3298     default:
3299       llvm_unreachable("Unknown loc info!");
3300     case CCValAssign::Full:
3301       break;
3302     case CCValAssign::BCvt:
3303       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3304       break;
3305     }
3306 
3307     InVals.push_back(Val);
3308   }
3309 
3310   return Chain;
3311 }
3312 
3313 /// Return true if the calling convention is one that we can guarantee TCO for.
3314 static bool canGuaranteeTCO(CallingConv::ID CC) {
3315   return CC == CallingConv::Fast;
3316 }
3317 
3318 /// Return true if we might ever do TCO for calls with this calling convention.
3319 static bool mayTailCallThisCC(CallingConv::ID CC) {
3320   switch (CC) {
3321   case CallingConv::C:
3322   case CallingConv::PreserveMost:
3323   case CallingConv::Swift:
3324     return true;
3325   default:
3326     return canGuaranteeTCO(CC);
3327   }
3328 }
3329 
3330 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3331     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3332     const SmallVectorImpl<ISD::OutputArg> &Outs,
3333     const SmallVectorImpl<SDValue> &OutVals,
3334     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3335   if (!mayTailCallThisCC(CalleeCC))
3336     return false;
3337 
3338   MachineFunction &MF = DAG.getMachineFunction();
3339   const Function &CallerF = MF.getFunction();
3340   CallingConv::ID CallerCC = CallerF.getCallingConv();
3341   bool CCMatch = CallerCC == CalleeCC;
3342 
3343   // Byval parameters hand the function a pointer directly into the stack area
3344   // we want to reuse during a tail call. Working around this *is* possible (see
3345   // X86) but less efficient and uglier in LowerCall.
3346   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3347                                     e = CallerF.arg_end();
3348        i != e; ++i)
3349     if (i->hasByValAttr())
3350       return false;
3351 
3352   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3353     return canGuaranteeTCO(CalleeCC) && CCMatch;
3354 
3355   // Externally-defined functions with weak linkage should not be
3356   // tail-called on AArch64 when the OS does not support dynamic
3357   // pre-emption of symbols, as the AAELF spec requires normal calls
3358   // to undefined weak functions to be replaced with a NOP or jump to the
3359   // next instruction. The behaviour of branch instructions in this
3360   // situation (as used for tail calls) is implementation-defined, so we
3361   // cannot rely on the linker replacing the tail call with a return.
3362   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3363     const GlobalValue *GV = G->getGlobal();
3364     const Triple &TT = getTargetMachine().getTargetTriple();
3365     if (GV->hasExternalWeakLinkage() &&
3366         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3367       return false;
3368   }
3369 
3370   // Now we search for cases where we can use a tail call without changing the
3371   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3372   // concept.
3373 
3374   // I want anyone implementing a new calling convention to think long and hard
3375   // about this assert.
3376   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3377          "Unexpected variadic calling convention");
3378 
3379   LLVMContext &C = *DAG.getContext();
3380   if (isVarArg && !Outs.empty()) {
3381     // At least two cases here: if caller is fastcc then we can't have any
3382     // memory arguments (we'd be expected to clean up the stack afterwards). If
3383     // caller is C then we could potentially use its argument area.
3384 
3385     // FIXME: for now we take the most conservative of these in both cases:
3386     // disallow all variadic memory operands.
3387     SmallVector<CCValAssign, 16> ArgLocs;
3388     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3389 
3390     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3391     for (const CCValAssign &ArgLoc : ArgLocs)
3392       if (!ArgLoc.isRegLoc())
3393         return false;
3394   }
3395 
3396   // Check that the call results are passed in the same way.
3397   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3398                                   CCAssignFnForCall(CalleeCC, isVarArg),
3399                                   CCAssignFnForCall(CallerCC, isVarArg)))
3400     return false;
3401   // The callee has to preserve all registers the caller needs to preserve.
3402   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3403   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3404   if (!CCMatch) {
3405     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3406     if (Subtarget->hasCustomCallingConv()) {
3407       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3408       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3409     }
3410     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3411       return false;
3412   }
3413 
3414   // Nothing more to check if the callee is taking no arguments
3415   if (Outs.empty())
3416     return true;
3417 
3418   SmallVector<CCValAssign, 16> ArgLocs;
3419   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3420 
3421   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3422 
3423   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3424 
3425   // If the stack arguments for this call do not fit into our own save area then
3426   // the call cannot be made tail.
3427   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3428     return false;
3429 
3430   const MachineRegisterInfo &MRI = MF.getRegInfo();
3431   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3432     return false;
3433 
3434   return true;
3435 }
3436 
3437 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3438                                                    SelectionDAG &DAG,
3439                                                    MachineFrameInfo &MFI,
3440                                                    int ClobberedFI) const {
3441   SmallVector<SDValue, 8> ArgChains;
3442   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3443   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3444 
3445   // Include the original chain at the beginning of the list. When this is
3446   // used by target LowerCall hooks, this helps legalize find the
3447   // CALLSEQ_BEGIN node.
3448   ArgChains.push_back(Chain);
3449 
3450   // Add a chain value for each stack argument corresponding
3451   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3452                             UE = DAG.getEntryNode().getNode()->use_end();
3453        U != UE; ++U)
3454     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3455       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3456         if (FI->getIndex() < 0) {
3457           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3458           int64_t InLastByte = InFirstByte;
3459           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3460 
3461           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3462               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3463             ArgChains.push_back(SDValue(L, 1));
3464         }
3465 
3466   // Build a tokenfactor for all the chains.
3467   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3468 }
3469 
3470 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3471                                                    bool TailCallOpt) const {
3472   return CallCC == CallingConv::Fast && TailCallOpt;
3473 }
3474 
3475 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3476 /// and add input and output parameter nodes.
3477 SDValue
3478 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3479                                  SmallVectorImpl<SDValue> &InVals) const {
3480   SelectionDAG &DAG = CLI.DAG;
3481   SDLoc &DL = CLI.DL;
3482   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3483   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3484   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3485   SDValue Chain = CLI.Chain;
3486   SDValue Callee = CLI.Callee;
3487   bool &IsTailCall = CLI.IsTailCall;
3488   CallingConv::ID CallConv = CLI.CallConv;
3489   bool IsVarArg = CLI.IsVarArg;
3490 
3491   MachineFunction &MF = DAG.getMachineFunction();
3492   bool IsThisReturn = false;
3493 
3494   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3495   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3496   bool IsSibCall = false;
3497 
3498   if (IsTailCall) {
3499     // Check if it's really possible to do a tail call.
3500     IsTailCall = isEligibleForTailCallOptimization(
3501         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3502     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3503       report_fatal_error("failed to perform tail call elimination on a call "
3504                          "site marked musttail");
3505 
3506     // A sibling call is one where we're under the usual C ABI and not planning
3507     // to change that but can still do a tail call:
3508     if (!TailCallOpt && IsTailCall)
3509       IsSibCall = true;
3510 
3511     if (IsTailCall)
3512       ++NumTailCalls;
3513   }
3514 
3515   // Analyze operands of the call, assigning locations to each operand.
3516   SmallVector<CCValAssign, 16> ArgLocs;
3517   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3518                  *DAG.getContext());
3519 
3520   if (IsVarArg) {
3521     // Handle fixed and variable vector arguments differently.
3522     // Variable vector arguments always go into memory.
3523     unsigned NumArgs = Outs.size();
3524 
3525     for (unsigned i = 0; i != NumArgs; ++i) {
3526       MVT ArgVT = Outs[i].VT;
3527       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3528       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3529                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3530       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3531       assert(!Res && "Call operand has unhandled type");
3532       (void)Res;
3533     }
3534   } else {
3535     // At this point, Outs[].VT may already be promoted to i32. To correctly
3536     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3537     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3538     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3539     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3540     // LocVT.
3541     unsigned NumArgs = Outs.size();
3542     for (unsigned i = 0; i != NumArgs; ++i) {
3543       MVT ValVT = Outs[i].VT;
3544       // Get type of the original argument.
3545       EVT ActualVT = getValueType(DAG.getDataLayout(),
3546                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3547                                   /*AllowUnknown*/ true);
3548       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3549       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3550       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3551       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3552         ValVT = MVT::i8;
3553       else if (ActualMVT == MVT::i16)
3554         ValVT = MVT::i16;
3555 
3556       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3557       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3558       assert(!Res && "Call operand has unhandled type");
3559       (void)Res;
3560     }
3561   }
3562 
3563   // Get a count of how many bytes are to be pushed on the stack.
3564   unsigned NumBytes = CCInfo.getNextStackOffset();
3565 
3566   if (IsSibCall) {
3567     // Since we're not changing the ABI to make this a tail call, the memory
3568     // operands are already available in the caller's incoming argument space.
3569     NumBytes = 0;
3570   }
3571 
3572   // FPDiff is the byte offset of the call's argument area from the callee's.
3573   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3574   // by this amount for a tail call. In a sibling call it must be 0 because the
3575   // caller will deallocate the entire stack and the callee still expects its
3576   // arguments to begin at SP+0. Completely unused for non-tail calls.
3577   int FPDiff = 0;
3578 
3579   if (IsTailCall && !IsSibCall) {
3580     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3581 
3582     // Since callee will pop argument stack as a tail call, we must keep the
3583     // popped size 16-byte aligned.
3584     NumBytes = alignTo(NumBytes, 16);
3585 
3586     // FPDiff will be negative if this tail call requires more space than we
3587     // would automatically have in our incoming argument space. Positive if we
3588     // can actually shrink the stack.
3589     FPDiff = NumReusableBytes - NumBytes;
3590 
3591     // The stack pointer must be 16-byte aligned at all times it's used for a
3592     // memory operation, which in practice means at *all* times and in
3593     // particular across call boundaries. Therefore our own arguments started at
3594     // a 16-byte aligned SP and the delta applied for the tail call should
3595     // satisfy the same constraint.
3596     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3597   }
3598 
3599   // Adjust the stack pointer for the new arguments...
3600   // These operations are automatically eliminated by the prolog/epilog pass
3601   if (!IsSibCall)
3602     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3603 
3604   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3605                                         getPointerTy(DAG.getDataLayout()));
3606 
3607   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3608   SmallVector<SDValue, 8> MemOpChains;
3609   auto PtrVT = getPointerTy(DAG.getDataLayout());
3610 
3611   // Walk the register/memloc assignments, inserting copies/loads.
3612   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3613        ++i, ++realArgIdx) {
3614     CCValAssign &VA = ArgLocs[i];
3615     SDValue Arg = OutVals[realArgIdx];
3616     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3617 
3618     // Promote the value if needed.
3619     switch (VA.getLocInfo()) {
3620     default:
3621       llvm_unreachable("Unknown loc info!");
3622     case CCValAssign::Full:
3623       break;
3624     case CCValAssign::SExt:
3625       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3626       break;
3627     case CCValAssign::ZExt:
3628       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3629       break;
3630     case CCValAssign::AExt:
3631       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3632         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3633         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3634         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3635       }
3636       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3637       break;
3638     case CCValAssign::BCvt:
3639       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3640       break;
3641     case CCValAssign::FPExt:
3642       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3643       break;
3644     }
3645 
3646     if (VA.isRegLoc()) {
3647       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3648           Outs[0].VT == MVT::i64) {
3649         assert(VA.getLocVT() == MVT::i64 &&
3650                "unexpected calling convention register assignment");
3651         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3652                "unexpected use of 'returned'");
3653         IsThisReturn = true;
3654       }
3655       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3656     } else {
3657       assert(VA.isMemLoc());
3658 
3659       SDValue DstAddr;
3660       MachinePointerInfo DstInfo;
3661 
3662       // FIXME: This works on big-endian for composite byvals, which are the
3663       // common case. It should also work for fundamental types too.
3664       uint32_t BEAlign = 0;
3665       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3666                                         : VA.getValVT().getSizeInBits();
3667       OpSize = (OpSize + 7) / 8;
3668       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3669           !Flags.isInConsecutiveRegs()) {
3670         if (OpSize < 8)
3671           BEAlign = 8 - OpSize;
3672       }
3673       unsigned LocMemOffset = VA.getLocMemOffset();
3674       int32_t Offset = LocMemOffset + BEAlign;
3675       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3676       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3677 
3678       if (IsTailCall) {
3679         Offset = Offset + FPDiff;
3680         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3681 
3682         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3683         DstInfo =
3684             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3685 
3686         // Make sure any stack arguments overlapping with where we're storing
3687         // are loaded before this eventual operation. Otherwise they'll be
3688         // clobbered.
3689         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3690       } else {
3691         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3692 
3693         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3694         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3695                                                LocMemOffset);
3696       }
3697 
3698       if (Outs[i].Flags.isByVal()) {
3699         SDValue SizeNode =
3700             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3701         SDValue Cpy = DAG.getMemcpy(
3702             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3703             /*isVol = */ false, /*AlwaysInline = */ false,
3704             /*isTailCall = */ false,
3705             DstInfo, MachinePointerInfo());
3706 
3707         MemOpChains.push_back(Cpy);
3708       } else {
3709         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3710         // promoted to a legal register type i32, we should truncate Arg back to
3711         // i1/i8/i16.
3712         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3713             VA.getValVT() == MVT::i16)
3714           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3715 
3716         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3717         MemOpChains.push_back(Store);
3718       }
3719     }
3720   }
3721 
3722   if (!MemOpChains.empty())
3723     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3724 
3725   // Build a sequence of copy-to-reg nodes chained together with token chain
3726   // and flag operands which copy the outgoing args into the appropriate regs.
3727   SDValue InFlag;
3728   for (auto &RegToPass : RegsToPass) {
3729     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3730                              RegToPass.second, InFlag);
3731     InFlag = Chain.getValue(1);
3732   }
3733 
3734   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3735   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3736   // node so that legalize doesn't hack it.
3737   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3738     auto GV = G->getGlobal();
3739     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3740         AArch64II::MO_GOT) {
3741       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3742       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3743     } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3744       assert(Subtarget->isTargetWindows() &&
3745              "Windows is the only supported COFF target");
3746       Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3747     } else {
3748       const GlobalValue *GV = G->getGlobal();
3749       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3750     }
3751   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3752     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3753         Subtarget->isTargetMachO()) {
3754       const char *Sym = S->getSymbol();
3755       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3756       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3757     } else {
3758       const char *Sym = S->getSymbol();
3759       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3760     }
3761   }
3762 
3763   // We don't usually want to end the call-sequence here because we would tidy
3764   // the frame up *after* the call, however in the ABI-changing tail-call case
3765   // we've carefully laid out the parameters so that when sp is reset they'll be
3766   // in the correct location.
3767   if (IsTailCall && !IsSibCall) {
3768     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3769                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3770     InFlag = Chain.getValue(1);
3771   }
3772 
3773   std::vector<SDValue> Ops;
3774   Ops.push_back(Chain);
3775   Ops.push_back(Callee);
3776 
3777   if (IsTailCall) {
3778     // Each tail call may have to adjust the stack by a different amount, so
3779     // this information must travel along with the operation for eventual
3780     // consumption by emitEpilogue.
3781     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3782   }
3783 
3784   // Add argument registers to the end of the list so that they are known live
3785   // into the call.
3786   for (auto &RegToPass : RegsToPass)
3787     Ops.push_back(DAG.getRegister(RegToPass.first,
3788                                   RegToPass.second.getValueType()));
3789 
3790   // Add a register mask operand representing the call-preserved registers.
3791   const uint32_t *Mask;
3792   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3793   if (IsThisReturn) {
3794     // For 'this' returns, use the X0-preserving mask if applicable
3795     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3796     if (!Mask) {
3797       IsThisReturn = false;
3798       Mask = TRI->getCallPreservedMask(MF, CallConv);
3799     }
3800   } else
3801     Mask = TRI->getCallPreservedMask(MF, CallConv);
3802 
3803   if (Subtarget->hasCustomCallingConv())
3804     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3805 
3806   if (TRI->isAnyArgRegReserved(MF))
3807     TRI->emitReservedArgRegCallError(MF);
3808 
3809   assert(Mask && "Missing call preserved mask for calling convention");
3810   Ops.push_back(DAG.getRegisterMask(Mask));
3811 
3812   if (InFlag.getNode())
3813     Ops.push_back(InFlag);
3814 
3815   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3816 
3817   // If we're doing a tall call, use a TC_RETURN here rather than an
3818   // actual call instruction.
3819   if (IsTailCall) {
3820     MF.getFrameInfo().setHasTailCall();
3821     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3822   }
3823 
3824   // Returns a chain and a flag for retval copy to use.
3825   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3826   InFlag = Chain.getValue(1);
3827 
3828   uint64_t CalleePopBytes =
3829       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3830 
3831   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3832                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3833                              InFlag, DL);
3834   if (!Ins.empty())
3835     InFlag = Chain.getValue(1);
3836 
3837   // Handle result values, copying them out of physregs into vregs that we
3838   // return.
3839   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3840                          InVals, IsThisReturn,
3841                          IsThisReturn ? OutVals[0] : SDValue());
3842 }
3843 
3844 bool AArch64TargetLowering::CanLowerReturn(
3845     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3846     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3847   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3848                           ? RetCC_AArch64_WebKit_JS
3849                           : RetCC_AArch64_AAPCS;
3850   SmallVector<CCValAssign, 16> RVLocs;
3851   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3852   return CCInfo.CheckReturn(Outs, RetCC);
3853 }
3854 
3855 SDValue
3856 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3857                                    bool isVarArg,
3858                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3859                                    const SmallVectorImpl<SDValue> &OutVals,
3860                                    const SDLoc &DL, SelectionDAG &DAG) const {
3861   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3862                           ? RetCC_AArch64_WebKit_JS
3863                           : RetCC_AArch64_AAPCS;
3864   SmallVector<CCValAssign, 16> RVLocs;
3865   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3866                  *DAG.getContext());
3867   CCInfo.AnalyzeReturn(Outs, RetCC);
3868 
3869   // Copy the result values into the output registers.
3870   SDValue Flag;
3871   SmallVector<SDValue, 4> RetOps(1, Chain);
3872   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3873        ++i, ++realRVLocIdx) {
3874     CCValAssign &VA = RVLocs[i];
3875     assert(VA.isRegLoc() && "Can only return in registers!");
3876     SDValue Arg = OutVals[realRVLocIdx];
3877 
3878     switch (VA.getLocInfo()) {
3879     default:
3880       llvm_unreachable("Unknown loc info!");
3881     case CCValAssign::Full:
3882       if (Outs[i].ArgVT == MVT::i1) {
3883         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3884         // value. This is strictly redundant on Darwin (which uses "zeroext
3885         // i1"), but will be optimised out before ISel.
3886         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3887         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3888       }
3889       break;
3890     case CCValAssign::BCvt:
3891       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3892       break;
3893     }
3894 
3895     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3896     Flag = Chain.getValue(1);
3897     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3898   }
3899   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3900   const MCPhysReg *I =
3901       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3902   if (I) {
3903     for (; *I; ++I) {
3904       if (AArch64::GPR64RegClass.contains(*I))
3905         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3906       else if (AArch64::FPR64RegClass.contains(*I))
3907         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3908       else
3909         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3910     }
3911   }
3912 
3913   RetOps[0] = Chain; // Update chain.
3914 
3915   // Add the flag if we have it.
3916   if (Flag.getNode())
3917     RetOps.push_back(Flag);
3918 
3919   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3920 }
3921 
3922 //===----------------------------------------------------------------------===//
3923 //  Other Lowering Code
3924 //===----------------------------------------------------------------------===//
3925 
3926 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3927                                              SelectionDAG &DAG,
3928                                              unsigned Flag) const {
3929   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3930                                     N->getOffset(), Flag);
3931 }
3932 
3933 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3934                                              SelectionDAG &DAG,
3935                                              unsigned Flag) const {
3936   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3937 }
3938 
3939 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3940                                              SelectionDAG &DAG,
3941                                              unsigned Flag) const {
3942   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3943                                    N->getOffset(), Flag);
3944 }
3945 
3946 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3947                                              SelectionDAG &DAG,
3948                                              unsigned Flag) const {
3949   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3950 }
3951 
3952 // (loadGOT sym)
3953 template <class NodeTy>
3954 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3955                                       unsigned Flags) const {
3956   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3957   SDLoc DL(N);
3958   EVT Ty = getPointerTy(DAG.getDataLayout());
3959   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
3960   // FIXME: Once remat is capable of dealing with instructions with register
3961   // operands, expand this into two nodes instead of using a wrapper node.
3962   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3963 }
3964 
3965 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3966 template <class NodeTy>
3967 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3968                                             unsigned Flags) const {
3969   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3970   SDLoc DL(N);
3971   EVT Ty = getPointerTy(DAG.getDataLayout());
3972   const unsigned char MO_NC = AArch64II::MO_NC;
3973   return DAG.getNode(
3974       AArch64ISD::WrapperLarge, DL, Ty,
3975       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3976       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3977       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3978       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
3979 }
3980 
3981 // (addlow (adrp %hi(sym)) %lo(sym))
3982 template <class NodeTy>
3983 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3984                                        unsigned Flags) const {
3985   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3986   SDLoc DL(N);
3987   EVT Ty = getPointerTy(DAG.getDataLayout());
3988   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
3989   SDValue Lo = getTargetNode(N, Ty, DAG,
3990                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
3991   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3992   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3993 }
3994 
3995 // (adr sym)
3996 template <class NodeTy>
3997 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
3998                                            unsigned Flags) const {
3999   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4000   SDLoc DL(N);
4001   EVT Ty = getPointerTy(DAG.getDataLayout());
4002   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4003   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4004 }
4005 
4006 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4007                                                   SelectionDAG &DAG) const {
4008   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4009   const GlobalValue *GV = GN->getGlobal();
4010   unsigned char OpFlags =
4011       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4012 
4013   if (OpFlags != AArch64II::MO_NO_FLAG)
4014     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4015            "unexpected offset in global node");
4016 
4017   // This also catches the large code model case for Darwin, and tiny code
4018   // model with got relocations.
4019   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4020     return getGOT(GN, DAG, OpFlags);
4021   }
4022 
4023   SDValue Result;
4024   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4025     Result = getAddrLarge(GN, DAG, OpFlags);
4026   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4027     Result = getAddrTiny(GN, DAG, OpFlags);
4028   } else {
4029     Result = getAddr(GN, DAG, OpFlags);
4030   }
4031   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4032   SDLoc DL(GN);
4033   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4034     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4035                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4036   return Result;
4037 }
4038 
4039 /// Convert a TLS address reference into the correct sequence of loads
4040 /// and calls to compute the variable's address (for Darwin, currently) and
4041 /// return an SDValue containing the final node.
4042 
4043 /// Darwin only has one TLS scheme which must be capable of dealing with the
4044 /// fully general situation, in the worst case. This means:
4045 ///     + "extern __thread" declaration.
4046 ///     + Defined in a possibly unknown dynamic library.
4047 ///
4048 /// The general system is that each __thread variable has a [3 x i64] descriptor
4049 /// which contains information used by the runtime to calculate the address. The
4050 /// only part of this the compiler needs to know about is the first xword, which
4051 /// contains a function pointer that must be called with the address of the
4052 /// entire descriptor in "x0".
4053 ///
4054 /// Since this descriptor may be in a different unit, in general even the
4055 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4056 /// is:
4057 ///     adrp x0, _var@TLVPPAGE
4058 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4059 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4060 ///                                      ; the function pointer
4061 ///     blr x1                           ; Uses descriptor address in x0
4062 ///     ; Address of _var is now in x0.
4063 ///
4064 /// If the address of _var's descriptor *is* known to the linker, then it can
4065 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4066 /// a slight efficiency gain.
4067 SDValue
4068 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4069                                                    SelectionDAG &DAG) const {
4070   assert(Subtarget->isTargetDarwin() &&
4071          "This function expects a Darwin target");
4072 
4073   SDLoc DL(Op);
4074   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4075   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4076 
4077   SDValue TLVPAddr =
4078       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4079   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4080 
4081   // The first entry in the descriptor is a function pointer that we must call
4082   // to obtain the address of the variable.
4083   SDValue Chain = DAG.getEntryNode();
4084   SDValue FuncTLVGet = DAG.getLoad(
4085       MVT::i64, DL, Chain, DescAddr,
4086       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4087       /* Alignment = */ 8,
4088       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4089           MachineMemOperand::MODereferenceable);
4090   Chain = FuncTLVGet.getValue(1);
4091 
4092   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4093   MFI.setAdjustsStack(true);
4094 
4095   // TLS calls preserve all registers except those that absolutely must be
4096   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4097   // silly).
4098   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4099   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4100   if (Subtarget->hasCustomCallingConv())
4101     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4102 
4103   // Finally, we can make the call. This is just a degenerate version of a
4104   // normal AArch64 call node: x0 takes the address of the descriptor, and
4105   // returns the address of the variable in this thread.
4106   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4107   Chain =
4108       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4109                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4110                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4111   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4112 }
4113 
4114 /// When accessing thread-local variables under either the general-dynamic or
4115 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4116 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4117 /// is a function pointer to carry out the resolution.
4118 ///
4119 /// The sequence is:
4120 ///    adrp  x0, :tlsdesc:var
4121 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4122 ///    add   x0, x0, #:tlsdesc_lo12:var
4123 ///    .tlsdesccall var
4124 ///    blr   x1
4125 ///    (TPIDR_EL0 offset now in x0)
4126 ///
4127 ///  The above sequence must be produced unscheduled, to enable the linker to
4128 ///  optimize/relax this sequence.
4129 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4130 ///  above sequence, and expanded really late in the compilation flow, to ensure
4131 ///  the sequence is produced as per above.
4132 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4133                                                       const SDLoc &DL,
4134                                                       SelectionDAG &DAG) const {
4135   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4136 
4137   SDValue Chain = DAG.getEntryNode();
4138   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4139 
4140   Chain =
4141       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4142   SDValue Glue = Chain.getValue(1);
4143 
4144   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4145 }
4146 
4147 SDValue
4148 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4149                                                 SelectionDAG &DAG) const {
4150   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4151   if (getTargetMachine().getCodeModel() == CodeModel::Large)
4152     report_fatal_error("ELF TLS only supported in small memory model");
4153   // Different choices can be made for the maximum size of the TLS area for a
4154   // module. For the small address model, the default TLS size is 16MiB and the
4155   // maximum TLS size is 4GiB.
4156   // FIXME: add -mtls-size command line option and make it control the 16MiB
4157   // vs. 4GiB code sequence generation.
4158   // FIXME: add tiny codemodel support. We currently generate the same code as
4159   // small, which may be larger than needed.
4160   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4161 
4162   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4163 
4164   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4165     if (Model == TLSModel::LocalDynamic)
4166       Model = TLSModel::GeneralDynamic;
4167   }
4168 
4169   SDValue TPOff;
4170   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4171   SDLoc DL(Op);
4172   const GlobalValue *GV = GA->getGlobal();
4173 
4174   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4175 
4176   if (Model == TLSModel::LocalExec) {
4177     SDValue HiVar = DAG.getTargetGlobalAddress(
4178         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4179     SDValue LoVar = DAG.getTargetGlobalAddress(
4180         GV, DL, PtrVT, 0,
4181         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4182 
4183     SDValue TPWithOff_lo =
4184         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4185                                    HiVar,
4186                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4187                 0);
4188     SDValue TPWithOff =
4189         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4190                                    LoVar,
4191                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4192                 0);
4193     return TPWithOff;
4194   } else if (Model == TLSModel::InitialExec) {
4195     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4196     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4197   } else if (Model == TLSModel::LocalDynamic) {
4198     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4199     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4200     // the beginning of the module's TLS region, followed by a DTPREL offset
4201     // calculation.
4202 
4203     // These accesses will need deduplicating if there's more than one.
4204     AArch64FunctionInfo *MFI =
4205         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4206     MFI->incNumLocalDynamicTLSAccesses();
4207 
4208     // The call needs a relocation too for linker relaxation. It doesn't make
4209     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4210     // the address.
4211     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4212                                                   AArch64II::MO_TLS);
4213 
4214     // Now we can calculate the offset from TPIDR_EL0 to this module's
4215     // thread-local area.
4216     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4217 
4218     // Now use :dtprel_whatever: operations to calculate this variable's offset
4219     // in its thread-storage area.
4220     SDValue HiVar = DAG.getTargetGlobalAddress(
4221         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4222     SDValue LoVar = DAG.getTargetGlobalAddress(
4223         GV, DL, MVT::i64, 0,
4224         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4225 
4226     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4227                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4228                     0);
4229     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4230                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4231                     0);
4232   } else if (Model == TLSModel::GeneralDynamic) {
4233     // The call needs a relocation too for linker relaxation. It doesn't make
4234     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4235     // the address.
4236     SDValue SymAddr =
4237         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4238 
4239     // Finally we can make a call to calculate the offset from tpidr_el0.
4240     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4241   } else
4242     llvm_unreachable("Unsupported ELF TLS access model");
4243 
4244   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4245 }
4246 
4247 SDValue
4248 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4249                                                     SelectionDAG &DAG) const {
4250   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4251 
4252   SDValue Chain = DAG.getEntryNode();
4253   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4254   SDLoc DL(Op);
4255 
4256   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4257 
4258   // Load the ThreadLocalStoragePointer from the TEB
4259   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4260   SDValue TLSArray =
4261       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4262   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4263   Chain = TLSArray.getValue(1);
4264 
4265   // Load the TLS index from the C runtime;
4266   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4267   // This also does the same as LOADgot, but using a generic i32 load,
4268   // while LOADgot only loads i64.
4269   SDValue TLSIndexHi =
4270       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4271   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4272       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4273   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4274   SDValue TLSIndex =
4275       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4276   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4277   Chain = TLSIndex.getValue(1);
4278 
4279   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4280   // offset into the TLSArray.
4281   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4282   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4283                              DAG.getConstant(3, DL, PtrVT));
4284   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4285                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4286                             MachinePointerInfo());
4287   Chain = TLS.getValue(1);
4288 
4289   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4290   const GlobalValue *GV = GA->getGlobal();
4291   SDValue TGAHi = DAG.getTargetGlobalAddress(
4292       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4293   SDValue TGALo = DAG.getTargetGlobalAddress(
4294       GV, DL, PtrVT, 0,
4295       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4296 
4297   // Add the offset from the start of the .tls section (section base).
4298   SDValue Addr =
4299       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4300                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4301               0);
4302   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4303   return Addr;
4304 }
4305 
4306 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4307                                                      SelectionDAG &DAG) const {
4308   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4309   if (DAG.getTarget().useEmulatedTLS())
4310     return LowerToTLSEmulatedModel(GA, DAG);
4311 
4312   if (Subtarget->isTargetDarwin())
4313     return LowerDarwinGlobalTLSAddress(Op, DAG);
4314   if (Subtarget->isTargetELF())
4315     return LowerELFGlobalTLSAddress(Op, DAG);
4316   if (Subtarget->isTargetWindows())
4317     return LowerWindowsGlobalTLSAddress(Op, DAG);
4318 
4319   llvm_unreachable("Unexpected platform trying to use TLS");
4320 }
4321 
4322 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4323   SDValue Chain = Op.getOperand(0);
4324   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4325   SDValue LHS = Op.getOperand(2);
4326   SDValue RHS = Op.getOperand(3);
4327   SDValue Dest = Op.getOperand(4);
4328   SDLoc dl(Op);
4329 
4330   // Handle f128 first, since lowering it will result in comparing the return
4331   // value of a libcall against zero, which is just what the rest of LowerBR_CC
4332   // is expecting to deal with.
4333   if (LHS.getValueType() == MVT::f128) {
4334     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4335 
4336     // If softenSetCCOperands returned a scalar, we need to compare the result
4337     // against zero to select between true and false values.
4338     if (!RHS.getNode()) {
4339       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4340       CC = ISD::SETNE;
4341     }
4342   }
4343 
4344   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4345   // instruction.
4346   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4347       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4348     // Only lower legal XALUO ops.
4349     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4350       return SDValue();
4351 
4352     // The actual operation with overflow check.
4353     AArch64CC::CondCode OFCC;
4354     SDValue Value, Overflow;
4355     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4356 
4357     if (CC == ISD::SETNE)
4358       OFCC = getInvertedCondCode(OFCC);
4359     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4360 
4361     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4362                        Overflow);
4363   }
4364 
4365   if (LHS.getValueType().isInteger()) {
4366     assert((LHS.getValueType() == RHS.getValueType()) &&
4367            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4368 
4369     // If the RHS of the comparison is zero, we can potentially fold this
4370     // to a specialized branch.
4371     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4372     if (RHSC && RHSC->getZExtValue() == 0) {
4373       if (CC == ISD::SETEQ) {
4374         // See if we can use a TBZ to fold in an AND as well.
4375         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4376         // out of bounds, a late MI-layer pass rewrites branches.
4377         // 403.gcc is an example that hits this case.
4378         if (LHS.getOpcode() == ISD::AND &&
4379             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4380             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4381           SDValue Test = LHS.getOperand(0);
4382           uint64_t Mask = LHS.getConstantOperandVal(1);
4383           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4384                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4385                              Dest);
4386         }
4387 
4388         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4389       } else if (CC == ISD::SETNE) {
4390         // See if we can use a TBZ to fold in an AND as well.
4391         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4392         // out of bounds, a late MI-layer pass rewrites branches.
4393         // 403.gcc is an example that hits this case.
4394         if (LHS.getOpcode() == ISD::AND &&
4395             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4396             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4397           SDValue Test = LHS.getOperand(0);
4398           uint64_t Mask = LHS.getConstantOperandVal(1);
4399           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4400                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4401                              Dest);
4402         }
4403 
4404         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4405       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4406         // Don't combine AND since emitComparison converts the AND to an ANDS
4407         // (a.k.a. TST) and the test in the test bit and branch instruction
4408         // becomes redundant.  This would also increase register pressure.
4409         uint64_t Mask = LHS.getValueSizeInBits() - 1;
4410         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4411                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
4412       }
4413     }
4414     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4415         LHS.getOpcode() != ISD::AND) {
4416       // Don't combine AND since emitComparison converts the AND to an ANDS
4417       // (a.k.a. TST) and the test in the test bit and branch instruction
4418       // becomes redundant.  This would also increase register pressure.
4419       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4420       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4421                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4422     }
4423 
4424     SDValue CCVal;
4425     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4426     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4427                        Cmp);
4428   }
4429 
4430   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4431          LHS.getValueType() == MVT::f64);
4432 
4433   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4434   // clean.  Some of them require two branches to implement.
4435   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4436   AArch64CC::CondCode CC1, CC2;
4437   changeFPCCToAArch64CC(CC, CC1, CC2);
4438   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4439   SDValue BR1 =
4440       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4441   if (CC2 != AArch64CC::AL) {
4442     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4443     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4444                        Cmp);
4445   }
4446 
4447   return BR1;
4448 }
4449 
4450 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4451                                               SelectionDAG &DAG) const {
4452   EVT VT = Op.getValueType();
4453   SDLoc DL(Op);
4454 
4455   SDValue In1 = Op.getOperand(0);
4456   SDValue In2 = Op.getOperand(1);
4457   EVT SrcVT = In2.getValueType();
4458 
4459   if (SrcVT.bitsLT(VT))
4460     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4461   else if (SrcVT.bitsGT(VT))
4462     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4463 
4464   EVT VecVT;
4465   uint64_t EltMask;
4466   SDValue VecVal1, VecVal2;
4467 
4468   auto setVecVal = [&] (int Idx) {
4469     if (!VT.isVector()) {
4470       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4471                                           DAG.getUNDEF(VecVT), In1);
4472       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4473                                           DAG.getUNDEF(VecVT), In2);
4474     } else {
4475       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4476       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4477     }
4478   };
4479 
4480   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4481     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4482     EltMask = 0x80000000ULL;
4483     setVecVal(AArch64::ssub);
4484   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4485     VecVT = MVT::v2i64;
4486 
4487     // We want to materialize a mask with the high bit set, but the AdvSIMD
4488     // immediate moves cannot materialize that in a single instruction for
4489     // 64-bit elements. Instead, materialize zero and then negate it.
4490     EltMask = 0;
4491 
4492     setVecVal(AArch64::dsub);
4493   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4494     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4495     EltMask = 0x8000ULL;
4496     setVecVal(AArch64::hsub);
4497   } else {
4498     llvm_unreachable("Invalid type for copysign!");
4499   }
4500 
4501   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4502 
4503   // If we couldn't materialize the mask above, then the mask vector will be
4504   // the zero vector, and we need to negate it here.
4505   if (VT == MVT::f64 || VT == MVT::v2f64) {
4506     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4507     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4508     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4509   }
4510 
4511   SDValue Sel =
4512       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4513 
4514   if (VT == MVT::f16)
4515     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4516   if (VT == MVT::f32)
4517     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4518   else if (VT == MVT::f64)
4519     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4520   else
4521     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4522 }
4523 
4524 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4525   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4526           Attribute::NoImplicitFloat))
4527     return SDValue();
4528 
4529   if (!Subtarget->hasNEON())
4530     return SDValue();
4531 
4532   // While there is no integer popcount instruction, it can
4533   // be more efficiently lowered to the following sequence that uses
4534   // AdvSIMD registers/instructions as long as the copies to/from
4535   // the AdvSIMD registers are cheap.
4536   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4537   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4538   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4539   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4540   SDValue Val = Op.getOperand(0);
4541   SDLoc DL(Op);
4542   EVT VT = Op.getValueType();
4543 
4544   if (VT == MVT::i32 || VT == MVT::i64) {
4545     if (VT == MVT::i32)
4546       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4547     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4548 
4549     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4550     SDValue UaddLV = DAG.getNode(
4551         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4552         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4553 
4554     if (VT == MVT::i64)
4555       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4556     return UaddLV;
4557   }
4558 
4559   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4560           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4561          "Unexpected type for custom ctpop lowering");
4562 
4563   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4564   Val = DAG.getBitcast(VT8Bit, Val);
4565   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4566 
4567   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4568   unsigned EltSize = 8;
4569   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4570   while (EltSize != VT.getScalarSizeInBits()) {
4571     EltSize *= 2;
4572     NumElts /= 2;
4573     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4574     Val = DAG.getNode(
4575         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4576         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4577   }
4578 
4579   return Val;
4580 }
4581 
4582 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4583 
4584   if (Op.getValueType().isVector())
4585     return LowerVSETCC(Op, DAG);
4586 
4587   SDValue LHS = Op.getOperand(0);
4588   SDValue RHS = Op.getOperand(1);
4589   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4590   SDLoc dl(Op);
4591 
4592   // We chose ZeroOrOneBooleanContents, so use zero and one.
4593   EVT VT = Op.getValueType();
4594   SDValue TVal = DAG.getConstant(1, dl, VT);
4595   SDValue FVal = DAG.getConstant(0, dl, VT);
4596 
4597   // Handle f128 first, since one possible outcome is a normal integer
4598   // comparison which gets picked up by the next if statement.
4599   if (LHS.getValueType() == MVT::f128) {
4600     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4601 
4602     // If softenSetCCOperands returned a scalar, use it.
4603     if (!RHS.getNode()) {
4604       assert(LHS.getValueType() == Op.getValueType() &&
4605              "Unexpected setcc expansion!");
4606       return LHS;
4607     }
4608   }
4609 
4610   if (LHS.getValueType().isInteger()) {
4611     SDValue CCVal;
4612     SDValue Cmp =
4613         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4614 
4615     // Note that we inverted the condition above, so we reverse the order of
4616     // the true and false operands here.  This will allow the setcc to be
4617     // matched to a single CSINC instruction.
4618     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4619   }
4620 
4621   // Now we know we're dealing with FP values.
4622   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4623          LHS.getValueType() == MVT::f64);
4624 
4625   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
4626   // and do the comparison.
4627   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4628 
4629   AArch64CC::CondCode CC1, CC2;
4630   changeFPCCToAArch64CC(CC, CC1, CC2);
4631   if (CC2 == AArch64CC::AL) {
4632     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4633     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4634 
4635     // Note that we inverted the condition above, so we reverse the order of
4636     // the true and false operands here.  This will allow the setcc to be
4637     // matched to a single CSINC instruction.
4638     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4639   } else {
4640     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4641     // totally clean.  Some of them require two CSELs to implement.  As is in
4642     // this case, we emit the first CSEL and then emit a second using the output
4643     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
4644 
4645     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4646     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4647     SDValue CS1 =
4648         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4649 
4650     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4651     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4652   }
4653 }
4654 
4655 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4656                                               SDValue RHS, SDValue TVal,
4657                                               SDValue FVal, const SDLoc &dl,
4658                                               SelectionDAG &DAG) const {
4659   // Handle f128 first, because it will result in a comparison of some RTLIB
4660   // call result against zero.
4661   if (LHS.getValueType() == MVT::f128) {
4662     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4663 
4664     // If softenSetCCOperands returned a scalar, we need to compare the result
4665     // against zero to select between true and false values.
4666     if (!RHS.getNode()) {
4667       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4668       CC = ISD::SETNE;
4669     }
4670   }
4671 
4672   // Also handle f16, for which we need to do a f32 comparison.
4673   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4674     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4675     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4676   }
4677 
4678   // Next, handle integers.
4679   if (LHS.getValueType().isInteger()) {
4680     assert((LHS.getValueType() == RHS.getValueType()) &&
4681            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4682 
4683     unsigned Opcode = AArch64ISD::CSEL;
4684 
4685     // If both the TVal and the FVal are constants, see if we can swap them in
4686     // order to for a CSINV or CSINC out of them.
4687     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4688     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4689 
4690     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4691       std::swap(TVal, FVal);
4692       std::swap(CTVal, CFVal);
4693       CC = ISD::getSetCCInverse(CC, true);
4694     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4695       std::swap(TVal, FVal);
4696       std::swap(CTVal, CFVal);
4697       CC = ISD::getSetCCInverse(CC, true);
4698     } else if (TVal.getOpcode() == ISD::XOR) {
4699       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4700       // with a CSINV rather than a CSEL.
4701       if (isAllOnesConstant(TVal.getOperand(1))) {
4702         std::swap(TVal, FVal);
4703         std::swap(CTVal, CFVal);
4704         CC = ISD::getSetCCInverse(CC, true);
4705       }
4706     } else if (TVal.getOpcode() == ISD::SUB) {
4707       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4708       // that we can match with a CSNEG rather than a CSEL.
4709       if (isNullConstant(TVal.getOperand(0))) {
4710         std::swap(TVal, FVal);
4711         std::swap(CTVal, CFVal);
4712         CC = ISD::getSetCCInverse(CC, true);
4713       }
4714     } else if (CTVal && CFVal) {
4715       const int64_t TrueVal = CTVal->getSExtValue();
4716       const int64_t FalseVal = CFVal->getSExtValue();
4717       bool Swap = false;
4718 
4719       // If both TVal and FVal are constants, see if FVal is the
4720       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4721       // instead of a CSEL in that case.
4722       if (TrueVal == ~FalseVal) {
4723         Opcode = AArch64ISD::CSINV;
4724       } else if (TrueVal == -FalseVal) {
4725         Opcode = AArch64ISD::CSNEG;
4726       } else if (TVal.getValueType() == MVT::i32) {
4727         // If our operands are only 32-bit wide, make sure we use 32-bit
4728         // arithmetic for the check whether we can use CSINC. This ensures that
4729         // the addition in the check will wrap around properly in case there is
4730         // an overflow (which would not be the case if we do the check with
4731         // 64-bit arithmetic).
4732         const uint32_t TrueVal32 = CTVal->getZExtValue();
4733         const uint32_t FalseVal32 = CFVal->getZExtValue();
4734 
4735         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4736           Opcode = AArch64ISD::CSINC;
4737 
4738           if (TrueVal32 > FalseVal32) {
4739             Swap = true;
4740           }
4741         }
4742         // 64-bit check whether we can use CSINC.
4743       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4744         Opcode = AArch64ISD::CSINC;
4745 
4746         if (TrueVal > FalseVal) {
4747           Swap = true;
4748         }
4749       }
4750 
4751       // Swap TVal and FVal if necessary.
4752       if (Swap) {
4753         std::swap(TVal, FVal);
4754         std::swap(CTVal, CFVal);
4755         CC = ISD::getSetCCInverse(CC, true);
4756       }
4757 
4758       if (Opcode != AArch64ISD::CSEL) {
4759         // Drop FVal since we can get its value by simply inverting/negating
4760         // TVal.
4761         FVal = TVal;
4762       }
4763     }
4764 
4765     // Avoid materializing a constant when possible by reusing a known value in
4766     // a register.  However, don't perform this optimization if the known value
4767     // is one, zero or negative one in the case of a CSEL.  We can always
4768     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4769     // FVal, respectively.
4770     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4771     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4772         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4773       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4774       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4775       // "a != C ? x : a" to avoid materializing C.
4776       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4777         TVal = LHS;
4778       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4779         FVal = LHS;
4780     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4781       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4782       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4783       // avoid materializing C.
4784       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4785       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4786         Opcode = AArch64ISD::CSINV;
4787         TVal = LHS;
4788         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4789       }
4790     }
4791 
4792     SDValue CCVal;
4793     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4794     EVT VT = TVal.getValueType();
4795     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4796   }
4797 
4798   // Now we know we're dealing with FP values.
4799   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4800          LHS.getValueType() == MVT::f64);
4801   assert(LHS.getValueType() == RHS.getValueType());
4802   EVT VT = TVal.getValueType();
4803   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4804 
4805   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4806   // clean.  Some of them require two CSELs to implement.
4807   AArch64CC::CondCode CC1, CC2;
4808   changeFPCCToAArch64CC(CC, CC1, CC2);
4809 
4810   if (DAG.getTarget().Options.UnsafeFPMath) {
4811     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4812     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4813     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4814     if (RHSVal && RHSVal->isZero()) {
4815       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4816       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4817 
4818       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4819           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4820         TVal = LHS;
4821       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4822                CFVal && CFVal->isZero() &&
4823                FVal.getValueType() == LHS.getValueType())
4824         FVal = LHS;
4825     }
4826   }
4827 
4828   // Emit first, and possibly only, CSEL.
4829   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4830   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4831 
4832   // If we need a second CSEL, emit it, using the output of the first as the
4833   // RHS.  We're effectively OR'ing the two CC's together.
4834   if (CC2 != AArch64CC::AL) {
4835     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4836     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4837   }
4838 
4839   // Otherwise, return the output of the first CSEL.
4840   return CS1;
4841 }
4842 
4843 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4844                                               SelectionDAG &DAG) const {
4845   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4846   SDValue LHS = Op.getOperand(0);
4847   SDValue RHS = Op.getOperand(1);
4848   SDValue TVal = Op.getOperand(2);
4849   SDValue FVal = Op.getOperand(3);
4850   SDLoc DL(Op);
4851   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4852 }
4853 
4854 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4855                                            SelectionDAG &DAG) const {
4856   SDValue CCVal = Op->getOperand(0);
4857   SDValue TVal = Op->getOperand(1);
4858   SDValue FVal = Op->getOperand(2);
4859   SDLoc DL(Op);
4860 
4861   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4862   // instruction.
4863   if (isOverflowIntrOpRes(CCVal)) {
4864     // Only lower legal XALUO ops.
4865     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4866       return SDValue();
4867 
4868     AArch64CC::CondCode OFCC;
4869     SDValue Value, Overflow;
4870     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4871     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4872 
4873     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4874                        CCVal, Overflow);
4875   }
4876 
4877   // Lower it the same way as we would lower a SELECT_CC node.
4878   ISD::CondCode CC;
4879   SDValue LHS, RHS;
4880   if (CCVal.getOpcode() == ISD::SETCC) {
4881     LHS = CCVal.getOperand(0);
4882     RHS = CCVal.getOperand(1);
4883     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4884   } else {
4885     LHS = CCVal;
4886     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4887     CC = ISD::SETNE;
4888   }
4889   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4890 }
4891 
4892 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4893                                               SelectionDAG &DAG) const {
4894   // Jump table entries as PC relative offsets. No additional tweaking
4895   // is necessary here. Just get the address of the jump table.
4896   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4897 
4898   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4899       !Subtarget->isTargetMachO()) {
4900     return getAddrLarge(JT, DAG);
4901   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4902     return getAddrTiny(JT, DAG);
4903   }
4904   return getAddr(JT, DAG);
4905 }
4906 
4907 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4908                                           SelectionDAG &DAG) const {
4909   // Jump table entries as PC relative offsets. No additional tweaking
4910   // is necessary here. Just get the address of the jump table.
4911   SDLoc DL(Op);
4912   SDValue JT = Op.getOperand(1);
4913   SDValue Entry = Op.getOperand(2);
4914   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4915 
4916   SDNode *Dest =
4917       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4918                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4919   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4920                      SDValue(Dest, 0));
4921 }
4922 
4923 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4924                                                  SelectionDAG &DAG) const {
4925   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4926 
4927   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4928     // Use the GOT for the large code model on iOS.
4929     if (Subtarget->isTargetMachO()) {
4930       return getGOT(CP, DAG);
4931     }
4932     return getAddrLarge(CP, DAG);
4933   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4934     return getAddrTiny(CP, DAG);
4935   } else {
4936     return getAddr(CP, DAG);
4937   }
4938 }
4939 
4940 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4941                                                SelectionDAG &DAG) const {
4942   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4943   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4944       !Subtarget->isTargetMachO()) {
4945     return getAddrLarge(BA, DAG);
4946   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4947     return getAddrTiny(BA, DAG);
4948   }
4949   return getAddr(BA, DAG);
4950 }
4951 
4952 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4953                                                  SelectionDAG &DAG) const {
4954   AArch64FunctionInfo *FuncInfo =
4955       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4956 
4957   SDLoc DL(Op);
4958   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4959                                  getPointerTy(DAG.getDataLayout()));
4960   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4961   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4962                       MachinePointerInfo(SV));
4963 }
4964 
4965 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4966                                                   SelectionDAG &DAG) const {
4967   AArch64FunctionInfo *FuncInfo =
4968       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4969 
4970   SDLoc DL(Op);
4971   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4972                                      ? FuncInfo->getVarArgsGPRIndex()
4973                                      : FuncInfo->getVarArgsStackIndex(),
4974                                  getPointerTy(DAG.getDataLayout()));
4975   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4976   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4977                       MachinePointerInfo(SV));
4978 }
4979 
4980 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4981                                                 SelectionDAG &DAG) const {
4982   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4983   // Standard, section B.3.
4984   MachineFunction &MF = DAG.getMachineFunction();
4985   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4986   auto PtrVT = getPointerTy(DAG.getDataLayout());
4987   SDLoc DL(Op);
4988 
4989   SDValue Chain = Op.getOperand(0);
4990   SDValue VAList = Op.getOperand(1);
4991   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4992   SmallVector<SDValue, 4> MemOps;
4993 
4994   // void *__stack at offset 0
4995   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4996   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4997                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4998 
4999   // void *__gr_top at offset 8
5000   int GPRSize = FuncInfo->getVarArgsGPRSize();
5001   if (GPRSize > 0) {
5002     SDValue GRTop, GRTopAddr;
5003 
5004     GRTopAddr =
5005         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5006 
5007     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5008     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5009                         DAG.getConstant(GPRSize, DL, PtrVT));
5010 
5011     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5012                                   MachinePointerInfo(SV, 8),
5013                                   /* Alignment = */ 8));
5014   }
5015 
5016   // void *__vr_top at offset 16
5017   int FPRSize = FuncInfo->getVarArgsFPRSize();
5018   if (FPRSize > 0) {
5019     SDValue VRTop, VRTopAddr;
5020     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5021                             DAG.getConstant(16, DL, PtrVT));
5022 
5023     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5024     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5025                         DAG.getConstant(FPRSize, DL, PtrVT));
5026 
5027     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5028                                   MachinePointerInfo(SV, 16),
5029                                   /* Alignment = */ 8));
5030   }
5031 
5032   // int __gr_offs at offset 24
5033   SDValue GROffsAddr =
5034       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5035   MemOps.push_back(DAG.getStore(
5036       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5037       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5038 
5039   // int __vr_offs at offset 28
5040   SDValue VROffsAddr =
5041       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5042   MemOps.push_back(DAG.getStore(
5043       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5044       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5045 
5046   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5047 }
5048 
5049 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5050                                             SelectionDAG &DAG) const {
5051   MachineFunction &MF = DAG.getMachineFunction();
5052 
5053   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5054     return LowerWin64_VASTART(Op, DAG);
5055   else if (Subtarget->isTargetDarwin())
5056     return LowerDarwin_VASTART(Op, DAG);
5057   else
5058     return LowerAAPCS_VASTART(Op, DAG);
5059 }
5060 
5061 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5062                                            SelectionDAG &DAG) const {
5063   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5064   // pointer.
5065   SDLoc DL(Op);
5066   unsigned VaListSize =
5067       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
5068   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5069   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5070 
5071   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5072                        Op.getOperand(2),
5073                        DAG.getConstant(VaListSize, DL, MVT::i32),
5074                        8, false, false, false, MachinePointerInfo(DestSV),
5075                        MachinePointerInfo(SrcSV));
5076 }
5077 
5078 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5079   assert(Subtarget->isTargetDarwin() &&
5080          "automatic va_arg instruction only works on Darwin");
5081 
5082   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5083   EVT VT = Op.getValueType();
5084   SDLoc DL(Op);
5085   SDValue Chain = Op.getOperand(0);
5086   SDValue Addr = Op.getOperand(1);
5087   unsigned Align = Op.getConstantOperandVal(3);
5088   auto PtrVT = getPointerTy(DAG.getDataLayout());
5089 
5090   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
5091   Chain = VAList.getValue(1);
5092 
5093   if (Align > 8) {
5094     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5095     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5096                          DAG.getConstant(Align - 1, DL, PtrVT));
5097     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5098                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5099   }
5100 
5101   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5102   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5103 
5104   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5105   // up to 64 bits.  At the very least, we have to increase the striding of the
5106   // vaargs list to match this, and for FP values we need to introduce
5107   // FP_ROUND nodes as well.
5108   if (VT.isInteger() && !VT.isVector())
5109     ArgSize = 8;
5110   bool NeedFPTrunc = false;
5111   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5112     ArgSize = 8;
5113     NeedFPTrunc = true;
5114   }
5115 
5116   // Increment the pointer, VAList, to the next vaarg
5117   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5118                                DAG.getConstant(ArgSize, DL, PtrVT));
5119   // Store the incremented VAList to the legalized pointer
5120   SDValue APStore =
5121       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5122 
5123   // Load the actual argument out of the pointer VAList
5124   if (NeedFPTrunc) {
5125     // Load the value as an f64.
5126     SDValue WideFP =
5127         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5128     // Round the value down to an f32.
5129     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5130                                    DAG.getIntPtrConstant(1, DL));
5131     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5132     // Merge the rounded value with the chain output of the load.
5133     return DAG.getMergeValues(Ops, DL);
5134   }
5135 
5136   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5137 }
5138 
5139 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5140                                               SelectionDAG &DAG) const {
5141   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5142   MFI.setFrameAddressIsTaken(true);
5143 
5144   EVT VT = Op.getValueType();
5145   SDLoc DL(Op);
5146   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5147   SDValue FrameAddr =
5148       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5149   while (Depth--)
5150     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5151                             MachinePointerInfo());
5152   return FrameAddr;
5153 }
5154 
5155 // FIXME? Maybe this could be a TableGen attribute on some registers and
5156 // this table could be generated automatically from RegInfo.
5157 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5158                                                   SelectionDAG &DAG) const {
5159   unsigned Reg = StringSwitch<unsigned>(RegName)
5160                        .Case("sp", AArch64::SP)
5161                        .Case("x1", AArch64::X1)
5162                        .Case("w1", AArch64::W1)
5163                        .Case("x2", AArch64::X2)
5164                        .Case("w2", AArch64::W2)
5165                        .Case("x3", AArch64::X3)
5166                        .Case("w3", AArch64::W3)
5167                        .Case("x4", AArch64::X4)
5168                        .Case("w4", AArch64::W4)
5169                        .Case("x5", AArch64::X5)
5170                        .Case("w5", AArch64::W5)
5171                        .Case("x6", AArch64::X6)
5172                        .Case("w6", AArch64::W6)
5173                        .Case("x7", AArch64::X7)
5174                        .Case("w7", AArch64::W7)
5175                        .Case("x18", AArch64::X18)
5176                        .Case("w18", AArch64::W18)
5177                        .Case("x20", AArch64::X20)
5178                        .Case("w20", AArch64::W20)
5179                        .Default(0);
5180   if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5181       !Subtarget->isXRegisterReserved(1)) ||
5182       ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5183       !Subtarget->isXRegisterReserved(2)) ||
5184       ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5185       !Subtarget->isXRegisterReserved(3)) ||
5186       ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5187       !Subtarget->isXRegisterReserved(4)) ||
5188       ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5189       !Subtarget->isXRegisterReserved(5)) ||
5190       ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5191       !Subtarget->isXRegisterReserved(6)) ||
5192       ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5193       !Subtarget->isXRegisterReserved(7)) ||
5194       ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5195       !Subtarget->isXRegisterReserved(18)) ||
5196       ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
5197       !Subtarget->isXRegisterReserved(20)))
5198     Reg = 0;
5199   if (Reg)
5200     return Reg;
5201   report_fatal_error(Twine("Invalid register name \""
5202                               + StringRef(RegName)  + "\"."));
5203 }
5204 
5205 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5206                                                SelectionDAG &DAG) const {
5207   MachineFunction &MF = DAG.getMachineFunction();
5208   MachineFrameInfo &MFI = MF.getFrameInfo();
5209   MFI.setReturnAddressIsTaken(true);
5210 
5211   EVT VT = Op.getValueType();
5212   SDLoc DL(Op);
5213   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5214   if (Depth) {
5215     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5216     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5217     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5218                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5219                        MachinePointerInfo());
5220   }
5221 
5222   // Return LR, which contains the return address. Mark it an implicit live-in.
5223   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5224   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5225 }
5226 
5227 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5228 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5229 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5230                                                     SelectionDAG &DAG) const {
5231   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5232   EVT VT = Op.getValueType();
5233   unsigned VTBits = VT.getSizeInBits();
5234   SDLoc dl(Op);
5235   SDValue ShOpLo = Op.getOperand(0);
5236   SDValue ShOpHi = Op.getOperand(1);
5237   SDValue ShAmt = Op.getOperand(2);
5238   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5239 
5240   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5241 
5242   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5243                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5244   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5245 
5246   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5247   // is "undef". We wanted 0, so CSEL it directly.
5248   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5249                                ISD::SETEQ, dl, DAG);
5250   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5251   HiBitsForLo =
5252       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5253                   HiBitsForLo, CCVal, Cmp);
5254 
5255   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5256                                    DAG.getConstant(VTBits, dl, MVT::i64));
5257 
5258   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5259   SDValue LoForNormalShift =
5260       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5261 
5262   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5263                        dl, DAG);
5264   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5265   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5266   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5267                            LoForNormalShift, CCVal, Cmp);
5268 
5269   // AArch64 shifts larger than the register width are wrapped rather than
5270   // clamped, so we can't just emit "hi >> x".
5271   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5272   SDValue HiForBigShift =
5273       Opc == ISD::SRA
5274           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5275                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5276           : DAG.getConstant(0, dl, VT);
5277   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5278                            HiForNormalShift, CCVal, Cmp);
5279 
5280   SDValue Ops[2] = { Lo, Hi };
5281   return DAG.getMergeValues(Ops, dl);
5282 }
5283 
5284 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5285 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5286 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5287                                                    SelectionDAG &DAG) const {
5288   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5289   EVT VT = Op.getValueType();
5290   unsigned VTBits = VT.getSizeInBits();
5291   SDLoc dl(Op);
5292   SDValue ShOpLo = Op.getOperand(0);
5293   SDValue ShOpHi = Op.getOperand(1);
5294   SDValue ShAmt = Op.getOperand(2);
5295 
5296   assert(Op.getOpcode() == ISD::SHL_PARTS);
5297   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5298                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5299   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5300 
5301   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5302   // is "undef". We wanted 0, so CSEL it directly.
5303   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5304                                ISD::SETEQ, dl, DAG);
5305   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5306   LoBitsForHi =
5307       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5308                   LoBitsForHi, CCVal, Cmp);
5309 
5310   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5311                                    DAG.getConstant(VTBits, dl, MVT::i64));
5312   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5313   SDValue HiForNormalShift =
5314       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5315 
5316   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5317 
5318   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5319                        dl, DAG);
5320   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5321   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5322                            HiForNormalShift, CCVal, Cmp);
5323 
5324   // AArch64 shifts of larger than register sizes are wrapped rather than
5325   // clamped, so we can't just emit "lo << a" if a is too big.
5326   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5327   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5328   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5329                            LoForNormalShift, CCVal, Cmp);
5330 
5331   SDValue Ops[2] = { Lo, Hi };
5332   return DAG.getMergeValues(Ops, dl);
5333 }
5334 
5335 bool AArch64TargetLowering::isOffsetFoldingLegal(
5336     const GlobalAddressSDNode *GA) const {
5337   // Offsets are folded in the DAG combine rather than here so that we can
5338   // intelligently choose an offset based on the uses.
5339   return false;
5340 }
5341 
5342 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5343   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
5344   // FIXME: We should be able to handle f128 as well with a clever lowering.
5345   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
5346                           (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
5347     LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString() << " imm value: 0\n");
5348     return true;
5349   }
5350 
5351   bool IsLegal = false;
5352   SmallString<128> ImmStrVal;
5353   Imm.toString(ImmStrVal);
5354 
5355   if (VT == MVT::f64)
5356     IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
5357   else if (VT == MVT::f32)
5358     IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
5359   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5360     IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
5361 
5362   if (IsLegal) {
5363     LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString()
5364                       << " imm value: " << ImmStrVal << "\n");
5365     return true;
5366   }
5367 
5368   LLVM_DEBUG(dbgs() << "Illegal " << VT.getEVTString()
5369                     << " imm value: " << ImmStrVal << "\n");
5370   return false;
5371 }
5372 
5373 //===----------------------------------------------------------------------===//
5374 //                          AArch64 Optimization Hooks
5375 //===----------------------------------------------------------------------===//
5376 
5377 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5378                            SDValue Operand, SelectionDAG &DAG,
5379                            int &ExtraSteps) {
5380   EVT VT = Operand.getValueType();
5381   if (ST->hasNEON() &&
5382       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5383        VT == MVT::f32 || VT == MVT::v1f32 ||
5384        VT == MVT::v2f32 || VT == MVT::v4f32)) {
5385     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5386       // For the reciprocal estimates, convergence is quadratic, so the number
5387       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
5388       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
5389       // the result for float (23 mantissa bits) is 2 and for double (52
5390       // mantissa bits) is 3.
5391       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5392 
5393     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5394   }
5395 
5396   return SDValue();
5397 }
5398 
5399 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5400                                                SelectionDAG &DAG, int Enabled,
5401                                                int &ExtraSteps,
5402                                                bool &UseOneConst,
5403                                                bool Reciprocal) const {
5404   if (Enabled == ReciprocalEstimate::Enabled ||
5405       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5406     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5407                                        DAG, ExtraSteps)) {
5408       SDLoc DL(Operand);
5409       EVT VT = Operand.getValueType();
5410 
5411       SDNodeFlags Flags;
5412       Flags.setAllowReassociation(true);
5413 
5414       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5415       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5416       for (int i = ExtraSteps; i > 0; --i) {
5417         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5418                                    Flags);
5419         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5420         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5421       }
5422       if (!Reciprocal) {
5423         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5424                                       VT);
5425         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5426         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5427 
5428         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5429         // Correct the result if the operand is 0.0.
5430         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5431                                VT, Eq, Operand, Estimate);
5432       }
5433 
5434       ExtraSteps = 0;
5435       return Estimate;
5436     }
5437 
5438   return SDValue();
5439 }
5440 
5441 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5442                                                 SelectionDAG &DAG, int Enabled,
5443                                                 int &ExtraSteps) const {
5444   if (Enabled == ReciprocalEstimate::Enabled)
5445     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5446                                        DAG, ExtraSteps)) {
5447       SDLoc DL(Operand);
5448       EVT VT = Operand.getValueType();
5449 
5450       SDNodeFlags Flags;
5451       Flags.setAllowReassociation(true);
5452 
5453       // Newton reciprocal iteration: E * (2 - X * E)
5454       // AArch64 reciprocal iteration instruction: (2 - M * N)
5455       for (int i = ExtraSteps; i > 0; --i) {
5456         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5457                                    Estimate, Flags);
5458         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5459       }
5460 
5461       ExtraSteps = 0;
5462       return Estimate;
5463     }
5464 
5465   return SDValue();
5466 }
5467 
5468 //===----------------------------------------------------------------------===//
5469 //                          AArch64 Inline Assembly Support
5470 //===----------------------------------------------------------------------===//
5471 
5472 // Table of Constraints
5473 // TODO: This is the current set of constraints supported by ARM for the
5474 // compiler, not all of them may make sense.
5475 //
5476 // r - A general register
5477 // w - An FP/SIMD register of some size in the range v0-v31
5478 // x - An FP/SIMD register of some size in the range v0-v15
5479 // I - Constant that can be used with an ADD instruction
5480 // J - Constant that can be used with a SUB instruction
5481 // K - Constant that can be used with a 32-bit logical instruction
5482 // L - Constant that can be used with a 64-bit logical instruction
5483 // M - Constant that can be used as a 32-bit MOV immediate
5484 // N - Constant that can be used as a 64-bit MOV immediate
5485 // Q - A memory reference with base register and no offset
5486 // S - A symbolic address
5487 // Y - Floating point constant zero
5488 // Z - Integer constant zero
5489 //
5490 //   Note that general register operands will be output using their 64-bit x
5491 // register name, whatever the size of the variable, unless the asm operand
5492 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5493 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5494 // %q modifier.
5495 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5496   // At this point, we have to lower this constraint to something else, so we
5497   // lower it to an "r" or "w". However, by doing this we will force the result
5498   // to be in register, while the X constraint is much more permissive.
5499   //
5500   // Although we are correct (we are free to emit anything, without
5501   // constraints), we might break use cases that would expect us to be more
5502   // efficient and emit something else.
5503   if (!Subtarget->hasFPARMv8())
5504     return "r";
5505 
5506   if (ConstraintVT.isFloatingPoint())
5507     return "w";
5508 
5509   if (ConstraintVT.isVector() &&
5510      (ConstraintVT.getSizeInBits() == 64 ||
5511       ConstraintVT.getSizeInBits() == 128))
5512     return "w";
5513 
5514   return "r";
5515 }
5516 
5517 /// getConstraintType - Given a constraint letter, return the type of
5518 /// constraint it is for this target.
5519 AArch64TargetLowering::ConstraintType
5520 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5521   if (Constraint.size() == 1) {
5522     switch (Constraint[0]) {
5523     default:
5524       break;
5525     case 'z':
5526       return C_Other;
5527     case 'x':
5528     case 'w':
5529       return C_RegisterClass;
5530     // An address with a single base register. Due to the way we
5531     // currently handle addresses it is the same as 'r'.
5532     case 'Q':
5533       return C_Memory;
5534     case 'S': // A symbolic address
5535       return C_Other;
5536     }
5537   }
5538   return TargetLowering::getConstraintType(Constraint);
5539 }
5540 
5541 /// Examine constraint type and operand type and determine a weight value.
5542 /// This object must already have been set up with the operand type
5543 /// and the current alternative constraint selected.
5544 TargetLowering::ConstraintWeight
5545 AArch64TargetLowering::getSingleConstraintMatchWeight(
5546     AsmOperandInfo &info, const char *constraint) const {
5547   ConstraintWeight weight = CW_Invalid;
5548   Value *CallOperandVal = info.CallOperandVal;
5549   // If we don't have a value, we can't do a match,
5550   // but allow it at the lowest weight.
5551   if (!CallOperandVal)
5552     return CW_Default;
5553   Type *type = CallOperandVal->getType();
5554   // Look at the constraint type.
5555   switch (*constraint) {
5556   default:
5557     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5558     break;
5559   case 'x':
5560   case 'w':
5561     if (type->isFloatingPointTy() || type->isVectorTy())
5562       weight = CW_Register;
5563     break;
5564   case 'z':
5565     weight = CW_Constant;
5566     break;
5567   }
5568   return weight;
5569 }
5570 
5571 std::pair<unsigned, const TargetRegisterClass *>
5572 AArch64TargetLowering::getRegForInlineAsmConstraint(
5573     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5574   if (Constraint.size() == 1) {
5575     switch (Constraint[0]) {
5576     case 'r':
5577       if (VT.getSizeInBits() == 64)
5578         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5579       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5580     case 'w':
5581       if (!Subtarget->hasFPARMv8())
5582         break;
5583       if (VT.getSizeInBits() == 16)
5584         return std::make_pair(0U, &AArch64::FPR16RegClass);
5585       if (VT.getSizeInBits() == 32)
5586         return std::make_pair(0U, &AArch64::FPR32RegClass);
5587       if (VT.getSizeInBits() == 64)
5588         return std::make_pair(0U, &AArch64::FPR64RegClass);
5589       if (VT.getSizeInBits() == 128)
5590         return std::make_pair(0U, &AArch64::FPR128RegClass);
5591       break;
5592     // The instructions that this constraint is designed for can
5593     // only take 128-bit registers so just use that regclass.
5594     case 'x':
5595       if (!Subtarget->hasFPARMv8())
5596         break;
5597       if (VT.getSizeInBits() == 128)
5598         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5599       break;
5600     }
5601   }
5602   if (StringRef("{cc}").equals_lower(Constraint))
5603     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5604 
5605   // Use the default implementation in TargetLowering to convert the register
5606   // constraint into a member of a register class.
5607   std::pair<unsigned, const TargetRegisterClass *> Res;
5608   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5609 
5610   // Not found as a standard register?
5611   if (!Res.second) {
5612     unsigned Size = Constraint.size();
5613     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5614         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5615       int RegNo;
5616       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5617       if (!Failed && RegNo >= 0 && RegNo <= 31) {
5618         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5619         // By default we'll emit v0-v31 for this unless there's a modifier where
5620         // we'll emit the correct register as well.
5621         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5622           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5623           Res.second = &AArch64::FPR64RegClass;
5624         } else {
5625           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5626           Res.second = &AArch64::FPR128RegClass;
5627         }
5628       }
5629     }
5630   }
5631 
5632   if (Res.second && !Subtarget->hasFPARMv8() &&
5633       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5634       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5635     return std::make_pair(0U, nullptr);
5636 
5637   return Res;
5638 }
5639 
5640 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5641 /// vector.  If it is invalid, don't add anything to Ops.
5642 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5643     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5644     SelectionDAG &DAG) const {
5645   SDValue Result;
5646 
5647   // Currently only support length 1 constraints.
5648   if (Constraint.length() != 1)
5649     return;
5650 
5651   char ConstraintLetter = Constraint[0];
5652   switch (ConstraintLetter) {
5653   default:
5654     break;
5655 
5656   // This set of constraints deal with valid constants for various instructions.
5657   // Validate and return a target constant for them if we can.
5658   case 'z': {
5659     // 'z' maps to xzr or wzr so it needs an input of 0.
5660     if (!isNullConstant(Op))
5661       return;
5662 
5663     if (Op.getValueType() == MVT::i64)
5664       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5665     else
5666       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5667     break;
5668   }
5669   case 'S': {
5670     // An absolute symbolic address or label reference.
5671     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5672       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5673                                           GA->getValueType(0));
5674     } else if (const BlockAddressSDNode *BA =
5675                    dyn_cast<BlockAddressSDNode>(Op)) {
5676       Result =
5677           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5678     } else if (const ExternalSymbolSDNode *ES =
5679                    dyn_cast<ExternalSymbolSDNode>(Op)) {
5680       Result =
5681           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5682     } else
5683       return;
5684     break;
5685   }
5686 
5687   case 'I':
5688   case 'J':
5689   case 'K':
5690   case 'L':
5691   case 'M':
5692   case 'N':
5693     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5694     if (!C)
5695       return;
5696 
5697     // Grab the value and do some validation.
5698     uint64_t CVal = C->getZExtValue();
5699     switch (ConstraintLetter) {
5700     // The I constraint applies only to simple ADD or SUB immediate operands:
5701     // i.e. 0 to 4095 with optional shift by 12
5702     // The J constraint applies only to ADD or SUB immediates that would be
5703     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5704     // instruction [or vice versa], in other words -1 to -4095 with optional
5705     // left shift by 12.
5706     case 'I':
5707       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5708         break;
5709       return;
5710     case 'J': {
5711       uint64_t NVal = -C->getSExtValue();
5712       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5713         CVal = C->getSExtValue();
5714         break;
5715       }
5716       return;
5717     }
5718     // The K and L constraints apply *only* to logical immediates, including
5719     // what used to be the MOVI alias for ORR (though the MOVI alias has now
5720     // been removed and MOV should be used). So these constraints have to
5721     // distinguish between bit patterns that are valid 32-bit or 64-bit
5722     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5723     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5724     // versa.
5725     case 'K':
5726       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5727         break;
5728       return;
5729     case 'L':
5730       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5731         break;
5732       return;
5733     // The M and N constraints are a superset of K and L respectively, for use
5734     // with the MOV (immediate) alias. As well as the logical immediates they
5735     // also match 32 or 64-bit immediates that can be loaded either using a
5736     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5737     // (M) or 64-bit 0x1234000000000000 (N) etc.
5738     // As a note some of this code is liberally stolen from the asm parser.
5739     case 'M': {
5740       if (!isUInt<32>(CVal))
5741         return;
5742       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5743         break;
5744       if ((CVal & 0xFFFF) == CVal)
5745         break;
5746       if ((CVal & 0xFFFF0000ULL) == CVal)
5747         break;
5748       uint64_t NCVal = ~(uint32_t)CVal;
5749       if ((NCVal & 0xFFFFULL) == NCVal)
5750         break;
5751       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5752         break;
5753       return;
5754     }
5755     case 'N': {
5756       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5757         break;
5758       if ((CVal & 0xFFFFULL) == CVal)
5759         break;
5760       if ((CVal & 0xFFFF0000ULL) == CVal)
5761         break;
5762       if ((CVal & 0xFFFF00000000ULL) == CVal)
5763         break;
5764       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5765         break;
5766       uint64_t NCVal = ~CVal;
5767       if ((NCVal & 0xFFFFULL) == NCVal)
5768         break;
5769       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5770         break;
5771       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5772         break;
5773       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5774         break;
5775       return;
5776     }
5777     default:
5778       return;
5779     }
5780 
5781     // All assembler immediates are 64-bit integers.
5782     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5783     break;
5784   }
5785 
5786   if (Result.getNode()) {
5787     Ops.push_back(Result);
5788     return;
5789   }
5790 
5791   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5792 }
5793 
5794 //===----------------------------------------------------------------------===//
5795 //                     AArch64 Advanced SIMD Support
5796 //===----------------------------------------------------------------------===//
5797 
5798 /// WidenVector - Given a value in the V64 register class, produce the
5799 /// equivalent value in the V128 register class.
5800 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5801   EVT VT = V64Reg.getValueType();
5802   unsigned NarrowSize = VT.getVectorNumElements();
5803   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5804   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5805   SDLoc DL(V64Reg);
5806 
5807   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5808                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5809 }
5810 
5811 /// getExtFactor - Determine the adjustment factor for the position when
5812 /// generating an "extract from vector registers" instruction.
5813 static unsigned getExtFactor(SDValue &V) {
5814   EVT EltType = V.getValueType().getVectorElementType();
5815   return EltType.getSizeInBits() / 8;
5816 }
5817 
5818 /// NarrowVector - Given a value in the V128 register class, produce the
5819 /// equivalent value in the V64 register class.
5820 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5821   EVT VT = V128Reg.getValueType();
5822   unsigned WideSize = VT.getVectorNumElements();
5823   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5824   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5825   SDLoc DL(V128Reg);
5826 
5827   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5828 }
5829 
5830 // Gather data to see if the operation can be modelled as a
5831 // shuffle in combination with VEXTs.
5832 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5833                                                   SelectionDAG &DAG) const {
5834   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5835   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
5836   SDLoc dl(Op);
5837   EVT VT = Op.getValueType();
5838   unsigned NumElts = VT.getVectorNumElements();
5839 
5840   struct ShuffleSourceInfo {
5841     SDValue Vec;
5842     unsigned MinElt;
5843     unsigned MaxElt;
5844 
5845     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5846     // be compatible with the shuffle we intend to construct. As a result
5847     // ShuffleVec will be some sliding window into the original Vec.
5848     SDValue ShuffleVec;
5849 
5850     // Code should guarantee that element i in Vec starts at element "WindowBase
5851     // + i * WindowScale in ShuffleVec".
5852     int WindowBase;
5853     int WindowScale;
5854 
5855     ShuffleSourceInfo(SDValue Vec)
5856       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5857           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5858 
5859     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5860   };
5861 
5862   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5863   // node.
5864   SmallVector<ShuffleSourceInfo, 2> Sources;
5865   for (unsigned i = 0; i < NumElts; ++i) {
5866     SDValue V = Op.getOperand(i);
5867     if (V.isUndef())
5868       continue;
5869     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5870              !isa<ConstantSDNode>(V.getOperand(1))) {
5871       LLVM_DEBUG(
5872           dbgs() << "Reshuffle failed: "
5873                     "a shuffle can only come from building a vector from "
5874                     "various elements of other vectors, provided their "
5875                     "indices are constant\n");
5876       return SDValue();
5877     }
5878 
5879     // Add this element source to the list if it's not already there.
5880     SDValue SourceVec = V.getOperand(0);
5881     auto Source = find(Sources, SourceVec);
5882     if (Source == Sources.end())
5883       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5884 
5885     // Update the minimum and maximum lane number seen.
5886     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5887     Source->MinElt = std::min(Source->MinElt, EltNo);
5888     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5889   }
5890 
5891   if (Sources.size() > 2) {
5892     LLVM_DEBUG(
5893         dbgs() << "Reshuffle failed: currently only do something sane when at "
5894                   "most two source vectors are involved\n");
5895     return SDValue();
5896   }
5897 
5898   // Find out the smallest element size among result and two sources, and use
5899   // it as element size to build the shuffle_vector.
5900   EVT SmallestEltTy = VT.getVectorElementType();
5901   for (auto &Source : Sources) {
5902     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5903     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5904       SmallestEltTy = SrcEltTy;
5905     }
5906   }
5907   unsigned ResMultiplier =
5908       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5909   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5910   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5911 
5912   // If the source vector is too wide or too narrow, we may nevertheless be able
5913   // to construct a compatible shuffle either by concatenating it with UNDEF or
5914   // extracting a suitable range of elements.
5915   for (auto &Src : Sources) {
5916     EVT SrcVT = Src.ShuffleVec.getValueType();
5917 
5918     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5919       continue;
5920 
5921     // This stage of the search produces a source with the same element type as
5922     // the original, but with a total width matching the BUILD_VECTOR output.
5923     EVT EltVT = SrcVT.getVectorElementType();
5924     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5925     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5926 
5927     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5928       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5929       // We can pad out the smaller vector for free, so if it's part of a
5930       // shuffle...
5931       Src.ShuffleVec =
5932           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5933                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5934       continue;
5935     }
5936 
5937     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5938 
5939     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5940       LLVM_DEBUG(
5941           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
5942       return SDValue();
5943     }
5944 
5945     if (Src.MinElt >= NumSrcElts) {
5946       // The extraction can just take the second half
5947       Src.ShuffleVec =
5948           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5949                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5950       Src.WindowBase = -NumSrcElts;
5951     } else if (Src.MaxElt < NumSrcElts) {
5952       // The extraction can just take the first half
5953       Src.ShuffleVec =
5954           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5955                       DAG.getConstant(0, dl, MVT::i64));
5956     } else {
5957       // An actual VEXT is needed
5958       SDValue VEXTSrc1 =
5959           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5960                       DAG.getConstant(0, dl, MVT::i64));
5961       SDValue VEXTSrc2 =
5962           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5963                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5964       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5965 
5966       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5967                                    VEXTSrc2,
5968                                    DAG.getConstant(Imm, dl, MVT::i32));
5969       Src.WindowBase = -Src.MinElt;
5970     }
5971   }
5972 
5973   // Another possible incompatibility occurs from the vector element types. We
5974   // can fix this by bitcasting the source vectors to the same type we intend
5975   // for the shuffle.
5976   for (auto &Src : Sources) {
5977     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5978     if (SrcEltTy == SmallestEltTy)
5979       continue;
5980     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5981     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5982     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5983     Src.WindowBase *= Src.WindowScale;
5984   }
5985 
5986   // Final sanity check before we try to actually produce a shuffle.
5987   LLVM_DEBUG(for (auto Src
5988                   : Sources)
5989                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
5990 
5991   // The stars all align, our next step is to produce the mask for the shuffle.
5992   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5993   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5994   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5995     SDValue Entry = Op.getOperand(i);
5996     if (Entry.isUndef())
5997       continue;
5998 
5999     auto Src = find(Sources, Entry.getOperand(0));
6000     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6001 
6002     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6003     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6004     // segment.
6005     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6006     int BitsDefined =
6007         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6008     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6009 
6010     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6011     // starting at the appropriate offset.
6012     int *LaneMask = &Mask[i * ResMultiplier];
6013 
6014     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6015     ExtractBase += NumElts * (Src - Sources.begin());
6016     for (int j = 0; j < LanesDefined; ++j)
6017       LaneMask[j] = ExtractBase + j;
6018   }
6019 
6020   // Final check before we try to produce nonsense...
6021   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6022     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6023     return SDValue();
6024   }
6025 
6026   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6027   for (unsigned i = 0; i < Sources.size(); ++i)
6028     ShuffleOps[i] = Sources[i].ShuffleVec;
6029 
6030   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6031                                          ShuffleOps[1], Mask);
6032   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6033 
6034   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6035              dbgs() << "Reshuffle, creating node: "; V.dump(););
6036 
6037   return V;
6038 }
6039 
6040 // check if an EXT instruction can handle the shuffle mask when the
6041 // vector sources of the shuffle are the same.
6042 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6043   unsigned NumElts = VT.getVectorNumElements();
6044 
6045   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6046   if (M[0] < 0)
6047     return false;
6048 
6049   Imm = M[0];
6050 
6051   // If this is a VEXT shuffle, the immediate value is the index of the first
6052   // element.  The other shuffle indices must be the successive elements after
6053   // the first one.
6054   unsigned ExpectedElt = Imm;
6055   for (unsigned i = 1; i < NumElts; ++i) {
6056     // Increment the expected index.  If it wraps around, just follow it
6057     // back to index zero and keep going.
6058     ++ExpectedElt;
6059     if (ExpectedElt == NumElts)
6060       ExpectedElt = 0;
6061 
6062     if (M[i] < 0)
6063       continue; // ignore UNDEF indices
6064     if (ExpectedElt != static_cast<unsigned>(M[i]))
6065       return false;
6066   }
6067 
6068   return true;
6069 }
6070 
6071 // check if an EXT instruction can handle the shuffle mask when the
6072 // vector sources of the shuffle are different.
6073 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6074                       unsigned &Imm) {
6075   // Look for the first non-undef element.
6076   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6077 
6078   // Benefit form APInt to handle overflow when calculating expected element.
6079   unsigned NumElts = VT.getVectorNumElements();
6080   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6081   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6082   // The following shuffle indices must be the successive elements after the
6083   // first real element.
6084   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6085       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6086   if (FirstWrongElt != M.end())
6087     return false;
6088 
6089   // The index of an EXT is the first element if it is not UNDEF.
6090   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6091   // value of the first element.  E.g.
6092   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6093   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6094   // ExpectedElt is the last mask index plus 1.
6095   Imm = ExpectedElt.getZExtValue();
6096 
6097   // There are two difference cases requiring to reverse input vectors.
6098   // For example, for vector <4 x i32> we have the following cases,
6099   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6100   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6101   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6102   // to reverse two input vectors.
6103   if (Imm < NumElts)
6104     ReverseEXT = true;
6105   else
6106     Imm -= NumElts;
6107 
6108   return true;
6109 }
6110 
6111 /// isREVMask - Check if a vector shuffle corresponds to a REV
6112 /// instruction with the specified blocksize.  (The order of the elements
6113 /// within each block of the vector is reversed.)
6114 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6115   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6116          "Only possible block sizes for REV are: 16, 32, 64");
6117 
6118   unsigned EltSz = VT.getScalarSizeInBits();
6119   if (EltSz == 64)
6120     return false;
6121 
6122   unsigned NumElts = VT.getVectorNumElements();
6123   unsigned BlockElts = M[0] + 1;
6124   // If the first shuffle index is UNDEF, be optimistic.
6125   if (M[0] < 0)
6126     BlockElts = BlockSize / EltSz;
6127 
6128   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6129     return false;
6130 
6131   for (unsigned i = 0; i < NumElts; ++i) {
6132     if (M[i] < 0)
6133       continue; // ignore UNDEF indices
6134     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6135       return false;
6136   }
6137 
6138   return true;
6139 }
6140 
6141 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6142   unsigned NumElts = VT.getVectorNumElements();
6143   WhichResult = (M[0] == 0 ? 0 : 1);
6144   unsigned Idx = WhichResult * NumElts / 2;
6145   for (unsigned i = 0; i != NumElts; i += 2) {
6146     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6147         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6148       return false;
6149     Idx += 1;
6150   }
6151 
6152   return true;
6153 }
6154 
6155 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6156   unsigned NumElts = VT.getVectorNumElements();
6157   WhichResult = (M[0] == 0 ? 0 : 1);
6158   for (unsigned i = 0; i != NumElts; ++i) {
6159     if (M[i] < 0)
6160       continue; // ignore UNDEF indices
6161     if ((unsigned)M[i] != 2 * i + WhichResult)
6162       return false;
6163   }
6164 
6165   return true;
6166 }
6167 
6168 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6169   unsigned NumElts = VT.getVectorNumElements();
6170   WhichResult = (M[0] == 0 ? 0 : 1);
6171   for (unsigned i = 0; i < NumElts; i += 2) {
6172     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6173         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6174       return false;
6175   }
6176   return true;
6177 }
6178 
6179 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6180 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6181 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6182 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6183   unsigned NumElts = VT.getVectorNumElements();
6184   WhichResult = (M[0] == 0 ? 0 : 1);
6185   unsigned Idx = WhichResult * NumElts / 2;
6186   for (unsigned i = 0; i != NumElts; i += 2) {
6187     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6188         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6189       return false;
6190     Idx += 1;
6191   }
6192 
6193   return true;
6194 }
6195 
6196 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6197 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6198 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6199 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6200   unsigned Half = VT.getVectorNumElements() / 2;
6201   WhichResult = (M[0] == 0 ? 0 : 1);
6202   for (unsigned j = 0; j != 2; ++j) {
6203     unsigned Idx = WhichResult;
6204     for (unsigned i = 0; i != Half; ++i) {
6205       int MIdx = M[i + j * Half];
6206       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6207         return false;
6208       Idx += 2;
6209     }
6210   }
6211 
6212   return true;
6213 }
6214 
6215 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6216 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6217 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6218 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6219   unsigned NumElts = VT.getVectorNumElements();
6220   WhichResult = (M[0] == 0 ? 0 : 1);
6221   for (unsigned i = 0; i < NumElts; i += 2) {
6222     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6223         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6224       return false;
6225   }
6226   return true;
6227 }
6228 
6229 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6230                       bool &DstIsLeft, int &Anomaly) {
6231   if (M.size() != static_cast<size_t>(NumInputElements))
6232     return false;
6233 
6234   int NumLHSMatch = 0, NumRHSMatch = 0;
6235   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6236 
6237   for (int i = 0; i < NumInputElements; ++i) {
6238     if (M[i] == -1) {
6239       ++NumLHSMatch;
6240       ++NumRHSMatch;
6241       continue;
6242     }
6243 
6244     if (M[i] == i)
6245       ++NumLHSMatch;
6246     else
6247       LastLHSMismatch = i;
6248 
6249     if (M[i] == i + NumInputElements)
6250       ++NumRHSMatch;
6251     else
6252       LastRHSMismatch = i;
6253   }
6254 
6255   if (NumLHSMatch == NumInputElements - 1) {
6256     DstIsLeft = true;
6257     Anomaly = LastLHSMismatch;
6258     return true;
6259   } else if (NumRHSMatch == NumInputElements - 1) {
6260     DstIsLeft = false;
6261     Anomaly = LastRHSMismatch;
6262     return true;
6263   }
6264 
6265   return false;
6266 }
6267 
6268 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6269   if (VT.getSizeInBits() != 128)
6270     return false;
6271 
6272   unsigned NumElts = VT.getVectorNumElements();
6273 
6274   for (int I = 0, E = NumElts / 2; I != E; I++) {
6275     if (Mask[I] != I)
6276       return false;
6277   }
6278 
6279   int Offset = NumElts / 2;
6280   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6281     if (Mask[I] != I + SplitLHS * Offset)
6282       return false;
6283   }
6284 
6285   return true;
6286 }
6287 
6288 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6289   SDLoc DL(Op);
6290   EVT VT = Op.getValueType();
6291   SDValue V0 = Op.getOperand(0);
6292   SDValue V1 = Op.getOperand(1);
6293   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6294 
6295   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6296       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6297     return SDValue();
6298 
6299   bool SplitV0 = V0.getValueSizeInBits() == 128;
6300 
6301   if (!isConcatMask(Mask, VT, SplitV0))
6302     return SDValue();
6303 
6304   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6305                                 VT.getVectorNumElements() / 2);
6306   if (SplitV0) {
6307     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6308                      DAG.getConstant(0, DL, MVT::i64));
6309   }
6310   if (V1.getValueSizeInBits() == 128) {
6311     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6312                      DAG.getConstant(0, DL, MVT::i64));
6313   }
6314   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6315 }
6316 
6317 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6318 /// the specified operations to build the shuffle.
6319 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6320                                       SDValue RHS, SelectionDAG &DAG,
6321                                       const SDLoc &dl) {
6322   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6323   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6324   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6325 
6326   enum {
6327     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6328     OP_VREV,
6329     OP_VDUP0,
6330     OP_VDUP1,
6331     OP_VDUP2,
6332     OP_VDUP3,
6333     OP_VEXT1,
6334     OP_VEXT2,
6335     OP_VEXT3,
6336     OP_VUZPL, // VUZP, left result
6337     OP_VUZPR, // VUZP, right result
6338     OP_VZIPL, // VZIP, left result
6339     OP_VZIPR, // VZIP, right result
6340     OP_VTRNL, // VTRN, left result
6341     OP_VTRNR  // VTRN, right result
6342   };
6343 
6344   if (OpNum == OP_COPY) {
6345     if (LHSID == (1 * 9 + 2) * 9 + 3)
6346       return LHS;
6347     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6348     return RHS;
6349   }
6350 
6351   SDValue OpLHS, OpRHS;
6352   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6353   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6354   EVT VT = OpLHS.getValueType();
6355 
6356   switch (OpNum) {
6357   default:
6358     llvm_unreachable("Unknown shuffle opcode!");
6359   case OP_VREV:
6360     // VREV divides the vector in half and swaps within the half.
6361     if (VT.getVectorElementType() == MVT::i32 ||
6362         VT.getVectorElementType() == MVT::f32)
6363       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6364     // vrev <4 x i16> -> REV32
6365     if (VT.getVectorElementType() == MVT::i16 ||
6366         VT.getVectorElementType() == MVT::f16)
6367       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6368     // vrev <4 x i8> -> REV16
6369     assert(VT.getVectorElementType() == MVT::i8);
6370     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6371   case OP_VDUP0:
6372   case OP_VDUP1:
6373   case OP_VDUP2:
6374   case OP_VDUP3: {
6375     EVT EltTy = VT.getVectorElementType();
6376     unsigned Opcode;
6377     if (EltTy == MVT::i8)
6378       Opcode = AArch64ISD::DUPLANE8;
6379     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6380       Opcode = AArch64ISD::DUPLANE16;
6381     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6382       Opcode = AArch64ISD::DUPLANE32;
6383     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6384       Opcode = AArch64ISD::DUPLANE64;
6385     else
6386       llvm_unreachable("Invalid vector element type?");
6387 
6388     if (VT.getSizeInBits() == 64)
6389       OpLHS = WidenVector(OpLHS, DAG);
6390     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6391     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6392   }
6393   case OP_VEXT1:
6394   case OP_VEXT2:
6395   case OP_VEXT3: {
6396     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6397     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6398                        DAG.getConstant(Imm, dl, MVT::i32));
6399   }
6400   case OP_VUZPL:
6401     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6402                        OpRHS);
6403   case OP_VUZPR:
6404     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6405                        OpRHS);
6406   case OP_VZIPL:
6407     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6408                        OpRHS);
6409   case OP_VZIPR:
6410     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6411                        OpRHS);
6412   case OP_VTRNL:
6413     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6414                        OpRHS);
6415   case OP_VTRNR:
6416     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6417                        OpRHS);
6418   }
6419 }
6420 
6421 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6422                            SelectionDAG &DAG) {
6423   // Check to see if we can use the TBL instruction.
6424   SDValue V1 = Op.getOperand(0);
6425   SDValue V2 = Op.getOperand(1);
6426   SDLoc DL(Op);
6427 
6428   EVT EltVT = Op.getValueType().getVectorElementType();
6429   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6430 
6431   SmallVector<SDValue, 8> TBLMask;
6432   for (int Val : ShuffleMask) {
6433     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6434       unsigned Offset = Byte + Val * BytesPerElt;
6435       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6436     }
6437   }
6438 
6439   MVT IndexVT = MVT::v8i8;
6440   unsigned IndexLen = 8;
6441   if (Op.getValueSizeInBits() == 128) {
6442     IndexVT = MVT::v16i8;
6443     IndexLen = 16;
6444   }
6445 
6446   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6447   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6448 
6449   SDValue Shuffle;
6450   if (V2.getNode()->isUndef()) {
6451     if (IndexLen == 8)
6452       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6453     Shuffle = DAG.getNode(
6454         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6455         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6456         DAG.getBuildVector(IndexVT, DL,
6457                            makeArrayRef(TBLMask.data(), IndexLen)));
6458   } else {
6459     if (IndexLen == 8) {
6460       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6461       Shuffle = DAG.getNode(
6462           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6463           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6464           DAG.getBuildVector(IndexVT, DL,
6465                              makeArrayRef(TBLMask.data(), IndexLen)));
6466     } else {
6467       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6468       // cannot currently represent the register constraints on the input
6469       // table registers.
6470       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6471       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6472       //                   IndexLen));
6473       Shuffle = DAG.getNode(
6474           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6475           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6476           V2Cst, DAG.getBuildVector(IndexVT, DL,
6477                                     makeArrayRef(TBLMask.data(), IndexLen)));
6478     }
6479   }
6480   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6481 }
6482 
6483 static unsigned getDUPLANEOp(EVT EltType) {
6484   if (EltType == MVT::i8)
6485     return AArch64ISD::DUPLANE8;
6486   if (EltType == MVT::i16 || EltType == MVT::f16)
6487     return AArch64ISD::DUPLANE16;
6488   if (EltType == MVT::i32 || EltType == MVT::f32)
6489     return AArch64ISD::DUPLANE32;
6490   if (EltType == MVT::i64 || EltType == MVT::f64)
6491     return AArch64ISD::DUPLANE64;
6492 
6493   llvm_unreachable("Invalid vector element type?");
6494 }
6495 
6496 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6497                                                    SelectionDAG &DAG) const {
6498   SDLoc dl(Op);
6499   EVT VT = Op.getValueType();
6500 
6501   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6502 
6503   // Convert shuffles that are directly supported on NEON to target-specific
6504   // DAG nodes, instead of keeping them as shuffles and matching them again
6505   // during code selection.  This is more efficient and avoids the possibility
6506   // of inconsistencies between legalization and selection.
6507   ArrayRef<int> ShuffleMask = SVN->getMask();
6508 
6509   SDValue V1 = Op.getOperand(0);
6510   SDValue V2 = Op.getOperand(1);
6511 
6512   if (SVN->isSplat()) {
6513     int Lane = SVN->getSplatIndex();
6514     // If this is undef splat, generate it via "just" vdup, if possible.
6515     if (Lane == -1)
6516       Lane = 0;
6517 
6518     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6519       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6520                          V1.getOperand(0));
6521     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6522     // constant. If so, we can just reference the lane's definition directly.
6523     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6524         !isa<ConstantSDNode>(V1.getOperand(Lane)))
6525       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6526 
6527     // Otherwise, duplicate from the lane of the input vector.
6528     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6529 
6530     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6531     // to make a vector of the same size as this SHUFFLE. We can ignore the
6532     // extract entirely, and canonicalise the concat using WidenVector.
6533     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6534       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6535       V1 = V1.getOperand(0);
6536     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6537       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6538       Lane -= Idx * VT.getVectorNumElements() / 2;
6539       V1 = WidenVector(V1.getOperand(Idx), DAG);
6540     } else if (VT.getSizeInBits() == 64)
6541       V1 = WidenVector(V1, DAG);
6542 
6543     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6544   }
6545 
6546   if (isREVMask(ShuffleMask, VT, 64))
6547     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6548   if (isREVMask(ShuffleMask, VT, 32))
6549     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6550   if (isREVMask(ShuffleMask, VT, 16))
6551     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6552 
6553   bool ReverseEXT = false;
6554   unsigned Imm;
6555   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6556     if (ReverseEXT)
6557       std::swap(V1, V2);
6558     Imm *= getExtFactor(V1);
6559     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6560                        DAG.getConstant(Imm, dl, MVT::i32));
6561   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6562     Imm *= getExtFactor(V1);
6563     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6564                        DAG.getConstant(Imm, dl, MVT::i32));
6565   }
6566 
6567   unsigned WhichResult;
6568   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6569     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6570     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6571   }
6572   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6573     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6574     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6575   }
6576   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6577     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6578     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6579   }
6580 
6581   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6582     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6583     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6584   }
6585   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6586     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6587     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6588   }
6589   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6590     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6591     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6592   }
6593 
6594   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6595     return Concat;
6596 
6597   bool DstIsLeft;
6598   int Anomaly;
6599   int NumInputElements = V1.getValueType().getVectorNumElements();
6600   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6601     SDValue DstVec = DstIsLeft ? V1 : V2;
6602     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6603 
6604     SDValue SrcVec = V1;
6605     int SrcLane = ShuffleMask[Anomaly];
6606     if (SrcLane >= NumInputElements) {
6607       SrcVec = V2;
6608       SrcLane -= VT.getVectorNumElements();
6609     }
6610     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6611 
6612     EVT ScalarVT = VT.getVectorElementType();
6613 
6614     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6615       ScalarVT = MVT::i32;
6616 
6617     return DAG.getNode(
6618         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6619         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6620         DstLaneV);
6621   }
6622 
6623   // If the shuffle is not directly supported and it has 4 elements, use
6624   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6625   unsigned NumElts = VT.getVectorNumElements();
6626   if (NumElts == 4) {
6627     unsigned PFIndexes[4];
6628     for (unsigned i = 0; i != 4; ++i) {
6629       if (ShuffleMask[i] < 0)
6630         PFIndexes[i] = 8;
6631       else
6632         PFIndexes[i] = ShuffleMask[i];
6633     }
6634 
6635     // Compute the index in the perfect shuffle table.
6636     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6637                             PFIndexes[2] * 9 + PFIndexes[3];
6638     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6639     unsigned Cost = (PFEntry >> 30);
6640 
6641     if (Cost <= 4)
6642       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6643   }
6644 
6645   return GenerateTBL(Op, ShuffleMask, DAG);
6646 }
6647 
6648 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6649                                APInt &UndefBits) {
6650   EVT VT = BVN->getValueType(0);
6651   APInt SplatBits, SplatUndef;
6652   unsigned SplatBitSize;
6653   bool HasAnyUndefs;
6654   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6655     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6656 
6657     for (unsigned i = 0; i < NumSplats; ++i) {
6658       CnstBits <<= SplatBitSize;
6659       UndefBits <<= SplatBitSize;
6660       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6661       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6662     }
6663 
6664     return true;
6665   }
6666 
6667   return false;
6668 }
6669 
6670 // Try 64-bit splatted SIMD immediate.
6671 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6672                                  const APInt &Bits) {
6673   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6674     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6675     EVT VT = Op.getValueType();
6676     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6677 
6678     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6679       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6680 
6681       SDLoc dl(Op);
6682       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6683                                 DAG.getConstant(Value, dl, MVT::i32));
6684       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6685     }
6686   }
6687 
6688   return SDValue();
6689 }
6690 
6691 // Try 32-bit splatted SIMD immediate.
6692 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6693                                   const APInt &Bits,
6694                                   const SDValue *LHS = nullptr) {
6695   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6696     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6697     EVT VT = Op.getValueType();
6698     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6699     bool isAdvSIMDModImm = false;
6700     uint64_t Shift;
6701 
6702     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6703       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6704       Shift = 0;
6705     }
6706     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6707       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6708       Shift = 8;
6709     }
6710     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6711       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6712       Shift = 16;
6713     }
6714     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6715       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6716       Shift = 24;
6717     }
6718 
6719     if (isAdvSIMDModImm) {
6720       SDLoc dl(Op);
6721       SDValue Mov;
6722 
6723       if (LHS)
6724         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6725                           DAG.getConstant(Value, dl, MVT::i32),
6726                           DAG.getConstant(Shift, dl, MVT::i32));
6727       else
6728         Mov = DAG.getNode(NewOp, dl, MovTy,
6729                           DAG.getConstant(Value, dl, MVT::i32),
6730                           DAG.getConstant(Shift, dl, MVT::i32));
6731 
6732       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6733     }
6734   }
6735 
6736   return SDValue();
6737 }
6738 
6739 // Try 16-bit splatted SIMD immediate.
6740 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6741                                   const APInt &Bits,
6742                                   const SDValue *LHS = nullptr) {
6743   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6744     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6745     EVT VT = Op.getValueType();
6746     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6747     bool isAdvSIMDModImm = false;
6748     uint64_t Shift;
6749 
6750     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6751       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6752       Shift = 0;
6753     }
6754     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6755       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6756       Shift = 8;
6757     }
6758 
6759     if (isAdvSIMDModImm) {
6760       SDLoc dl(Op);
6761       SDValue Mov;
6762 
6763       if (LHS)
6764         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6765                           DAG.getConstant(Value, dl, MVT::i32),
6766                           DAG.getConstant(Shift, dl, MVT::i32));
6767       else
6768         Mov = DAG.getNode(NewOp, dl, MovTy,
6769                           DAG.getConstant(Value, dl, MVT::i32),
6770                           DAG.getConstant(Shift, dl, MVT::i32));
6771 
6772       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6773     }
6774   }
6775 
6776   return SDValue();
6777 }
6778 
6779 // Try 32-bit splatted SIMD immediate with shifted ones.
6780 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6781                                     SelectionDAG &DAG, const APInt &Bits) {
6782   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6783     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6784     EVT VT = Op.getValueType();
6785     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6786     bool isAdvSIMDModImm = false;
6787     uint64_t Shift;
6788 
6789     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6790       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6791       Shift = 264;
6792     }
6793     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6794       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6795       Shift = 272;
6796     }
6797 
6798     if (isAdvSIMDModImm) {
6799       SDLoc dl(Op);
6800       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6801                                 DAG.getConstant(Value, dl, MVT::i32),
6802                                 DAG.getConstant(Shift, dl, MVT::i32));
6803       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6804     }
6805   }
6806 
6807   return SDValue();
6808 }
6809 
6810 // Try 8-bit splatted SIMD immediate.
6811 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6812                                  const APInt &Bits) {
6813   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6814     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6815     EVT VT = Op.getValueType();
6816     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6817 
6818     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6819       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6820 
6821       SDLoc dl(Op);
6822       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6823                                 DAG.getConstant(Value, dl, MVT::i32));
6824       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6825     }
6826   }
6827 
6828   return SDValue();
6829 }
6830 
6831 // Try FP splatted SIMD immediate.
6832 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6833                                   const APInt &Bits) {
6834   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6835     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6836     EVT VT = Op.getValueType();
6837     bool isWide = (VT.getSizeInBits() == 128);
6838     MVT MovTy;
6839     bool isAdvSIMDModImm = false;
6840 
6841     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6842       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6843       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6844     }
6845     else if (isWide &&
6846              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6847       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6848       MovTy = MVT::v2f64;
6849     }
6850 
6851     if (isAdvSIMDModImm) {
6852       SDLoc dl(Op);
6853       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6854                                 DAG.getConstant(Value, dl, MVT::i32));
6855       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6856     }
6857   }
6858 
6859   return SDValue();
6860 }
6861 
6862 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6863                                               SelectionDAG &DAG) const {
6864   SDValue LHS = Op.getOperand(0);
6865   EVT VT = Op.getValueType();
6866 
6867   BuildVectorSDNode *BVN =
6868       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6869   if (!BVN) {
6870     // AND commutes, so try swapping the operands.
6871     LHS = Op.getOperand(1);
6872     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6873   }
6874   if (!BVN)
6875     return Op;
6876 
6877   APInt DefBits(VT.getSizeInBits(), 0);
6878   APInt UndefBits(VT.getSizeInBits(), 0);
6879   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6880     SDValue NewOp;
6881 
6882     // We only have BIC vector immediate instruction, which is and-not.
6883     DefBits = ~DefBits;
6884     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6885                                     DefBits, &LHS)) ||
6886         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6887                                     DefBits, &LHS)))
6888       return NewOp;
6889 
6890     UndefBits = ~UndefBits;
6891     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6892                                     UndefBits, &LHS)) ||
6893         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6894                                     UndefBits, &LHS)))
6895       return NewOp;
6896   }
6897 
6898   // We can always fall back to a non-immediate AND.
6899   return Op;
6900 }
6901 
6902 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6903 // consists of only the same constant int value, returned in reference arg
6904 // ConstVal
6905 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6906                                      uint64_t &ConstVal) {
6907   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6908   if (!Bvec)
6909     return false;
6910   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6911   if (!FirstElt)
6912     return false;
6913   EVT VT = Bvec->getValueType(0);
6914   unsigned NumElts = VT.getVectorNumElements();
6915   for (unsigned i = 1; i < NumElts; ++i)
6916     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6917       return false;
6918   ConstVal = FirstElt->getZExtValue();
6919   return true;
6920 }
6921 
6922 static unsigned getIntrinsicID(const SDNode *N) {
6923   unsigned Opcode = N->getOpcode();
6924   switch (Opcode) {
6925   default:
6926     return Intrinsic::not_intrinsic;
6927   case ISD::INTRINSIC_WO_CHAIN: {
6928     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6929     if (IID < Intrinsic::num_intrinsics)
6930       return IID;
6931     return Intrinsic::not_intrinsic;
6932   }
6933   }
6934 }
6935 
6936 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6937 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6938 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6939 // Also, logical shift right -> sri, with the same structure.
6940 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6941   EVT VT = N->getValueType(0);
6942 
6943   if (!VT.isVector())
6944     return SDValue();
6945 
6946   SDLoc DL(N);
6947 
6948   // Is the first op an AND?
6949   const SDValue And = N->getOperand(0);
6950   if (And.getOpcode() != ISD::AND)
6951     return SDValue();
6952 
6953   // Is the second op an shl or lshr?
6954   SDValue Shift = N->getOperand(1);
6955   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6956   // or AArch64ISD::VLSHR vector, #shift
6957   unsigned ShiftOpc = Shift.getOpcode();
6958   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6959     return SDValue();
6960   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6961 
6962   // Is the shift amount constant?
6963   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6964   if (!C2node)
6965     return SDValue();
6966 
6967   // Is the and mask vector all constant?
6968   uint64_t C1;
6969   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6970     return SDValue();
6971 
6972   // Is C1 == ~C2, taking into account how much one can shift elements of a
6973   // particular size?
6974   uint64_t C2 = C2node->getZExtValue();
6975   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6976   if (C2 > ElemSizeInBits)
6977     return SDValue();
6978   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6979   if ((C1 & ElemMask) != (~C2 & ElemMask))
6980     return SDValue();
6981 
6982   SDValue X = And.getOperand(0);
6983   SDValue Y = Shift.getOperand(0);
6984 
6985   unsigned Intrin =
6986       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6987   SDValue ResultSLI =
6988       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6989                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6990                   Shift.getOperand(1));
6991 
6992   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6993   LLVM_DEBUG(N->dump(&DAG));
6994   LLVM_DEBUG(dbgs() << "into: \n");
6995   LLVM_DEBUG(ResultSLI->dump(&DAG));
6996 
6997   ++NumShiftInserts;
6998   return ResultSLI;
6999 }
7000 
7001 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7002                                              SelectionDAG &DAG) const {
7003   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7004   if (EnableAArch64SlrGeneration) {
7005     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7006       return Res;
7007   }
7008 
7009   EVT VT = Op.getValueType();
7010 
7011   SDValue LHS = Op.getOperand(0);
7012   BuildVectorSDNode *BVN =
7013       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7014   if (!BVN) {
7015     // OR commutes, so try swapping the operands.
7016     LHS = Op.getOperand(1);
7017     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7018   }
7019   if (!BVN)
7020     return Op;
7021 
7022   APInt DefBits(VT.getSizeInBits(), 0);
7023   APInt UndefBits(VT.getSizeInBits(), 0);
7024   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7025     SDValue NewOp;
7026 
7027     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7028                                     DefBits, &LHS)) ||
7029         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7030                                     DefBits, &LHS)))
7031       return NewOp;
7032 
7033     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7034                                     UndefBits, &LHS)) ||
7035         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7036                                     UndefBits, &LHS)))
7037       return NewOp;
7038   }
7039 
7040   // We can always fall back to a non-immediate OR.
7041   return Op;
7042 }
7043 
7044 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7045 // be truncated to fit element width.
7046 static SDValue NormalizeBuildVector(SDValue Op,
7047                                     SelectionDAG &DAG) {
7048   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7049   SDLoc dl(Op);
7050   EVT VT = Op.getValueType();
7051   EVT EltTy= VT.getVectorElementType();
7052 
7053   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7054     return Op;
7055 
7056   SmallVector<SDValue, 16> Ops;
7057   for (SDValue Lane : Op->ops()) {
7058     // For integer vectors, type legalization would have promoted the
7059     // operands already. Otherwise, if Op is a floating-point splat
7060     // (with operands cast to integers), then the only possibilities
7061     // are constants and UNDEFs.
7062     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7063       APInt LowBits(EltTy.getSizeInBits(),
7064                     CstLane->getZExtValue());
7065       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7066     } else if (Lane.getNode()->isUndef()) {
7067       Lane = DAG.getUNDEF(MVT::i32);
7068     } else {
7069       assert(Lane.getValueType() == MVT::i32 &&
7070              "Unexpected BUILD_VECTOR operand type");
7071     }
7072     Ops.push_back(Lane);
7073   }
7074   return DAG.getBuildVector(VT, dl, Ops);
7075 }
7076 
7077 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7078   EVT VT = Op.getValueType();
7079 
7080   APInt DefBits(VT.getSizeInBits(), 0);
7081   APInt UndefBits(VT.getSizeInBits(), 0);
7082   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7083   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7084     SDValue NewOp;
7085     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7086         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7087         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7088         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7089         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7090         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7091       return NewOp;
7092 
7093     DefBits = ~DefBits;
7094     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7095         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7096         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7097       return NewOp;
7098 
7099     DefBits = UndefBits;
7100     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7101         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7102         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7103         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7104         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7105         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7106       return NewOp;
7107 
7108     DefBits = ~UndefBits;
7109     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7110         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7111         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7112       return NewOp;
7113   }
7114 
7115   return SDValue();
7116 }
7117 
7118 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7119                                                  SelectionDAG &DAG) const {
7120   EVT VT = Op.getValueType();
7121 
7122   // Try to build a simple constant vector.
7123   Op = NormalizeBuildVector(Op, DAG);
7124   if (VT.isInteger()) {
7125     // Certain vector constants, used to express things like logical NOT and
7126     // arithmetic NEG, are passed through unmodified.  This allows special
7127     // patterns for these operations to match, which will lower these constants
7128     // to whatever is proven necessary.
7129     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7130     if (BVN->isConstant())
7131       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7132         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7133         APInt Val(BitSize,
7134                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7135         if (Val.isNullValue() || Val.isAllOnesValue())
7136           return Op;
7137       }
7138   }
7139 
7140   if (SDValue V = ConstantBuildVector(Op, DAG))
7141     return V;
7142 
7143   // Scan through the operands to find some interesting properties we can
7144   // exploit:
7145   //   1) If only one value is used, we can use a DUP, or
7146   //   2) if only the low element is not undef, we can just insert that, or
7147   //   3) if only one constant value is used (w/ some non-constant lanes),
7148   //      we can splat the constant value into the whole vector then fill
7149   //      in the non-constant lanes.
7150   //   4) FIXME: If different constant values are used, but we can intelligently
7151   //             select the values we'll be overwriting for the non-constant
7152   //             lanes such that we can directly materialize the vector
7153   //             some other way (MOVI, e.g.), we can be sneaky.
7154   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7155   SDLoc dl(Op);
7156   unsigned NumElts = VT.getVectorNumElements();
7157   bool isOnlyLowElement = true;
7158   bool usesOnlyOneValue = true;
7159   bool usesOnlyOneConstantValue = true;
7160   bool isConstant = true;
7161   bool AllLanesExtractElt = true;
7162   unsigned NumConstantLanes = 0;
7163   SDValue Value;
7164   SDValue ConstantValue;
7165   for (unsigned i = 0; i < NumElts; ++i) {
7166     SDValue V = Op.getOperand(i);
7167     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7168       AllLanesExtractElt = false;
7169     if (V.isUndef())
7170       continue;
7171     if (i > 0)
7172       isOnlyLowElement = false;
7173     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7174       isConstant = false;
7175 
7176     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7177       ++NumConstantLanes;
7178       if (!ConstantValue.getNode())
7179         ConstantValue = V;
7180       else if (ConstantValue != V)
7181         usesOnlyOneConstantValue = false;
7182     }
7183 
7184     if (!Value.getNode())
7185       Value = V;
7186     else if (V != Value)
7187       usesOnlyOneValue = false;
7188   }
7189 
7190   if (!Value.getNode()) {
7191     LLVM_DEBUG(
7192         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7193     return DAG.getUNDEF(VT);
7194   }
7195 
7196   if (isOnlyLowElement) {
7197     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7198                          "SCALAR_TO_VECTOR node\n");
7199     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7200   }
7201 
7202   if (AllLanesExtractElt) {
7203     SDNode *Vector = nullptr;
7204     bool Even = false;
7205     bool Odd = false;
7206     // Check whether the extract elements match the Even pattern <0,2,4,...> or
7207     // the Odd pattern <1,3,5,...>.
7208     for (unsigned i = 0; i < NumElts; ++i) {
7209       SDValue V = Op.getOperand(i);
7210       const SDNode *N = V.getNode();
7211       if (!isa<ConstantSDNode>(N->getOperand(1)))
7212         break;
7213       SDValue N0 = N->getOperand(0);
7214 
7215       // All elements are extracted from the same vector.
7216       if (!Vector) {
7217         Vector = N0.getNode();
7218         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7219         // BUILD_VECTOR.
7220         if (VT.getVectorElementType() !=
7221             N0.getValueType().getVectorElementType())
7222           break;
7223       } else if (Vector != N0.getNode()) {
7224         Odd = false;
7225         Even = false;
7226         break;
7227       }
7228 
7229       // Extracted values are either at Even indices <0,2,4,...> or at Odd
7230       // indices <1,3,5,...>.
7231       uint64_t Val = N->getConstantOperandVal(1);
7232       if (Val == 2 * i) {
7233         Even = true;
7234         continue;
7235       }
7236       if (Val - 1 == 2 * i) {
7237         Odd = true;
7238         continue;
7239       }
7240 
7241       // Something does not match: abort.
7242       Odd = false;
7243       Even = false;
7244       break;
7245     }
7246     if (Even || Odd) {
7247       SDValue LHS =
7248           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7249                       DAG.getConstant(0, dl, MVT::i64));
7250       SDValue RHS =
7251           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7252                       DAG.getConstant(NumElts, dl, MVT::i64));
7253 
7254       if (Even && !Odd)
7255         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7256                            RHS);
7257       if (Odd && !Even)
7258         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7259                            RHS);
7260     }
7261   }
7262 
7263   // Use DUP for non-constant splats. For f32 constant splats, reduce to
7264   // i32 and try again.
7265   if (usesOnlyOneValue) {
7266     if (!isConstant) {
7267       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7268           Value.getValueType() != VT) {
7269         LLVM_DEBUG(
7270             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7271         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7272       }
7273 
7274       // This is actually a DUPLANExx operation, which keeps everything vectory.
7275 
7276       SDValue Lane = Value.getOperand(1);
7277       Value = Value.getOperand(0);
7278       if (Value.getValueSizeInBits() == 64) {
7279         LLVM_DEBUG(
7280             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7281                       "widening it\n");
7282         Value = WidenVector(Value, DAG);
7283       }
7284 
7285       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7286       return DAG.getNode(Opcode, dl, VT, Value, Lane);
7287     }
7288 
7289     if (VT.getVectorElementType().isFloatingPoint()) {
7290       SmallVector<SDValue, 8> Ops;
7291       EVT EltTy = VT.getVectorElementType();
7292       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7293               "Unsupported floating-point vector type");
7294       LLVM_DEBUG(
7295           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7296                     "BITCASTS, and try again\n");
7297       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7298       for (unsigned i = 0; i < NumElts; ++i)
7299         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7300       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7301       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7302       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7303                  Val.dump(););
7304       Val = LowerBUILD_VECTOR(Val, DAG);
7305       if (Val.getNode())
7306         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7307     }
7308   }
7309 
7310   // If there was only one constant value used and for more than one lane,
7311   // start by splatting that value, then replace the non-constant lanes. This
7312   // is better than the default, which will perform a separate initialization
7313   // for each lane.
7314   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7315     // Firstly, try to materialize the splat constant.
7316     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7317             Val = ConstantBuildVector(Vec, DAG);
7318     if (!Val) {
7319       // Otherwise, materialize the constant and splat it.
7320       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7321       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7322     }
7323 
7324     // Now insert the non-constant lanes.
7325     for (unsigned i = 0; i < NumElts; ++i) {
7326       SDValue V = Op.getOperand(i);
7327       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7328       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7329         // Note that type legalization likely mucked about with the VT of the
7330         // source operand, so we may have to convert it here before inserting.
7331         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7332     }
7333     return Val;
7334   }
7335 
7336   // This will generate a load from the constant pool.
7337   if (isConstant) {
7338     LLVM_DEBUG(
7339         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7340                   "expansion\n");
7341     return SDValue();
7342   }
7343 
7344   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7345   if (NumElts >= 4) {
7346     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7347       return shuffle;
7348   }
7349 
7350   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7351   // know the default expansion would otherwise fall back on something even
7352   // worse. For a vector with one or two non-undef values, that's
7353   // scalar_to_vector for the elements followed by a shuffle (provided the
7354   // shuffle is valid for the target) and materialization element by element
7355   // on the stack followed by a load for everything else.
7356   if (!isConstant && !usesOnlyOneValue) {
7357     LLVM_DEBUG(
7358         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7359                   "of INSERT_VECTOR_ELT\n");
7360 
7361     SDValue Vec = DAG.getUNDEF(VT);
7362     SDValue Op0 = Op.getOperand(0);
7363     unsigned i = 0;
7364 
7365     // Use SCALAR_TO_VECTOR for lane zero to
7366     // a) Avoid a RMW dependency on the full vector register, and
7367     // b) Allow the register coalescer to fold away the copy if the
7368     //    value is already in an S or D register, and we're forced to emit an
7369     //    INSERT_SUBREG that we can't fold anywhere.
7370     //
7371     // We also allow types like i8 and i16 which are illegal scalar but legal
7372     // vector element types. After type-legalization the inserted value is
7373     // extended (i32) and it is safe to cast them to the vector type by ignoring
7374     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7375     if (!Op0.isUndef()) {
7376       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7377       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7378       ++i;
7379     }
7380     LLVM_DEBUG(if (i < NumElts) dbgs()
7381                    << "Creating nodes for the other vector elements:\n";);
7382     for (; i < NumElts; ++i) {
7383       SDValue V = Op.getOperand(i);
7384       if (V.isUndef())
7385         continue;
7386       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7387       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7388     }
7389     return Vec;
7390   }
7391 
7392   LLVM_DEBUG(
7393       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7394                 "better alternative\n");
7395   return SDValue();
7396 }
7397 
7398 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7399                                                       SelectionDAG &DAG) const {
7400   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7401 
7402   // Check for non-constant or out of range lane.
7403   EVT VT = Op.getOperand(0).getValueType();
7404   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7405   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7406     return SDValue();
7407 
7408 
7409   // Insertion/extraction are legal for V128 types.
7410   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7411       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7412       VT == MVT::v8f16)
7413     return Op;
7414 
7415   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7416       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7417     return SDValue();
7418 
7419   // For V64 types, we perform insertion by expanding the value
7420   // to a V128 type and perform the insertion on that.
7421   SDLoc DL(Op);
7422   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7423   EVT WideTy = WideVec.getValueType();
7424 
7425   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7426                              Op.getOperand(1), Op.getOperand(2));
7427   // Re-narrow the resultant vector.
7428   return NarrowVector(Node, DAG);
7429 }
7430 
7431 SDValue
7432 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7433                                                SelectionDAG &DAG) const {
7434   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7435 
7436   // Check for non-constant or out of range lane.
7437   EVT VT = Op.getOperand(0).getValueType();
7438   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7439   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7440     return SDValue();
7441 
7442 
7443   // Insertion/extraction are legal for V128 types.
7444   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7445       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7446       VT == MVT::v8f16)
7447     return Op;
7448 
7449   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7450       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7451     return SDValue();
7452 
7453   // For V64 types, we perform extraction by expanding the value
7454   // to a V128 type and perform the extraction on that.
7455   SDLoc DL(Op);
7456   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7457   EVT WideTy = WideVec.getValueType();
7458 
7459   EVT ExtrTy = WideTy.getVectorElementType();
7460   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7461     ExtrTy = MVT::i32;
7462 
7463   // For extractions, we just return the result directly.
7464   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7465                      Op.getOperand(1));
7466 }
7467 
7468 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7469                                                       SelectionDAG &DAG) const {
7470   EVT VT = Op.getOperand(0).getValueType();
7471   SDLoc dl(Op);
7472   // Just in case...
7473   if (!VT.isVector())
7474     return SDValue();
7475 
7476   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7477   if (!Cst)
7478     return SDValue();
7479   unsigned Val = Cst->getZExtValue();
7480 
7481   unsigned Size = Op.getValueSizeInBits();
7482 
7483   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7484   if (Val == 0)
7485     return Op;
7486 
7487   // If this is extracting the upper 64-bits of a 128-bit vector, we match
7488   // that directly.
7489   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7490     return Op;
7491 
7492   return SDValue();
7493 }
7494 
7495 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7496   if (VT.getVectorNumElements() == 4 &&
7497       (VT.is128BitVector() || VT.is64BitVector())) {
7498     unsigned PFIndexes[4];
7499     for (unsigned i = 0; i != 4; ++i) {
7500       if (M[i] < 0)
7501         PFIndexes[i] = 8;
7502       else
7503         PFIndexes[i] = M[i];
7504     }
7505 
7506     // Compute the index in the perfect shuffle table.
7507     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7508                             PFIndexes[2] * 9 + PFIndexes[3];
7509     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7510     unsigned Cost = (PFEntry >> 30);
7511 
7512     if (Cost <= 4)
7513       return true;
7514   }
7515 
7516   bool DummyBool;
7517   int DummyInt;
7518   unsigned DummyUnsigned;
7519 
7520   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7521           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7522           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7523           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7524           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7525           isZIPMask(M, VT, DummyUnsigned) ||
7526           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7527           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7528           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7529           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7530           isConcatMask(M, VT, VT.getSizeInBits() == 128));
7531 }
7532 
7533 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7534 /// operand of a vector shift operation, where all the elements of the
7535 /// build_vector must have the same constant integer value.
7536 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7537   // Ignore bit_converts.
7538   while (Op.getOpcode() == ISD::BITCAST)
7539     Op = Op.getOperand(0);
7540   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7541   APInt SplatBits, SplatUndef;
7542   unsigned SplatBitSize;
7543   bool HasAnyUndefs;
7544   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7545                                     HasAnyUndefs, ElementBits) ||
7546       SplatBitSize > ElementBits)
7547     return false;
7548   Cnt = SplatBits.getSExtValue();
7549   return true;
7550 }
7551 
7552 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7553 /// operand of a vector shift left operation.  That value must be in the range:
7554 ///   0 <= Value < ElementBits for a left shift; or
7555 ///   0 <= Value <= ElementBits for a long left shift.
7556 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7557   assert(VT.isVector() && "vector shift count is not a vector type");
7558   int64_t ElementBits = VT.getScalarSizeInBits();
7559   if (!getVShiftImm(Op, ElementBits, Cnt))
7560     return false;
7561   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7562 }
7563 
7564 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7565 /// operand of a vector shift right operation. The value must be in the range:
7566 ///   1 <= Value <= ElementBits for a right shift; or
7567 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7568   assert(VT.isVector() && "vector shift count is not a vector type");
7569   int64_t ElementBits = VT.getScalarSizeInBits();
7570   if (!getVShiftImm(Op, ElementBits, Cnt))
7571     return false;
7572   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7573 }
7574 
7575 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7576                                                       SelectionDAG &DAG) const {
7577   EVT VT = Op.getValueType();
7578   SDLoc DL(Op);
7579   int64_t Cnt;
7580 
7581   if (!Op.getOperand(1).getValueType().isVector())
7582     return Op;
7583   unsigned EltSize = VT.getScalarSizeInBits();
7584 
7585   switch (Op.getOpcode()) {
7586   default:
7587     llvm_unreachable("unexpected shift opcode");
7588 
7589   case ISD::SHL:
7590     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7591       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7592                          DAG.getConstant(Cnt, DL, MVT::i32));
7593     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7594                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7595                                        MVT::i32),
7596                        Op.getOperand(0), Op.getOperand(1));
7597   case ISD::SRA:
7598   case ISD::SRL:
7599     // Right shift immediate
7600     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7601       unsigned Opc =
7602           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7603       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7604                          DAG.getConstant(Cnt, DL, MVT::i32));
7605     }
7606 
7607     // Right shift register.  Note, there is not a shift right register
7608     // instruction, but the shift left register instruction takes a signed
7609     // value, where negative numbers specify a right shift.
7610     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7611                                                 : Intrinsic::aarch64_neon_ushl;
7612     // negate the shift amount
7613     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7614     SDValue NegShiftLeft =
7615         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7616                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7617                     NegShift);
7618     return NegShiftLeft;
7619   }
7620 
7621   return SDValue();
7622 }
7623 
7624 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7625                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
7626                                     const SDLoc &dl, SelectionDAG &DAG) {
7627   EVT SrcVT = LHS.getValueType();
7628   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7629          "function only supposed to emit natural comparisons");
7630 
7631   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7632   APInt CnstBits(VT.getSizeInBits(), 0);
7633   APInt UndefBits(VT.getSizeInBits(), 0);
7634   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7635   bool IsZero = IsCnst && (CnstBits == 0);
7636 
7637   if (SrcVT.getVectorElementType().isFloatingPoint()) {
7638     switch (CC) {
7639     default:
7640       return SDValue();
7641     case AArch64CC::NE: {
7642       SDValue Fcmeq;
7643       if (IsZero)
7644         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7645       else
7646         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7647       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7648     }
7649     case AArch64CC::EQ:
7650       if (IsZero)
7651         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7652       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7653     case AArch64CC::GE:
7654       if (IsZero)
7655         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7656       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7657     case AArch64CC::GT:
7658       if (IsZero)
7659         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7660       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7661     case AArch64CC::LS:
7662       if (IsZero)
7663         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7664       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7665     case AArch64CC::LT:
7666       if (!NoNans)
7667         return SDValue();
7668       // If we ignore NaNs then we can use to the MI implementation.
7669       LLVM_FALLTHROUGH;
7670     case AArch64CC::MI:
7671       if (IsZero)
7672         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7673       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7674     }
7675   }
7676 
7677   switch (CC) {
7678   default:
7679     return SDValue();
7680   case AArch64CC::NE: {
7681     SDValue Cmeq;
7682     if (IsZero)
7683       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7684     else
7685       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7686     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7687   }
7688   case AArch64CC::EQ:
7689     if (IsZero)
7690       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7691     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7692   case AArch64CC::GE:
7693     if (IsZero)
7694       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7695     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7696   case AArch64CC::GT:
7697     if (IsZero)
7698       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7699     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7700   case AArch64CC::LE:
7701     if (IsZero)
7702       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7703     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7704   case AArch64CC::LS:
7705     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7706   case AArch64CC::LO:
7707     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7708   case AArch64CC::LT:
7709     if (IsZero)
7710       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7711     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7712   case AArch64CC::HI:
7713     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7714   case AArch64CC::HS:
7715     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7716   }
7717 }
7718 
7719 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7720                                            SelectionDAG &DAG) const {
7721   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7722   SDValue LHS = Op.getOperand(0);
7723   SDValue RHS = Op.getOperand(1);
7724   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7725   SDLoc dl(Op);
7726 
7727   if (LHS.getValueType().getVectorElementType().isInteger()) {
7728     assert(LHS.getValueType() == RHS.getValueType());
7729     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7730     SDValue Cmp =
7731         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7732     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7733   }
7734 
7735   const bool FullFP16 =
7736     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7737 
7738   // Make v4f16 (only) fcmp operations utilise vector instructions
7739   // v8f16 support will be a litle more complicated
7740   if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7741     if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7742       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7743       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7744       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7745       DAG.ReplaceAllUsesWith(Op, NewSetcc);
7746       CmpVT = MVT::v4i32;
7747     } else
7748       return SDValue();
7749   }
7750 
7751   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7752          LHS.getValueType().getVectorElementType() == MVT::f64);
7753 
7754   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7755   // clean.  Some of them require two branches to implement.
7756   AArch64CC::CondCode CC1, CC2;
7757   bool ShouldInvert;
7758   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7759 
7760   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7761   SDValue Cmp =
7762       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7763   if (!Cmp.getNode())
7764     return SDValue();
7765 
7766   if (CC2 != AArch64CC::AL) {
7767     SDValue Cmp2 =
7768         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7769     if (!Cmp2.getNode())
7770       return SDValue();
7771 
7772     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7773   }
7774 
7775   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7776 
7777   if (ShouldInvert)
7778     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7779 
7780   return Cmp;
7781 }
7782 
7783 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7784                                   SelectionDAG &DAG) {
7785   SDValue VecOp = ScalarOp.getOperand(0);
7786   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7787   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7788                      DAG.getConstant(0, DL, MVT::i64));
7789 }
7790 
7791 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7792                                               SelectionDAG &DAG) const {
7793   SDLoc dl(Op);
7794   switch (Op.getOpcode()) {
7795   case ISD::VECREDUCE_ADD:
7796     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7797   case ISD::VECREDUCE_SMAX:
7798     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7799   case ISD::VECREDUCE_SMIN:
7800     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7801   case ISD::VECREDUCE_UMAX:
7802     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7803   case ISD::VECREDUCE_UMIN:
7804     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7805   case ISD::VECREDUCE_FMAX: {
7806     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7807     return DAG.getNode(
7808         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7809         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7810         Op.getOperand(0));
7811   }
7812   case ISD::VECREDUCE_FMIN: {
7813     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7814     return DAG.getNode(
7815         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7816         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7817         Op.getOperand(0));
7818   }
7819   default:
7820     llvm_unreachable("Unhandled reduction");
7821   }
7822 }
7823 
7824 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7825                                                     SelectionDAG &DAG) const {
7826   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7827   if (!Subtarget.hasLSE())
7828     return SDValue();
7829 
7830   // LSE has an atomic load-add instruction, but not a load-sub.
7831   SDLoc dl(Op);
7832   MVT VT = Op.getSimpleValueType();
7833   SDValue RHS = Op.getOperand(2);
7834   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7835   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7836   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7837                        Op.getOperand(0), Op.getOperand(1), RHS,
7838                        AN->getMemOperand());
7839 }
7840 
7841 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7842                                                     SelectionDAG &DAG) const {
7843   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7844   if (!Subtarget.hasLSE())
7845     return SDValue();
7846 
7847   // LSE has an atomic load-clear instruction, but not a load-and.
7848   SDLoc dl(Op);
7849   MVT VT = Op.getSimpleValueType();
7850   SDValue RHS = Op.getOperand(2);
7851   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7852   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7853   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7854                        Op.getOperand(0), Op.getOperand(1), RHS,
7855                        AN->getMemOperand());
7856 }
7857 
7858 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7859     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7860   SDLoc dl(Op);
7861   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7862   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7863 
7864   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7865   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7866   if (Subtarget->hasCustomCallingConv())
7867     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
7868 
7869   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7870                      DAG.getConstant(4, dl, MVT::i64));
7871   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7872   Chain =
7873       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7874                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7875                   DAG.getRegisterMask(Mask), Chain.getValue(1));
7876   // To match the actual intent better, we should read the output from X15 here
7877   // again (instead of potentially spilling it to the stack), but rereading Size
7878   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7879   // here.
7880 
7881   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7882                      DAG.getConstant(4, dl, MVT::i64));
7883   return Chain;
7884 }
7885 
7886 SDValue
7887 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7888                                                SelectionDAG &DAG) const {
7889   assert(Subtarget->isTargetWindows() &&
7890          "Only Windows alloca probing supported");
7891   SDLoc dl(Op);
7892   // Get the inputs.
7893   SDNode *Node = Op.getNode();
7894   SDValue Chain = Op.getOperand(0);
7895   SDValue Size = Op.getOperand(1);
7896   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7897   EVT VT = Node->getValueType(0);
7898 
7899   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7900           "no-stack-arg-probe")) {
7901     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7902     Chain = SP.getValue(1);
7903     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7904     if (Align)
7905       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7906                        DAG.getConstant(-(uint64_t)Align, dl, VT));
7907     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7908     SDValue Ops[2] = {SP, Chain};
7909     return DAG.getMergeValues(Ops, dl);
7910   }
7911 
7912   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7913 
7914   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7915 
7916   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7917   Chain = SP.getValue(1);
7918   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7919   if (Align)
7920     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7921                      DAG.getConstant(-(uint64_t)Align, dl, VT));
7922   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7923 
7924   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7925                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7926 
7927   SDValue Ops[2] = {SP, Chain};
7928   return DAG.getMergeValues(Ops, dl);
7929 }
7930 
7931 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7932 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
7933 /// specified in the intrinsic calls.
7934 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7935                                                const CallInst &I,
7936                                                MachineFunction &MF,
7937                                                unsigned Intrinsic) const {
7938   auto &DL = I.getModule()->getDataLayout();
7939   switch (Intrinsic) {
7940   case Intrinsic::aarch64_neon_ld2:
7941   case Intrinsic::aarch64_neon_ld3:
7942   case Intrinsic::aarch64_neon_ld4:
7943   case Intrinsic::aarch64_neon_ld1x2:
7944   case Intrinsic::aarch64_neon_ld1x3:
7945   case Intrinsic::aarch64_neon_ld1x4:
7946   case Intrinsic::aarch64_neon_ld2lane:
7947   case Intrinsic::aarch64_neon_ld3lane:
7948   case Intrinsic::aarch64_neon_ld4lane:
7949   case Intrinsic::aarch64_neon_ld2r:
7950   case Intrinsic::aarch64_neon_ld3r:
7951   case Intrinsic::aarch64_neon_ld4r: {
7952     Info.opc = ISD::INTRINSIC_W_CHAIN;
7953     // Conservatively set memVT to the entire set of vectors loaded.
7954     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7955     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7956     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7957     Info.offset = 0;
7958     Info.align = 0;
7959     // volatile loads with NEON intrinsics not supported
7960     Info.flags = MachineMemOperand::MOLoad;
7961     return true;
7962   }
7963   case Intrinsic::aarch64_neon_st2:
7964   case Intrinsic::aarch64_neon_st3:
7965   case Intrinsic::aarch64_neon_st4:
7966   case Intrinsic::aarch64_neon_st1x2:
7967   case Intrinsic::aarch64_neon_st1x3:
7968   case Intrinsic::aarch64_neon_st1x4:
7969   case Intrinsic::aarch64_neon_st2lane:
7970   case Intrinsic::aarch64_neon_st3lane:
7971   case Intrinsic::aarch64_neon_st4lane: {
7972     Info.opc = ISD::INTRINSIC_VOID;
7973     // Conservatively set memVT to the entire set of vectors stored.
7974     unsigned NumElts = 0;
7975     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7976       Type *ArgTy = I.getArgOperand(ArgI)->getType();
7977       if (!ArgTy->isVectorTy())
7978         break;
7979       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7980     }
7981     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7982     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7983     Info.offset = 0;
7984     Info.align = 0;
7985     // volatile stores with NEON intrinsics not supported
7986     Info.flags = MachineMemOperand::MOStore;
7987     return true;
7988   }
7989   case Intrinsic::aarch64_ldaxr:
7990   case Intrinsic::aarch64_ldxr: {
7991     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7992     Info.opc = ISD::INTRINSIC_W_CHAIN;
7993     Info.memVT = MVT::getVT(PtrTy->getElementType());
7994     Info.ptrVal = I.getArgOperand(0);
7995     Info.offset = 0;
7996     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7997     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
7998     return true;
7999   }
8000   case Intrinsic::aarch64_stlxr:
8001   case Intrinsic::aarch64_stxr: {
8002     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8003     Info.opc = ISD::INTRINSIC_W_CHAIN;
8004     Info.memVT = MVT::getVT(PtrTy->getElementType());
8005     Info.ptrVal = I.getArgOperand(1);
8006     Info.offset = 0;
8007     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
8008     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8009     return true;
8010   }
8011   case Intrinsic::aarch64_ldaxp:
8012   case Intrinsic::aarch64_ldxp:
8013     Info.opc = ISD::INTRINSIC_W_CHAIN;
8014     Info.memVT = MVT::i128;
8015     Info.ptrVal = I.getArgOperand(0);
8016     Info.offset = 0;
8017     Info.align = 16;
8018     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8019     return true;
8020   case Intrinsic::aarch64_stlxp:
8021   case Intrinsic::aarch64_stxp:
8022     Info.opc = ISD::INTRINSIC_W_CHAIN;
8023     Info.memVT = MVT::i128;
8024     Info.ptrVal = I.getArgOperand(2);
8025     Info.offset = 0;
8026     Info.align = 16;
8027     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8028     return true;
8029   default:
8030     break;
8031   }
8032 
8033   return false;
8034 }
8035 
8036 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8037                                                   ISD::LoadExtType ExtTy,
8038                                                   EVT NewVT) const {
8039   // If we're reducing the load width in order to avoid having to use an extra
8040   // instruction to do extension then it's probably a good idea.
8041   if (ExtTy != ISD::NON_EXTLOAD)
8042     return true;
8043   // Don't reduce load width if it would prevent us from combining a shift into
8044   // the offset.
8045   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8046   assert(Mem);
8047   const SDValue &Base = Mem->getBasePtr();
8048   if (Base.getOpcode() == ISD::ADD &&
8049       Base.getOperand(1).getOpcode() == ISD::SHL &&
8050       Base.getOperand(1).hasOneUse() &&
8051       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8052     // The shift can be combined if it matches the size of the value being
8053     // loaded (and so reducing the width would make it not match).
8054     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8055     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8056     if (ShiftAmount == Log2_32(LoadBytes))
8057       return false;
8058   }
8059   // We have no reason to disallow reducing the load width, so allow it.
8060   return true;
8061 }
8062 
8063 // Truncations from 64-bit GPR to 32-bit GPR is free.
8064 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8065   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8066     return false;
8067   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8068   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8069   return NumBits1 > NumBits2;
8070 }
8071 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8072   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8073     return false;
8074   unsigned NumBits1 = VT1.getSizeInBits();
8075   unsigned NumBits2 = VT2.getSizeInBits();
8076   return NumBits1 > NumBits2;
8077 }
8078 
8079 /// Check if it is profitable to hoist instruction in then/else to if.
8080 /// Not profitable if I and it's user can form a FMA instruction
8081 /// because we prefer FMSUB/FMADD.
8082 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8083   if (I->getOpcode() != Instruction::FMul)
8084     return true;
8085 
8086   if (!I->hasOneUse())
8087     return true;
8088 
8089   Instruction *User = I->user_back();
8090 
8091   if (User &&
8092       !(User->getOpcode() == Instruction::FSub ||
8093         User->getOpcode() == Instruction::FAdd))
8094     return true;
8095 
8096   const TargetOptions &Options = getTargetMachine().Options;
8097   const DataLayout &DL = I->getModule()->getDataLayout();
8098   EVT VT = getValueType(DL, User->getOperand(0)->getType());
8099 
8100   return !(isFMAFasterThanFMulAndFAdd(VT) &&
8101            isOperationLegalOrCustom(ISD::FMA, VT) &&
8102            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8103             Options.UnsafeFPMath));
8104 }
8105 
8106 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8107 // 64-bit GPR.
8108 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8109   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8110     return false;
8111   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8112   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8113   return NumBits1 == 32 && NumBits2 == 64;
8114 }
8115 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8116   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8117     return false;
8118   unsigned NumBits1 = VT1.getSizeInBits();
8119   unsigned NumBits2 = VT2.getSizeInBits();
8120   return NumBits1 == 32 && NumBits2 == 64;
8121 }
8122 
8123 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8124   EVT VT1 = Val.getValueType();
8125   if (isZExtFree(VT1, VT2)) {
8126     return true;
8127   }
8128 
8129   if (Val.getOpcode() != ISD::LOAD)
8130     return false;
8131 
8132   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8133   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8134           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8135           VT1.getSizeInBits() <= 32);
8136 }
8137 
8138 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8139   if (isa<FPExtInst>(Ext))
8140     return false;
8141 
8142   // Vector types are not free.
8143   if (Ext->getType()->isVectorTy())
8144     return false;
8145 
8146   for (const Use &U : Ext->uses()) {
8147     // The extension is free if we can fold it with a left shift in an
8148     // addressing mode or an arithmetic operation: add, sub, and cmp.
8149 
8150     // Is there a shift?
8151     const Instruction *Instr = cast<Instruction>(U.getUser());
8152 
8153     // Is this a constant shift?
8154     switch (Instr->getOpcode()) {
8155     case Instruction::Shl:
8156       if (!isa<ConstantInt>(Instr->getOperand(1)))
8157         return false;
8158       break;
8159     case Instruction::GetElementPtr: {
8160       gep_type_iterator GTI = gep_type_begin(Instr);
8161       auto &DL = Ext->getModule()->getDataLayout();
8162       std::advance(GTI, U.getOperandNo()-1);
8163       Type *IdxTy = GTI.getIndexedType();
8164       // This extension will end up with a shift because of the scaling factor.
8165       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8166       // Get the shift amount based on the scaling factor:
8167       // log2(sizeof(IdxTy)) - log2(8).
8168       uint64_t ShiftAmt =
8169           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
8170       // Is the constant foldable in the shift of the addressing mode?
8171       // I.e., shift amount is between 1 and 4 inclusive.
8172       if (ShiftAmt == 0 || ShiftAmt > 4)
8173         return false;
8174       break;
8175     }
8176     case Instruction::Trunc:
8177       // Check if this is a noop.
8178       // trunc(sext ty1 to ty2) to ty1.
8179       if (Instr->getType() == Ext->getOperand(0)->getType())
8180         continue;
8181       LLVM_FALLTHROUGH;
8182     default:
8183       return false;
8184     }
8185 
8186     // At this point we can use the bfm family, so this extension is free
8187     // for that use.
8188   }
8189   return true;
8190 }
8191 
8192 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8193                                           unsigned &RequiredAligment) const {
8194   if (!LoadedType.isSimple() ||
8195       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8196     return false;
8197   // Cyclone supports unaligned accesses.
8198   RequiredAligment = 0;
8199   unsigned NumBits = LoadedType.getSizeInBits();
8200   return NumBits == 32 || NumBits == 64;
8201 }
8202 
8203 /// A helper function for determining the number of interleaved accesses we
8204 /// will generate when lowering accesses of the given type.
8205 unsigned
8206 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8207                                                  const DataLayout &DL) const {
8208   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8209 }
8210 
8211 MachineMemOperand::Flags
8212 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8213   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8214       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8215     return MOStridedAccess;
8216   return MachineMemOperand::MONone;
8217 }
8218 
8219 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8220     VectorType *VecTy, const DataLayout &DL) const {
8221 
8222   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8223   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8224 
8225   // Ensure the number of vector elements is greater than 1.
8226   if (VecTy->getNumElements() < 2)
8227     return false;
8228 
8229   // Ensure the element type is legal.
8230   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8231     return false;
8232 
8233   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8234   // 128 will be split into multiple interleaved accesses.
8235   return VecSize == 64 || VecSize % 128 == 0;
8236 }
8237 
8238 /// Lower an interleaved load into a ldN intrinsic.
8239 ///
8240 /// E.g. Lower an interleaved load (Factor = 2):
8241 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8242 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
8243 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
8244 ///
8245 ///      Into:
8246 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8247 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8248 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8249 bool AArch64TargetLowering::lowerInterleavedLoad(
8250     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8251     ArrayRef<unsigned> Indices, unsigned Factor) const {
8252   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8253          "Invalid interleave factor");
8254   assert(!Shuffles.empty() && "Empty shufflevector input");
8255   assert(Shuffles.size() == Indices.size() &&
8256          "Unmatched number of shufflevectors and indices");
8257 
8258   const DataLayout &DL = LI->getModule()->getDataLayout();
8259 
8260   VectorType *VecTy = Shuffles[0]->getType();
8261 
8262   // Skip if we do not have NEON and skip illegal vector types. We can
8263   // "legalize" wide vector types into multiple interleaved accesses as long as
8264   // the vector types are divisible by 128.
8265   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8266     return false;
8267 
8268   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8269 
8270   // A pointer vector can not be the return type of the ldN intrinsics. Need to
8271   // load integer vectors first and then convert to pointer vectors.
8272   Type *EltTy = VecTy->getVectorElementType();
8273   if (EltTy->isPointerTy())
8274     VecTy =
8275         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8276 
8277   IRBuilder<> Builder(LI);
8278 
8279   // The base address of the load.
8280   Value *BaseAddr = LI->getPointerOperand();
8281 
8282   if (NumLoads > 1) {
8283     // If we're going to generate more than one load, reset the sub-vector type
8284     // to something legal.
8285     VecTy = VectorType::get(VecTy->getVectorElementType(),
8286                             VecTy->getVectorNumElements() / NumLoads);
8287 
8288     // We will compute the pointer operand of each load from the original base
8289     // address using GEPs. Cast the base address to a pointer to the scalar
8290     // element type.
8291     BaseAddr = Builder.CreateBitCast(
8292         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8293                       LI->getPointerAddressSpace()));
8294   }
8295 
8296   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8297   Type *Tys[2] = {VecTy, PtrTy};
8298   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8299                                             Intrinsic::aarch64_neon_ld3,
8300                                             Intrinsic::aarch64_neon_ld4};
8301   Function *LdNFunc =
8302       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8303 
8304   // Holds sub-vectors extracted from the load intrinsic return values. The
8305   // sub-vectors are associated with the shufflevector instructions they will
8306   // replace.
8307   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8308 
8309   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8310 
8311     // If we're generating more than one load, compute the base address of
8312     // subsequent loads as an offset from the previous.
8313     if (LoadCount > 0)
8314       BaseAddr = Builder.CreateConstGEP1_32(
8315           BaseAddr, VecTy->getVectorNumElements() * Factor);
8316 
8317     CallInst *LdN = Builder.CreateCall(
8318         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8319 
8320     // Extract and store the sub-vectors returned by the load intrinsic.
8321     for (unsigned i = 0; i < Shuffles.size(); i++) {
8322       ShuffleVectorInst *SVI = Shuffles[i];
8323       unsigned Index = Indices[i];
8324 
8325       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8326 
8327       // Convert the integer vector to pointer vector if the element is pointer.
8328       if (EltTy->isPointerTy())
8329         SubVec = Builder.CreateIntToPtr(
8330             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8331                                     VecTy->getVectorNumElements()));
8332       SubVecs[SVI].push_back(SubVec);
8333     }
8334   }
8335 
8336   // Replace uses of the shufflevector instructions with the sub-vectors
8337   // returned by the load intrinsic. If a shufflevector instruction is
8338   // associated with more than one sub-vector, those sub-vectors will be
8339   // concatenated into a single wide vector.
8340   for (ShuffleVectorInst *SVI : Shuffles) {
8341     auto &SubVec = SubVecs[SVI];
8342     auto *WideVec =
8343         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8344     SVI->replaceAllUsesWith(WideVec);
8345   }
8346 
8347   return true;
8348 }
8349 
8350 /// Lower an interleaved store into a stN intrinsic.
8351 ///
8352 /// E.g. Lower an interleaved store (Factor = 3):
8353 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8354 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8355 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8356 ///
8357 ///      Into:
8358 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8359 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8360 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8361 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8362 ///
8363 /// Note that the new shufflevectors will be removed and we'll only generate one
8364 /// st3 instruction in CodeGen.
8365 ///
8366 /// Example for a more general valid mask (Factor 3). Lower:
8367 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8368 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8369 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8370 ///
8371 ///      Into:
8372 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8373 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8374 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8375 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8376 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8377                                                   ShuffleVectorInst *SVI,
8378                                                   unsigned Factor) const {
8379   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8380          "Invalid interleave factor");
8381 
8382   VectorType *VecTy = SVI->getType();
8383   assert(VecTy->getVectorNumElements() % Factor == 0 &&
8384          "Invalid interleaved store");
8385 
8386   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8387   Type *EltTy = VecTy->getVectorElementType();
8388   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8389 
8390   const DataLayout &DL = SI->getModule()->getDataLayout();
8391 
8392   // Skip if we do not have NEON and skip illegal vector types. We can
8393   // "legalize" wide vector types into multiple interleaved accesses as long as
8394   // the vector types are divisible by 128.
8395   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8396     return false;
8397 
8398   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8399 
8400   Value *Op0 = SVI->getOperand(0);
8401   Value *Op1 = SVI->getOperand(1);
8402   IRBuilder<> Builder(SI);
8403 
8404   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8405   // vectors to integer vectors.
8406   if (EltTy->isPointerTy()) {
8407     Type *IntTy = DL.getIntPtrType(EltTy);
8408     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8409 
8410     // Convert to the corresponding integer vector.
8411     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8412     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8413     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8414 
8415     SubVecTy = VectorType::get(IntTy, LaneLen);
8416   }
8417 
8418   // The base address of the store.
8419   Value *BaseAddr = SI->getPointerOperand();
8420 
8421   if (NumStores > 1) {
8422     // If we're going to generate more than one store, reset the lane length
8423     // and sub-vector type to something legal.
8424     LaneLen /= NumStores;
8425     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8426 
8427     // We will compute the pointer operand of each store from the original base
8428     // address using GEPs. Cast the base address to a pointer to the scalar
8429     // element type.
8430     BaseAddr = Builder.CreateBitCast(
8431         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8432                       SI->getPointerAddressSpace()));
8433   }
8434 
8435   auto Mask = SVI->getShuffleMask();
8436 
8437   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8438   Type *Tys[2] = {SubVecTy, PtrTy};
8439   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8440                                              Intrinsic::aarch64_neon_st3,
8441                                              Intrinsic::aarch64_neon_st4};
8442   Function *StNFunc =
8443       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8444 
8445   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8446 
8447     SmallVector<Value *, 5> Ops;
8448 
8449     // Split the shufflevector operands into sub vectors for the new stN call.
8450     for (unsigned i = 0; i < Factor; i++) {
8451       unsigned IdxI = StoreCount * LaneLen * Factor + i;
8452       if (Mask[IdxI] >= 0) {
8453         Ops.push_back(Builder.CreateShuffleVector(
8454             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8455       } else {
8456         unsigned StartMask = 0;
8457         for (unsigned j = 1; j < LaneLen; j++) {
8458           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8459           if (Mask[IdxJ * Factor + IdxI] >= 0) {
8460             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8461             break;
8462           }
8463         }
8464         // Note: Filling undef gaps with random elements is ok, since
8465         // those elements were being written anyway (with undefs).
8466         // In the case of all undefs we're defaulting to using elems from 0
8467         // Note: StartMask cannot be negative, it's checked in
8468         // isReInterleaveMask
8469         Ops.push_back(Builder.CreateShuffleVector(
8470             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8471       }
8472     }
8473 
8474     // If we generating more than one store, we compute the base address of
8475     // subsequent stores as an offset from the previous.
8476     if (StoreCount > 0)
8477       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
8478 
8479     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8480     Builder.CreateCall(StNFunc, Ops);
8481   }
8482   return true;
8483 }
8484 
8485 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8486                        unsigned AlignCheck) {
8487   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8488           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8489 }
8490 
8491 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8492                                                unsigned SrcAlign, bool IsMemset,
8493                                                bool ZeroMemset,
8494                                                bool MemcpyStrSrc,
8495                                                MachineFunction &MF) const {
8496   const Function &F = MF.getFunction();
8497   bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8498   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8499   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8500   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8501   // taken one instruction to materialize the v2i64 zero and one store (with
8502   // restrictive addressing mode). Just do i64 stores.
8503   bool IsSmallMemset = IsMemset && Size < 32;
8504   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8505     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8506       return true;
8507     bool Fast;
8508     return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8509   };
8510 
8511   if (CanUseNEON && IsMemset && !IsSmallMemset &&
8512       AlignmentIsAcceptable(MVT::v2i64, 16))
8513     return MVT::v2i64;
8514   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8515     return MVT::f128;
8516   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8517     return MVT::i64;
8518   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8519     return MVT::i32;
8520   return MVT::Other;
8521 }
8522 
8523 // 12-bit optionally shifted immediates are legal for adds.
8524 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
8525   if (Immed == std::numeric_limits<int64_t>::min()) {
8526     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8527                       << ": avoid UB for INT64_MIN\n");
8528     return false;
8529   }
8530   // Same encoding for add/sub, just flip the sign.
8531   Immed = std::abs(Immed);
8532   bool IsLegal = ((Immed >> 12) == 0 ||
8533                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8534   LLVM_DEBUG(dbgs() << "Is " << Immed
8535                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
8536   return IsLegal;
8537 }
8538 
8539 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8540 // immediates is the same as for an add or a sub.
8541 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
8542   return isLegalAddImmediate(Immed);
8543 }
8544 
8545 /// isLegalAddressingMode - Return true if the addressing mode represented
8546 /// by AM is legal for this target, for a load/store of the specified type.
8547 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8548                                                   const AddrMode &AM, Type *Ty,
8549                                                   unsigned AS, Instruction *I) const {
8550   // AArch64 has five basic addressing modes:
8551   //  reg
8552   //  reg + 9-bit signed offset
8553   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
8554   //  reg1 + reg2
8555   //  reg + SIZE_IN_BYTES * reg
8556 
8557   // No global is ever allowed as a base.
8558   if (AM.BaseGV)
8559     return false;
8560 
8561   // No reg+reg+imm addressing.
8562   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8563     return false;
8564 
8565   // check reg + imm case:
8566   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8567   uint64_t NumBytes = 0;
8568   if (Ty->isSized()) {
8569     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
8570     NumBytes = NumBits / 8;
8571     if (!isPowerOf2_64(NumBits))
8572       NumBytes = 0;
8573   }
8574 
8575   if (!AM.Scale) {
8576     int64_t Offset = AM.BaseOffs;
8577 
8578     // 9-bit signed offset
8579     if (isInt<9>(Offset))
8580       return true;
8581 
8582     // 12-bit unsigned offset
8583     unsigned shift = Log2_64(NumBytes);
8584     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8585         // Must be a multiple of NumBytes (NumBytes is a power of 2)
8586         (Offset >> shift) << shift == Offset)
8587       return true;
8588     return false;
8589   }
8590 
8591   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8592 
8593   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8594 }
8595 
8596 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8597   // Consider splitting large offset of struct or array.
8598   return true;
8599 }
8600 
8601 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8602                                                 const AddrMode &AM, Type *Ty,
8603                                                 unsigned AS) const {
8604   // Scaling factors are not free at all.
8605   // Operands                     | Rt Latency
8606   // -------------------------------------------
8607   // Rt, [Xn, Xm]                 | 4
8608   // -------------------------------------------
8609   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
8610   // Rt, [Xn, Wm, <extend> #imm]  |
8611   if (isLegalAddressingMode(DL, AM, Ty, AS))
8612     // Scale represents reg2 * scale, thus account for 1 if
8613     // it is not equal to 0 or 1.
8614     return AM.Scale != 0 && AM.Scale != 1;
8615   return -1;
8616 }
8617 
8618 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8619   VT = VT.getScalarType();
8620 
8621   if (!VT.isSimple())
8622     return false;
8623 
8624   switch (VT.getSimpleVT().SimpleTy) {
8625   case MVT::f32:
8626   case MVT::f64:
8627     return true;
8628   default:
8629     break;
8630   }
8631 
8632   return false;
8633 }
8634 
8635 const MCPhysReg *
8636 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8637   // LR is a callee-save register, but we must treat it as clobbered by any call
8638   // site. Hence we include LR in the scratch registers, which are in turn added
8639   // as implicit-defs for stackmaps and patchpoints.
8640   static const MCPhysReg ScratchRegs[] = {
8641     AArch64::X16, AArch64::X17, AArch64::LR, 0
8642   };
8643   return ScratchRegs;
8644 }
8645 
8646 bool
8647 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8648                                                      CombineLevel Level) const {
8649   N = N->getOperand(0).getNode();
8650   EVT VT = N->getValueType(0);
8651     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8652     // it with shift to let it be lowered to UBFX.
8653   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8654       isa<ConstantSDNode>(N->getOperand(1))) {
8655     uint64_t TruncMask = N->getConstantOperandVal(1);
8656     if (isMask_64(TruncMask) &&
8657       N->getOperand(0).getOpcode() == ISD::SRL &&
8658       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8659       return false;
8660   }
8661   return true;
8662 }
8663 
8664 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8665                                                               Type *Ty) const {
8666   assert(Ty->isIntegerTy());
8667 
8668   unsigned BitSize = Ty->getPrimitiveSizeInBits();
8669   if (BitSize == 0)
8670     return false;
8671 
8672   int64_t Val = Imm.getSExtValue();
8673   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8674     return true;
8675 
8676   if ((int64_t)Val < 0)
8677     Val = ~Val;
8678   if (BitSize == 32)
8679     Val &= (1LL << 32) - 1;
8680 
8681   unsigned LZ = countLeadingZeros((uint64_t)Val);
8682   unsigned Shift = (63 - LZ) / 16;
8683   // MOVZ is free so return true for one or fewer MOVK.
8684   return Shift < 3;
8685 }
8686 
8687 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8688                                                     unsigned Index) const {
8689   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8690     return false;
8691 
8692   return (Index == 0 || Index == ResVT.getVectorNumElements());
8693 }
8694 
8695 /// Turn vector tests of the signbit in the form of:
8696 ///   xor (sra X, elt_size(X)-1), -1
8697 /// into:
8698 ///   cmge X, X, #0
8699 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8700                                          const AArch64Subtarget *Subtarget) {
8701   EVT VT = N->getValueType(0);
8702   if (!Subtarget->hasNEON() || !VT.isVector())
8703     return SDValue();
8704 
8705   // There must be a shift right algebraic before the xor, and the xor must be a
8706   // 'not' operation.
8707   SDValue Shift = N->getOperand(0);
8708   SDValue Ones = N->getOperand(1);
8709   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8710       !ISD::isBuildVectorAllOnes(Ones.getNode()))
8711     return SDValue();
8712 
8713   // The shift should be smearing the sign bit across each vector element.
8714   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8715   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8716   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8717     return SDValue();
8718 
8719   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8720 }
8721 
8722 // Generate SUBS and CSEL for integer abs.
8723 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8724   EVT VT = N->getValueType(0);
8725 
8726   SDValue N0 = N->getOperand(0);
8727   SDValue N1 = N->getOperand(1);
8728   SDLoc DL(N);
8729 
8730   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8731   // and change it to SUB and CSEL.
8732   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8733       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8734       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8735     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8736       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
8737         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
8738                                   N0.getOperand(0));
8739         // Generate SUBS & CSEL.
8740         SDValue Cmp =
8741             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
8742                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
8743         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8744                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8745                            SDValue(Cmp.getNode(), 1));
8746       }
8747   return SDValue();
8748 }
8749 
8750 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8751                                  TargetLowering::DAGCombinerInfo &DCI,
8752                                  const AArch64Subtarget *Subtarget) {
8753   if (DCI.isBeforeLegalizeOps())
8754     return SDValue();
8755 
8756   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8757     return Cmp;
8758 
8759   return performIntegerAbsCombine(N, DAG);
8760 }
8761 
8762 SDValue
8763 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8764                                      SelectionDAG &DAG,
8765                                      SmallVectorImpl<SDNode *> &Created) const {
8766   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
8767   if (isIntDivCheap(N->getValueType(0), Attr))
8768     return SDValue(N,0); // Lower SDIV as SDIV
8769 
8770   // fold (sdiv X, pow2)
8771   EVT VT = N->getValueType(0);
8772   if ((VT != MVT::i32 && VT != MVT::i64) ||
8773       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8774     return SDValue();
8775 
8776   SDLoc DL(N);
8777   SDValue N0 = N->getOperand(0);
8778   unsigned Lg2 = Divisor.countTrailingZeros();
8779   SDValue Zero = DAG.getConstant(0, DL, VT);
8780   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8781 
8782   // Add (N0 < 0) ? Pow2 - 1 : 0;
8783   SDValue CCVal;
8784   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8785   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8786   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8787 
8788   Created.push_back(Cmp.getNode());
8789   Created.push_back(Add.getNode());
8790   Created.push_back(CSel.getNode());
8791 
8792   // Divide by pow2.
8793   SDValue SRA =
8794       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8795 
8796   // If we're dividing by a positive value, we're done.  Otherwise, we must
8797   // negate the result.
8798   if (Divisor.isNonNegative())
8799     return SRA;
8800 
8801   Created.push_back(SRA.getNode());
8802   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8803 }
8804 
8805 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8806                                  TargetLowering::DAGCombinerInfo &DCI,
8807                                  const AArch64Subtarget *Subtarget) {
8808   if (DCI.isBeforeLegalizeOps())
8809     return SDValue();
8810 
8811   // The below optimizations require a constant RHS.
8812   if (!isa<ConstantSDNode>(N->getOperand(1)))
8813     return SDValue();
8814 
8815   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8816   const APInt &ConstValue = C->getAPIntValue();
8817 
8818   // Multiplication of a power of two plus/minus one can be done more
8819   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8820   // future CPUs have a cheaper MADD instruction, this may need to be
8821   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8822   // 64-bit is 5 cycles, so this is always a win.
8823   // More aggressively, some multiplications N0 * C can be lowered to
8824   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8825   // e.g. 6=3*2=(2+1)*2.
8826   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8827   // which equals to (1+2)*16-(1+2).
8828   SDValue N0 = N->getOperand(0);
8829   // TrailingZeroes is used to test if the mul can be lowered to
8830   // shift+add+shift.
8831   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8832   if (TrailingZeroes) {
8833     // Conservatively do not lower to shift+add+shift if the mul might be
8834     // folded into smul or umul.
8835     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8836                             isZeroExtended(N0.getNode(), DAG)))
8837       return SDValue();
8838     // Conservatively do not lower to shift+add+shift if the mul might be
8839     // folded into madd or msub.
8840     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8841                            N->use_begin()->getOpcode() == ISD::SUB))
8842       return SDValue();
8843   }
8844   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8845   // and shift+add+shift.
8846   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8847 
8848   unsigned ShiftAmt, AddSubOpc;
8849   // Is the shifted value the LHS operand of the add/sub?
8850   bool ShiftValUseIsN0 = true;
8851   // Do we need to negate the result?
8852   bool NegateResult = false;
8853 
8854   if (ConstValue.isNonNegative()) {
8855     // (mul x, 2^N + 1) => (add (shl x, N), x)
8856     // (mul x, 2^N - 1) => (sub (shl x, N), x)
8857     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8858     APInt SCVMinus1 = ShiftedConstValue - 1;
8859     APInt CVPlus1 = ConstValue + 1;
8860     if (SCVMinus1.isPowerOf2()) {
8861       ShiftAmt = SCVMinus1.logBase2();
8862       AddSubOpc = ISD::ADD;
8863     } else if (CVPlus1.isPowerOf2()) {
8864       ShiftAmt = CVPlus1.logBase2();
8865       AddSubOpc = ISD::SUB;
8866     } else
8867       return SDValue();
8868   } else {
8869     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8870     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8871     APInt CVNegPlus1 = -ConstValue + 1;
8872     APInt CVNegMinus1 = -ConstValue - 1;
8873     if (CVNegPlus1.isPowerOf2()) {
8874       ShiftAmt = CVNegPlus1.logBase2();
8875       AddSubOpc = ISD::SUB;
8876       ShiftValUseIsN0 = false;
8877     } else if (CVNegMinus1.isPowerOf2()) {
8878       ShiftAmt = CVNegMinus1.logBase2();
8879       AddSubOpc = ISD::ADD;
8880       NegateResult = true;
8881     } else
8882       return SDValue();
8883   }
8884 
8885   SDLoc DL(N);
8886   EVT VT = N->getValueType(0);
8887   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8888                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
8889 
8890   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8891   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8892   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8893   assert(!(NegateResult && TrailingZeroes) &&
8894          "NegateResult and TrailingZeroes cannot both be true for now.");
8895   // Negate the result.
8896   if (NegateResult)
8897     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8898   // Shift the result.
8899   if (TrailingZeroes)
8900     return DAG.getNode(ISD::SHL, DL, VT, Res,
8901                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8902   return Res;
8903 }
8904 
8905 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8906                                                          SelectionDAG &DAG) {
8907   // Take advantage of vector comparisons producing 0 or -1 in each lane to
8908   // optimize away operation when it's from a constant.
8909   //
8910   // The general transformation is:
8911   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8912   //       AND(VECTOR_CMP(x,y), constant2)
8913   //    constant2 = UNARYOP(constant)
8914 
8915   // Early exit if this isn't a vector operation, the operand of the
8916   // unary operation isn't a bitwise AND, or if the sizes of the operations
8917   // aren't the same.
8918   EVT VT = N->getValueType(0);
8919   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8920       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8921       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8922     return SDValue();
8923 
8924   // Now check that the other operand of the AND is a constant. We could
8925   // make the transformation for non-constant splats as well, but it's unclear
8926   // that would be a benefit as it would not eliminate any operations, just
8927   // perform one more step in scalar code before moving to the vector unit.
8928   if (BuildVectorSDNode *BV =
8929           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8930     // Bail out if the vector isn't a constant.
8931     if (!BV->isConstant())
8932       return SDValue();
8933 
8934     // Everything checks out. Build up the new and improved node.
8935     SDLoc DL(N);
8936     EVT IntVT = BV->getValueType(0);
8937     // Create a new constant of the appropriate type for the transformed
8938     // DAG.
8939     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8940     // The AND node needs bitcasts to/from an integer vector type around it.
8941     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8942     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8943                                  N->getOperand(0)->getOperand(0), MaskConst);
8944     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8945     return Res;
8946   }
8947 
8948   return SDValue();
8949 }
8950 
8951 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8952                                      const AArch64Subtarget *Subtarget) {
8953   // First try to optimize away the conversion when it's conditionally from
8954   // a constant. Vectors only.
8955   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8956     return Res;
8957 
8958   EVT VT = N->getValueType(0);
8959   if (VT != MVT::f32 && VT != MVT::f64)
8960     return SDValue();
8961 
8962   // Only optimize when the source and destination types have the same width.
8963   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8964     return SDValue();
8965 
8966   // If the result of an integer load is only used by an integer-to-float
8967   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8968   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8969   SDValue N0 = N->getOperand(0);
8970   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8971       // Do not change the width of a volatile load.
8972       !cast<LoadSDNode>(N0)->isVolatile()) {
8973     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8974     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8975                                LN0->getPointerInfo(), LN0->getAlignment(),
8976                                LN0->getMemOperand()->getFlags());
8977 
8978     // Make sure successors of the original load stay after it by updating them
8979     // to use the new Chain.
8980     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8981 
8982     unsigned Opcode =
8983         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8984     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8985   }
8986 
8987   return SDValue();
8988 }
8989 
8990 /// Fold a floating-point multiply by power of two into floating-point to
8991 /// fixed-point conversion.
8992 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8993                                      TargetLowering::DAGCombinerInfo &DCI,
8994                                      const AArch64Subtarget *Subtarget) {
8995   if (!Subtarget->hasNEON())
8996     return SDValue();
8997 
8998   SDValue Op = N->getOperand(0);
8999   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9000       Op.getOpcode() != ISD::FMUL)
9001     return SDValue();
9002 
9003   SDValue ConstVec = Op->getOperand(1);
9004   if (!isa<BuildVectorSDNode>(ConstVec))
9005     return SDValue();
9006 
9007   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9008   uint32_t FloatBits = FloatTy.getSizeInBits();
9009   if (FloatBits != 32 && FloatBits != 64)
9010     return SDValue();
9011 
9012   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9013   uint32_t IntBits = IntTy.getSizeInBits();
9014   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9015     return SDValue();
9016 
9017   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9018   if (IntBits > FloatBits)
9019     return SDValue();
9020 
9021   BitVector UndefElements;
9022   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9023   int32_t Bits = IntBits == 64 ? 64 : 32;
9024   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9025   if (C == -1 || C == 0 || C > Bits)
9026     return SDValue();
9027 
9028   MVT ResTy;
9029   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9030   switch (NumLanes) {
9031   default:
9032     return SDValue();
9033   case 2:
9034     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9035     break;
9036   case 4:
9037     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9038     break;
9039   }
9040 
9041   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9042     return SDValue();
9043 
9044   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9045          "Illegal vector type after legalization");
9046 
9047   SDLoc DL(N);
9048   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9049   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9050                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
9051   SDValue FixConv =
9052       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9053                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9054                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9055   // We can handle smaller integers by generating an extra trunc.
9056   if (IntBits < FloatBits)
9057     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9058 
9059   return FixConv;
9060 }
9061 
9062 /// Fold a floating-point divide by power of two into fixed-point to
9063 /// floating-point conversion.
9064 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9065                                   TargetLowering::DAGCombinerInfo &DCI,
9066                                   const AArch64Subtarget *Subtarget) {
9067   if (!Subtarget->hasNEON())
9068     return SDValue();
9069 
9070   SDValue Op = N->getOperand(0);
9071   unsigned Opc = Op->getOpcode();
9072   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9073       !Op.getOperand(0).getValueType().isSimple() ||
9074       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9075     return SDValue();
9076 
9077   SDValue ConstVec = N->getOperand(1);
9078   if (!isa<BuildVectorSDNode>(ConstVec))
9079     return SDValue();
9080 
9081   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9082   int32_t IntBits = IntTy.getSizeInBits();
9083   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9084     return SDValue();
9085 
9086   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9087   int32_t FloatBits = FloatTy.getSizeInBits();
9088   if (FloatBits != 32 && FloatBits != 64)
9089     return SDValue();
9090 
9091   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9092   if (IntBits > FloatBits)
9093     return SDValue();
9094 
9095   BitVector UndefElements;
9096   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9097   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9098   if (C == -1 || C == 0 || C > FloatBits)
9099     return SDValue();
9100 
9101   MVT ResTy;
9102   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9103   switch (NumLanes) {
9104   default:
9105     return SDValue();
9106   case 2:
9107     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9108     break;
9109   case 4:
9110     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9111     break;
9112   }
9113 
9114   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9115     return SDValue();
9116 
9117   SDLoc DL(N);
9118   SDValue ConvInput = Op.getOperand(0);
9119   bool IsSigned = Opc == ISD::SINT_TO_FP;
9120   if (IntBits < FloatBits)
9121     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9122                             ResTy, ConvInput);
9123 
9124   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9125                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
9126   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9127                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9128                      DAG.getConstant(C, DL, MVT::i32));
9129 }
9130 
9131 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9132 /// searches for and classifies those shifts.
9133 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9134                          bool &FromHi) {
9135   if (N.getOpcode() == ISD::SHL)
9136     FromHi = false;
9137   else if (N.getOpcode() == ISD::SRL)
9138     FromHi = true;
9139   else
9140     return false;
9141 
9142   if (!isa<ConstantSDNode>(N.getOperand(1)))
9143     return false;
9144 
9145   ShiftAmount = N->getConstantOperandVal(1);
9146   Src = N->getOperand(0);
9147   return true;
9148 }
9149 
9150 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9151 /// registers viewed as a high/low pair. This function looks for the pattern:
9152 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9153 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9154 /// aren't independent.
9155 static SDValue tryCombineToEXTR(SDNode *N,
9156                                 TargetLowering::DAGCombinerInfo &DCI) {
9157   SelectionDAG &DAG = DCI.DAG;
9158   SDLoc DL(N);
9159   EVT VT = N->getValueType(0);
9160 
9161   assert(N->getOpcode() == ISD::OR && "Unexpected root");
9162 
9163   if (VT != MVT::i32 && VT != MVT::i64)
9164     return SDValue();
9165 
9166   SDValue LHS;
9167   uint32_t ShiftLHS = 0;
9168   bool LHSFromHi = false;
9169   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9170     return SDValue();
9171 
9172   SDValue RHS;
9173   uint32_t ShiftRHS = 0;
9174   bool RHSFromHi = false;
9175   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9176     return SDValue();
9177 
9178   // If they're both trying to come from the high part of the register, they're
9179   // not really an EXTR.
9180   if (LHSFromHi == RHSFromHi)
9181     return SDValue();
9182 
9183   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9184     return SDValue();
9185 
9186   if (LHSFromHi) {
9187     std::swap(LHS, RHS);
9188     std::swap(ShiftLHS, ShiftRHS);
9189   }
9190 
9191   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9192                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
9193 }
9194 
9195 static SDValue tryCombineToBSL(SDNode *N,
9196                                 TargetLowering::DAGCombinerInfo &DCI) {
9197   EVT VT = N->getValueType(0);
9198   SelectionDAG &DAG = DCI.DAG;
9199   SDLoc DL(N);
9200 
9201   if (!VT.isVector())
9202     return SDValue();
9203 
9204   SDValue N0 = N->getOperand(0);
9205   if (N0.getOpcode() != ISD::AND)
9206     return SDValue();
9207 
9208   SDValue N1 = N->getOperand(1);
9209   if (N1.getOpcode() != ISD::AND)
9210     return SDValue();
9211 
9212   // We only have to look for constant vectors here since the general, variable
9213   // case can be handled in TableGen.
9214   unsigned Bits = VT.getScalarSizeInBits();
9215   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9216   for (int i = 1; i >= 0; --i)
9217     for (int j = 1; j >= 0; --j) {
9218       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9219       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9220       if (!BVN0 || !BVN1)
9221         continue;
9222 
9223       bool FoundMatch = true;
9224       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9225         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9226         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9227         if (!CN0 || !CN1 ||
9228             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9229           FoundMatch = false;
9230           break;
9231         }
9232       }
9233 
9234       if (FoundMatch)
9235         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9236                            N0->getOperand(1 - i), N1->getOperand(1 - j));
9237     }
9238 
9239   return SDValue();
9240 }
9241 
9242 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9243                                 const AArch64Subtarget *Subtarget) {
9244   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9245   SelectionDAG &DAG = DCI.DAG;
9246   EVT VT = N->getValueType(0);
9247 
9248   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9249     return SDValue();
9250 
9251   if (SDValue Res = tryCombineToEXTR(N, DCI))
9252     return Res;
9253 
9254   if (SDValue Res = tryCombineToBSL(N, DCI))
9255     return Res;
9256 
9257   return SDValue();
9258 }
9259 
9260 static SDValue performSRLCombine(SDNode *N,
9261                                  TargetLowering::DAGCombinerInfo &DCI) {
9262   SelectionDAG &DAG = DCI.DAG;
9263   EVT VT = N->getValueType(0);
9264   if (VT != MVT::i32 && VT != MVT::i64)
9265     return SDValue();
9266 
9267   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9268   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9269   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9270   SDValue N0 = N->getOperand(0);
9271   if (N0.getOpcode() == ISD::BSWAP) {
9272     SDLoc DL(N);
9273     SDValue N1 = N->getOperand(1);
9274     SDValue N00 = N0.getOperand(0);
9275     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9276       uint64_t ShiftAmt = C->getZExtValue();
9277       if (VT == MVT::i32 && ShiftAmt == 16 &&
9278           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9279         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9280       if (VT == MVT::i64 && ShiftAmt == 32 &&
9281           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9282         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9283     }
9284   }
9285   return SDValue();
9286 }
9287 
9288 static SDValue performBitcastCombine(SDNode *N,
9289                                      TargetLowering::DAGCombinerInfo &DCI,
9290                                      SelectionDAG &DAG) {
9291   // Wait 'til after everything is legalized to try this. That way we have
9292   // legal vector types and such.
9293   if (DCI.isBeforeLegalizeOps())
9294     return SDValue();
9295 
9296   // Remove extraneous bitcasts around an extract_subvector.
9297   // For example,
9298   //    (v4i16 (bitconvert
9299   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9300   //  becomes
9301   //    (extract_subvector ((v8i16 ...), (i64 4)))
9302 
9303   // Only interested in 64-bit vectors as the ultimate result.
9304   EVT VT = N->getValueType(0);
9305   if (!VT.isVector())
9306     return SDValue();
9307   if (VT.getSimpleVT().getSizeInBits() != 64)
9308     return SDValue();
9309   // Is the operand an extract_subvector starting at the beginning or halfway
9310   // point of the vector? A low half may also come through as an
9311   // EXTRACT_SUBREG, so look for that, too.
9312   SDValue Op0 = N->getOperand(0);
9313   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9314       !(Op0->isMachineOpcode() &&
9315         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9316     return SDValue();
9317   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9318   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9319     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9320       return SDValue();
9321   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9322     if (idx != AArch64::dsub)
9323       return SDValue();
9324     // The dsub reference is equivalent to a lane zero subvector reference.
9325     idx = 0;
9326   }
9327   // Look through the bitcast of the input to the extract.
9328   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9329     return SDValue();
9330   SDValue Source = Op0->getOperand(0)->getOperand(0);
9331   // If the source type has twice the number of elements as our destination
9332   // type, we know this is an extract of the high or low half of the vector.
9333   EVT SVT = Source->getValueType(0);
9334   if (!SVT.isVector() ||
9335       SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9336     return SDValue();
9337 
9338   LLVM_DEBUG(
9339       dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9340 
9341   // Create the simplified form to just extract the low or high half of the
9342   // vector directly rather than bothering with the bitcasts.
9343   SDLoc dl(N);
9344   unsigned NumElements = VT.getVectorNumElements();
9345   if (idx) {
9346     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9347     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9348   } else {
9349     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9350     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9351                                       Source, SubReg),
9352                    0);
9353   }
9354 }
9355 
9356 static SDValue performConcatVectorsCombine(SDNode *N,
9357                                            TargetLowering::DAGCombinerInfo &DCI,
9358                                            SelectionDAG &DAG) {
9359   SDLoc dl(N);
9360   EVT VT = N->getValueType(0);
9361   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9362 
9363   // Optimize concat_vectors of truncated vectors, where the intermediate
9364   // type is illegal, to avoid said illegality,  e.g.,
9365   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9366   //                          (v2i16 (truncate (v2i64)))))
9367   // ->
9368   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9369   //                                    (v4i32 (bitcast (v2i64))),
9370   //                                    <0, 2, 4, 6>)))
9371   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9372   // on both input and result type, so we might generate worse code.
9373   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9374   if (N->getNumOperands() == 2 &&
9375       N0->getOpcode() == ISD::TRUNCATE &&
9376       N1->getOpcode() == ISD::TRUNCATE) {
9377     SDValue N00 = N0->getOperand(0);
9378     SDValue N10 = N1->getOperand(0);
9379     EVT N00VT = N00.getValueType();
9380 
9381     if (N00VT == N10.getValueType() &&
9382         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9383         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9384       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9385       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9386       for (size_t i = 0; i < Mask.size(); ++i)
9387         Mask[i] = i * 2;
9388       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9389                          DAG.getVectorShuffle(
9390                              MidVT, dl,
9391                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9392                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9393     }
9394   }
9395 
9396   // Wait 'til after everything is legalized to try this. That way we have
9397   // legal vector types and such.
9398   if (DCI.isBeforeLegalizeOps())
9399     return SDValue();
9400 
9401   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9402   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9403   // canonicalise to that.
9404   if (N0 == N1 && VT.getVectorNumElements() == 2) {
9405     assert(VT.getScalarSizeInBits() == 64);
9406     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9407                        DAG.getConstant(0, dl, MVT::i64));
9408   }
9409 
9410   // Canonicalise concat_vectors so that the right-hand vector has as few
9411   // bit-casts as possible before its real operation. The primary matching
9412   // destination for these operations will be the narrowing "2" instructions,
9413   // which depend on the operation being performed on this right-hand vector.
9414   // For example,
9415   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
9416   // becomes
9417   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9418 
9419   if (N1->getOpcode() != ISD::BITCAST)
9420     return SDValue();
9421   SDValue RHS = N1->getOperand(0);
9422   MVT RHSTy = RHS.getValueType().getSimpleVT();
9423   // If the RHS is not a vector, this is not the pattern we're looking for.
9424   if (!RHSTy.isVector())
9425     return SDValue();
9426 
9427   LLVM_DEBUG(
9428       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9429 
9430   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9431                                   RHSTy.getVectorNumElements() * 2);
9432   return DAG.getNode(ISD::BITCAST, dl, VT,
9433                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9434                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9435                                  RHS));
9436 }
9437 
9438 static SDValue tryCombineFixedPointConvert(SDNode *N,
9439                                            TargetLowering::DAGCombinerInfo &DCI,
9440                                            SelectionDAG &DAG) {
9441   // Wait until after everything is legalized to try this. That way we have
9442   // legal vector types and such.
9443   if (DCI.isBeforeLegalizeOps())
9444     return SDValue();
9445   // Transform a scalar conversion of a value from a lane extract into a
9446   // lane extract of a vector conversion. E.g., from foo1 to foo2:
9447   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9448   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9449   //
9450   // The second form interacts better with instruction selection and the
9451   // register allocator to avoid cross-class register copies that aren't
9452   // coalescable due to a lane reference.
9453 
9454   // Check the operand and see if it originates from a lane extract.
9455   SDValue Op1 = N->getOperand(1);
9456   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9457     // Yep, no additional predication needed. Perform the transform.
9458     SDValue IID = N->getOperand(0);
9459     SDValue Shift = N->getOperand(2);
9460     SDValue Vec = Op1.getOperand(0);
9461     SDValue Lane = Op1.getOperand(1);
9462     EVT ResTy = N->getValueType(0);
9463     EVT VecResTy;
9464     SDLoc DL(N);
9465 
9466     // The vector width should be 128 bits by the time we get here, even
9467     // if it started as 64 bits (the extract_vector handling will have
9468     // done so).
9469     assert(Vec.getValueSizeInBits() == 128 &&
9470            "unexpected vector size on extract_vector_elt!");
9471     if (Vec.getValueType() == MVT::v4i32)
9472       VecResTy = MVT::v4f32;
9473     else if (Vec.getValueType() == MVT::v2i64)
9474       VecResTy = MVT::v2f64;
9475     else
9476       llvm_unreachable("unexpected vector type!");
9477 
9478     SDValue Convert =
9479         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9480     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9481   }
9482   return SDValue();
9483 }
9484 
9485 // AArch64 high-vector "long" operations are formed by performing the non-high
9486 // version on an extract_subvector of each operand which gets the high half:
9487 //
9488 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9489 //
9490 // However, there are cases which don't have an extract_high explicitly, but
9491 // have another operation that can be made compatible with one for free. For
9492 // example:
9493 //
9494 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
9495 //
9496 // This routine does the actual conversion of such DUPs, once outer routines
9497 // have determined that everything else is in order.
9498 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9499 // similarly here.
9500 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
9501   switch (N.getOpcode()) {
9502   case AArch64ISD::DUP:
9503   case AArch64ISD::DUPLANE8:
9504   case AArch64ISD::DUPLANE16:
9505   case AArch64ISD::DUPLANE32:
9506   case AArch64ISD::DUPLANE64:
9507   case AArch64ISD::MOVI:
9508   case AArch64ISD::MOVIshift:
9509   case AArch64ISD::MOVIedit:
9510   case AArch64ISD::MOVImsl:
9511   case AArch64ISD::MVNIshift:
9512   case AArch64ISD::MVNImsl:
9513     break;
9514   default:
9515     // FMOV could be supported, but isn't very useful, as it would only occur
9516     // if you passed a bitcast' floating point immediate to an eligible long
9517     // integer op (addl, smull, ...).
9518     return SDValue();
9519   }
9520 
9521   MVT NarrowTy = N.getSimpleValueType();
9522   if (!NarrowTy.is64BitVector())
9523     return SDValue();
9524 
9525   MVT ElementTy = NarrowTy.getVectorElementType();
9526   unsigned NumElems = NarrowTy.getVectorNumElements();
9527   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
9528 
9529   SDLoc dl(N);
9530   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9531                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
9532                      DAG.getConstant(NumElems, dl, MVT::i64));
9533 }
9534 
9535 static bool isEssentiallyExtractSubvector(SDValue N) {
9536   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9537     return true;
9538 
9539   return N.getOpcode() == ISD::BITCAST &&
9540          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9541 }
9542 
9543 /// Helper structure to keep track of ISD::SET_CC operands.
9544 struct GenericSetCCInfo {
9545   const SDValue *Opnd0;
9546   const SDValue *Opnd1;
9547   ISD::CondCode CC;
9548 };
9549 
9550 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9551 struct AArch64SetCCInfo {
9552   const SDValue *Cmp;
9553   AArch64CC::CondCode CC;
9554 };
9555 
9556 /// Helper structure to keep track of SetCC information.
9557 union SetCCInfo {
9558   GenericSetCCInfo Generic;
9559   AArch64SetCCInfo AArch64;
9560 };
9561 
9562 /// Helper structure to be able to read SetCC information.  If set to
9563 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9564 /// GenericSetCCInfo.
9565 struct SetCCInfoAndKind {
9566   SetCCInfo Info;
9567   bool IsAArch64;
9568 };
9569 
9570 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9571 /// an
9572 /// AArch64 lowered one.
9573 /// \p SetCCInfo is filled accordingly.
9574 /// \post SetCCInfo is meanginfull only when this function returns true.
9575 /// \return True when Op is a kind of SET_CC operation.
9576 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9577   // If this is a setcc, this is straight forward.
9578   if (Op.getOpcode() == ISD::SETCC) {
9579     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9580     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9581     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9582     SetCCInfo.IsAArch64 = false;
9583     return true;
9584   }
9585   // Otherwise, check if this is a matching csel instruction.
9586   // In other words:
9587   // - csel 1, 0, cc
9588   // - csel 0, 1, !cc
9589   if (Op.getOpcode() != AArch64ISD::CSEL)
9590     return false;
9591   // Set the information about the operands.
9592   // TODO: we want the operands of the Cmp not the csel
9593   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9594   SetCCInfo.IsAArch64 = true;
9595   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9596       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9597 
9598   // Check that the operands matches the constraints:
9599   // (1) Both operands must be constants.
9600   // (2) One must be 1 and the other must be 0.
9601   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9602   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9603 
9604   // Check (1).
9605   if (!TValue || !FValue)
9606     return false;
9607 
9608   // Check (2).
9609   if (!TValue->isOne()) {
9610     // Update the comparison when we are interested in !cc.
9611     std::swap(TValue, FValue);
9612     SetCCInfo.Info.AArch64.CC =
9613         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9614   }
9615   return TValue->isOne() && FValue->isNullValue();
9616 }
9617 
9618 // Returns true if Op is setcc or zext of setcc.
9619 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9620   if (isSetCC(Op, Info))
9621     return true;
9622   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9623     isSetCC(Op->getOperand(0), Info));
9624 }
9625 
9626 // The folding we want to perform is:
9627 // (add x, [zext] (setcc cc ...) )
9628 //   -->
9629 // (csel x, (add x, 1), !cc ...)
9630 //
9631 // The latter will get matched to a CSINC instruction.
9632 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9633   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9634   SDValue LHS = Op->getOperand(0);
9635   SDValue RHS = Op->getOperand(1);
9636   SetCCInfoAndKind InfoAndKind;
9637 
9638   // If neither operand is a SET_CC, give up.
9639   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9640     std::swap(LHS, RHS);
9641     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9642       return SDValue();
9643   }
9644 
9645   // FIXME: This could be generatized to work for FP comparisons.
9646   EVT CmpVT = InfoAndKind.IsAArch64
9647                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9648                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
9649   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9650     return SDValue();
9651 
9652   SDValue CCVal;
9653   SDValue Cmp;
9654   SDLoc dl(Op);
9655   if (InfoAndKind.IsAArch64) {
9656     CCVal = DAG.getConstant(
9657         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9658         MVT::i32);
9659     Cmp = *InfoAndKind.Info.AArch64.Cmp;
9660   } else
9661     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9662                       *InfoAndKind.Info.Generic.Opnd1,
9663                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9664                       CCVal, DAG, dl);
9665 
9666   EVT VT = Op->getValueType(0);
9667   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
9668   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9669 }
9670 
9671 // The basic add/sub long vector instructions have variants with "2" on the end
9672 // which act on the high-half of their inputs. They are normally matched by
9673 // patterns like:
9674 //
9675 // (add (zeroext (extract_high LHS)),
9676 //      (zeroext (extract_high RHS)))
9677 // -> uaddl2 vD, vN, vM
9678 //
9679 // However, if one of the extracts is something like a duplicate, this
9680 // instruction can still be used profitably. This function puts the DAG into a
9681 // more appropriate form for those patterns to trigger.
9682 static SDValue performAddSubLongCombine(SDNode *N,
9683                                         TargetLowering::DAGCombinerInfo &DCI,
9684                                         SelectionDAG &DAG) {
9685   if (DCI.isBeforeLegalizeOps())
9686     return SDValue();
9687 
9688   MVT VT = N->getSimpleValueType(0);
9689   if (!VT.is128BitVector()) {
9690     if (N->getOpcode() == ISD::ADD)
9691       return performSetccAddFolding(N, DAG);
9692     return SDValue();
9693   }
9694 
9695   // Make sure both branches are extended in the same way.
9696   SDValue LHS = N->getOperand(0);
9697   SDValue RHS = N->getOperand(1);
9698   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9699        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9700       LHS.getOpcode() != RHS.getOpcode())
9701     return SDValue();
9702 
9703   unsigned ExtType = LHS.getOpcode();
9704 
9705   // It's not worth doing if at least one of the inputs isn't already an
9706   // extract, but we don't know which it'll be so we have to try both.
9707   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9708     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9709     if (!RHS.getNode())
9710       return SDValue();
9711 
9712     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9713   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9714     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9715     if (!LHS.getNode())
9716       return SDValue();
9717 
9718     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9719   }
9720 
9721   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9722 }
9723 
9724 // Massage DAGs which we can use the high-half "long" operations on into
9725 // something isel will recognize better. E.g.
9726 //
9727 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9728 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
9729 //                     (extract_high (v2i64 (dup128 scalar)))))
9730 //
9731 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
9732                                        TargetLowering::DAGCombinerInfo &DCI,
9733                                        SelectionDAG &DAG) {
9734   if (DCI.isBeforeLegalizeOps())
9735     return SDValue();
9736 
9737   SDValue LHS = N->getOperand(1);
9738   SDValue RHS = N->getOperand(2);
9739   assert(LHS.getValueType().is64BitVector() &&
9740          RHS.getValueType().is64BitVector() &&
9741          "unexpected shape for long operation");
9742 
9743   // Either node could be a DUP, but it's not worth doing both of them (you'd
9744   // just as well use the non-high version) so look for a corresponding extract
9745   // operation on the other "wing".
9746   if (isEssentiallyExtractSubvector(LHS)) {
9747     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9748     if (!RHS.getNode())
9749       return SDValue();
9750   } else if (isEssentiallyExtractSubvector(RHS)) {
9751     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9752     if (!LHS.getNode())
9753       return SDValue();
9754   }
9755 
9756   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9757                      N->getOperand(0), LHS, RHS);
9758 }
9759 
9760 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9761   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9762   unsigned ElemBits = ElemTy.getSizeInBits();
9763 
9764   int64_t ShiftAmount;
9765   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9766     APInt SplatValue, SplatUndef;
9767     unsigned SplatBitSize;
9768     bool HasAnyUndefs;
9769     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9770                               HasAnyUndefs, ElemBits) ||
9771         SplatBitSize != ElemBits)
9772       return SDValue();
9773 
9774     ShiftAmount = SplatValue.getSExtValue();
9775   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9776     ShiftAmount = CVN->getSExtValue();
9777   } else
9778     return SDValue();
9779 
9780   unsigned Opcode;
9781   bool IsRightShift;
9782   switch (IID) {
9783   default:
9784     llvm_unreachable("Unknown shift intrinsic");
9785   case Intrinsic::aarch64_neon_sqshl:
9786     Opcode = AArch64ISD::SQSHL_I;
9787     IsRightShift = false;
9788     break;
9789   case Intrinsic::aarch64_neon_uqshl:
9790     Opcode = AArch64ISD::UQSHL_I;
9791     IsRightShift = false;
9792     break;
9793   case Intrinsic::aarch64_neon_srshl:
9794     Opcode = AArch64ISD::SRSHR_I;
9795     IsRightShift = true;
9796     break;
9797   case Intrinsic::aarch64_neon_urshl:
9798     Opcode = AArch64ISD::URSHR_I;
9799     IsRightShift = true;
9800     break;
9801   case Intrinsic::aarch64_neon_sqshlu:
9802     Opcode = AArch64ISD::SQSHLU_I;
9803     IsRightShift = false;
9804     break;
9805   }
9806 
9807   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9808     SDLoc dl(N);
9809     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9810                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9811   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9812     SDLoc dl(N);
9813     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9814                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
9815   }
9816 
9817   return SDValue();
9818 }
9819 
9820 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9821 // the intrinsics must be legal and take an i32, this means there's almost
9822 // certainly going to be a zext in the DAG which we can eliminate.
9823 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9824   SDValue AndN = N->getOperand(2);
9825   if (AndN.getOpcode() != ISD::AND)
9826     return SDValue();
9827 
9828   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9829   if (!CMask || CMask->getZExtValue() != Mask)
9830     return SDValue();
9831 
9832   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9833                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9834 }
9835 
9836 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9837                                            SelectionDAG &DAG) {
9838   SDLoc dl(N);
9839   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9840                      DAG.getNode(Opc, dl,
9841                                  N->getOperand(1).getSimpleValueType(),
9842                                  N->getOperand(1)),
9843                      DAG.getConstant(0, dl, MVT::i64));
9844 }
9845 
9846 static SDValue performIntrinsicCombine(SDNode *N,
9847                                        TargetLowering::DAGCombinerInfo &DCI,
9848                                        const AArch64Subtarget *Subtarget) {
9849   SelectionDAG &DAG = DCI.DAG;
9850   unsigned IID = getIntrinsicID(N);
9851   switch (IID) {
9852   default:
9853     break;
9854   case Intrinsic::aarch64_neon_vcvtfxs2fp:
9855   case Intrinsic::aarch64_neon_vcvtfxu2fp:
9856     return tryCombineFixedPointConvert(N, DCI, DAG);
9857   case Intrinsic::aarch64_neon_saddv:
9858     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9859   case Intrinsic::aarch64_neon_uaddv:
9860     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9861   case Intrinsic::aarch64_neon_sminv:
9862     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9863   case Intrinsic::aarch64_neon_uminv:
9864     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9865   case Intrinsic::aarch64_neon_smaxv:
9866     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9867   case Intrinsic::aarch64_neon_umaxv:
9868     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9869   case Intrinsic::aarch64_neon_fmax:
9870     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
9871                        N->getOperand(1), N->getOperand(2));
9872   case Intrinsic::aarch64_neon_fmin:
9873     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
9874                        N->getOperand(1), N->getOperand(2));
9875   case Intrinsic::aarch64_neon_fmaxnm:
9876     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9877                        N->getOperand(1), N->getOperand(2));
9878   case Intrinsic::aarch64_neon_fminnm:
9879     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9880                        N->getOperand(1), N->getOperand(2));
9881   case Intrinsic::aarch64_neon_smull:
9882   case Intrinsic::aarch64_neon_umull:
9883   case Intrinsic::aarch64_neon_pmull:
9884   case Intrinsic::aarch64_neon_sqdmull:
9885     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9886   case Intrinsic::aarch64_neon_sqshl:
9887   case Intrinsic::aarch64_neon_uqshl:
9888   case Intrinsic::aarch64_neon_sqshlu:
9889   case Intrinsic::aarch64_neon_srshl:
9890   case Intrinsic::aarch64_neon_urshl:
9891     return tryCombineShiftImm(IID, N, DAG);
9892   case Intrinsic::aarch64_crc32b:
9893   case Intrinsic::aarch64_crc32cb:
9894     return tryCombineCRC32(0xff, N, DAG);
9895   case Intrinsic::aarch64_crc32h:
9896   case Intrinsic::aarch64_crc32ch:
9897     return tryCombineCRC32(0xffff, N, DAG);
9898   }
9899   return SDValue();
9900 }
9901 
9902 static SDValue performExtendCombine(SDNode *N,
9903                                     TargetLowering::DAGCombinerInfo &DCI,
9904                                     SelectionDAG &DAG) {
9905   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9906   // we can convert that DUP into another extract_high (of a bigger DUP), which
9907   // helps the backend to decide that an sabdl2 would be useful, saving a real
9908   // extract_high operation.
9909   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9910       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9911     SDNode *ABDNode = N->getOperand(0).getNode();
9912     unsigned IID = getIntrinsicID(ABDNode);
9913     if (IID == Intrinsic::aarch64_neon_sabd ||
9914         IID == Intrinsic::aarch64_neon_uabd) {
9915       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9916       if (!NewABD.getNode())
9917         return SDValue();
9918 
9919       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9920                          NewABD);
9921     }
9922   }
9923 
9924   // This is effectively a custom type legalization for AArch64.
9925   //
9926   // Type legalization will split an extend of a small, legal, type to a larger
9927   // illegal type by first splitting the destination type, often creating
9928   // illegal source types, which then get legalized in isel-confusing ways,
9929   // leading to really terrible codegen. E.g.,
9930   //   %result = v8i32 sext v8i8 %value
9931   // becomes
9932   //   %losrc = extract_subreg %value, ...
9933   //   %hisrc = extract_subreg %value, ...
9934   //   %lo = v4i32 sext v4i8 %losrc
9935   //   %hi = v4i32 sext v4i8 %hisrc
9936   // Things go rapidly downhill from there.
9937   //
9938   // For AArch64, the [sz]ext vector instructions can only go up one element
9939   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9940   // take two instructions.
9941   //
9942   // This implies that the most efficient way to do the extend from v8i8
9943   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9944   // the normal splitting to happen for the v8i16->v8i32.
9945 
9946   // This is pre-legalization to catch some cases where the default
9947   // type legalization will create ill-tempered code.
9948   if (!DCI.isBeforeLegalizeOps())
9949     return SDValue();
9950 
9951   // We're only interested in cleaning things up for non-legal vector types
9952   // here. If both the source and destination are legal, things will just
9953   // work naturally without any fiddling.
9954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9955   EVT ResVT = N->getValueType(0);
9956   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9957     return SDValue();
9958   // If the vector type isn't a simple VT, it's beyond the scope of what
9959   // we're  worried about here. Let legalization do its thing and hope for
9960   // the best.
9961   SDValue Src = N->getOperand(0);
9962   EVT SrcVT = Src->getValueType(0);
9963   if (!ResVT.isSimple() || !SrcVT.isSimple())
9964     return SDValue();
9965 
9966   // If the source VT is a 64-bit vector, we can play games and get the
9967   // better results we want.
9968   if (SrcVT.getSizeInBits() != 64)
9969     return SDValue();
9970 
9971   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9972   unsigned ElementCount = SrcVT.getVectorNumElements();
9973   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9974   SDLoc DL(N);
9975   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9976 
9977   // Now split the rest of the operation into two halves, each with a 64
9978   // bit source.
9979   EVT LoVT, HiVT;
9980   SDValue Lo, Hi;
9981   unsigned NumElements = ResVT.getVectorNumElements();
9982   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9983   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9984                                  ResVT.getVectorElementType(), NumElements / 2);
9985 
9986   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9987                                LoVT.getVectorNumElements());
9988   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9989                    DAG.getConstant(0, DL, MVT::i64));
9990   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9991                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9992   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9993   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9994 
9995   // Now combine the parts back together so we still have a single result
9996   // like the combiner expects.
9997   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9998 }
9999 
10000 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10001                                SDValue SplatVal, unsigned NumVecElts) {
10002   unsigned OrigAlignment = St.getAlignment();
10003   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10004 
10005   // Create scalar stores. This is at least as good as the code sequence for a
10006   // split unaligned store which is a dup.s, ext.b, and two stores.
10007   // Most of the time the three stores should be replaced by store pair
10008   // instructions (stp).
10009   SDLoc DL(&St);
10010   SDValue BasePtr = St.getBasePtr();
10011   uint64_t BaseOffset = 0;
10012 
10013   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10014   SDValue NewST1 =
10015       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10016                    OrigAlignment, St.getMemOperand()->getFlags());
10017 
10018   // As this in ISel, we will not merge this add which may degrade results.
10019   if (BasePtr->getOpcode() == ISD::ADD &&
10020       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10021     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10022     BasePtr = BasePtr->getOperand(0);
10023   }
10024 
10025   unsigned Offset = EltOffset;
10026   while (--NumVecElts) {
10027     unsigned Alignment = MinAlign(OrigAlignment, Offset);
10028     SDValue OffsetPtr =
10029         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10030                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10031     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10032                           PtrInfo.getWithOffset(Offset), Alignment,
10033                           St.getMemOperand()->getFlags());
10034     Offset += EltOffset;
10035   }
10036   return NewST1;
10037 }
10038 
10039 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
10040 /// load store optimizer pass will merge them to store pair stores.  This should
10041 /// be better than a movi to create the vector zero followed by a vector store
10042 /// if the zero constant is not re-used, since one instructions and one register
10043 /// live range will be removed.
10044 ///
10045 /// For example, the final generated code should be:
10046 ///
10047 ///   stp xzr, xzr, [x0]
10048 ///
10049 /// instead of:
10050 ///
10051 ///   movi v0.2d, #0
10052 ///   str q0, [x0]
10053 ///
10054 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10055   SDValue StVal = St.getValue();
10056   EVT VT = StVal.getValueType();
10057 
10058   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10059   // 2, 3 or 4 i32 elements.
10060   int NumVecElts = VT.getVectorNumElements();
10061   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10062          VT.getVectorElementType().getSizeInBits() == 64) ||
10063         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10064          VT.getVectorElementType().getSizeInBits() == 32)))
10065     return SDValue();
10066 
10067   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10068     return SDValue();
10069 
10070   // If the zero constant has more than one use then the vector store could be
10071   // better since the constant mov will be amortized and stp q instructions
10072   // should be able to be formed.
10073   if (!StVal.hasOneUse())
10074     return SDValue();
10075 
10076   // If the immediate offset of the address operand is too large for the stp
10077   // instruction, then bail out.
10078   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10079     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10080     if (Offset < -512 || Offset > 504)
10081       return SDValue();
10082   }
10083 
10084   for (int I = 0; I < NumVecElts; ++I) {
10085     SDValue EltVal = StVal.getOperand(I);
10086     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10087       return SDValue();
10088   }
10089 
10090   // Use a CopyFromReg WZR/XZR here to prevent
10091   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10092   SDLoc DL(&St);
10093   unsigned ZeroReg;
10094   EVT ZeroVT;
10095   if (VT.getVectorElementType().getSizeInBits() == 32) {
10096     ZeroReg = AArch64::WZR;
10097     ZeroVT = MVT::i32;
10098   } else {
10099     ZeroReg = AArch64::XZR;
10100     ZeroVT = MVT::i64;
10101   }
10102   SDValue SplatVal =
10103       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10104   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10105 }
10106 
10107 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10108 /// value. The load store optimizer pass will merge them to store pair stores.
10109 /// This has better performance than a splat of the scalar followed by a split
10110 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10111 /// followed by an ext.b and two stores.
10112 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10113   SDValue StVal = St.getValue();
10114   EVT VT = StVal.getValueType();
10115 
10116   // Don't replace floating point stores, they possibly won't be transformed to
10117   // stp because of the store pair suppress pass.
10118   if (VT.isFloatingPoint())
10119     return SDValue();
10120 
10121   // We can express a splat as store pair(s) for 2 or 4 elements.
10122   unsigned NumVecElts = VT.getVectorNumElements();
10123   if (NumVecElts != 4 && NumVecElts != 2)
10124     return SDValue();
10125 
10126   // Check that this is a splat.
10127   // Make sure that each of the relevant vector element locations are inserted
10128   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10129   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10130   SDValue SplatVal;
10131   for (unsigned I = 0; I < NumVecElts; ++I) {
10132     // Check for insert vector elements.
10133     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10134       return SDValue();
10135 
10136     // Check that same value is inserted at each vector element.
10137     if (I == 0)
10138       SplatVal = StVal.getOperand(1);
10139     else if (StVal.getOperand(1) != SplatVal)
10140       return SDValue();
10141 
10142     // Check insert element index.
10143     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10144     if (!CIndex)
10145       return SDValue();
10146     uint64_t IndexVal = CIndex->getZExtValue();
10147     if (IndexVal >= NumVecElts)
10148       return SDValue();
10149     IndexNotInserted.reset(IndexVal);
10150 
10151     StVal = StVal.getOperand(0);
10152   }
10153   // Check that all vector element locations were inserted to.
10154   if (IndexNotInserted.any())
10155       return SDValue();
10156 
10157   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10158 }
10159 
10160 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10161                            SelectionDAG &DAG,
10162                            const AArch64Subtarget *Subtarget) {
10163 
10164   StoreSDNode *S = cast<StoreSDNode>(N);
10165   if (S->isVolatile() || S->isIndexed())
10166     return SDValue();
10167 
10168   SDValue StVal = S->getValue();
10169   EVT VT = StVal.getValueType();
10170   if (!VT.isVector())
10171     return SDValue();
10172 
10173   // If we get a splat of zeros, convert this vector store to a store of
10174   // scalars. They will be merged into store pairs of xzr thereby removing one
10175   // instruction and one register.
10176   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10177     return ReplacedZeroSplat;
10178 
10179   // FIXME: The logic for deciding if an unaligned store should be split should
10180   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10181   // a call to that function here.
10182 
10183   if (!Subtarget->isMisaligned128StoreSlow())
10184     return SDValue();
10185 
10186   // Don't split at -Oz.
10187   if (DAG.getMachineFunction().getFunction().optForMinSize())
10188     return SDValue();
10189 
10190   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10191   // those up regresses performance on micro-benchmarks and olden/bh.
10192   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10193     return SDValue();
10194 
10195   // Split unaligned 16B stores. They are terrible for performance.
10196   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10197   // extensions can use this to mark that it does not want splitting to happen
10198   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10199   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10200   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10201       S->getAlignment() <= 2)
10202     return SDValue();
10203 
10204   // If we get a splat of a scalar convert this vector store to a store of
10205   // scalars. They will be merged into store pairs thereby removing two
10206   // instructions.
10207   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10208     return ReplacedSplat;
10209 
10210   SDLoc DL(S);
10211   unsigned NumElts = VT.getVectorNumElements() / 2;
10212   // Split VT into two.
10213   EVT HalfVT =
10214       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10215   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10216                                    DAG.getConstant(0, DL, MVT::i64));
10217   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10218                                    DAG.getConstant(NumElts, DL, MVT::i64));
10219   SDValue BasePtr = S->getBasePtr();
10220   SDValue NewST1 =
10221       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10222                    S->getAlignment(), S->getMemOperand()->getFlags());
10223   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10224                                   DAG.getConstant(8, DL, MVT::i64));
10225   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10226                       S->getPointerInfo(), S->getAlignment(),
10227                       S->getMemOperand()->getFlags());
10228 }
10229 
10230 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10231 /// post-increment LD1R.
10232 static SDValue performPostLD1Combine(SDNode *N,
10233                                      TargetLowering::DAGCombinerInfo &DCI,
10234                                      bool IsLaneOp) {
10235   if (DCI.isBeforeLegalizeOps())
10236     return SDValue();
10237 
10238   SelectionDAG &DAG = DCI.DAG;
10239   EVT VT = N->getValueType(0);
10240 
10241   unsigned LoadIdx = IsLaneOp ? 1 : 0;
10242   SDNode *LD = N->getOperand(LoadIdx).getNode();
10243   // If it is not LOAD, can not do such combine.
10244   if (LD->getOpcode() != ISD::LOAD)
10245     return SDValue();
10246 
10247   // The vector lane must be a constant in the LD1LANE opcode.
10248   SDValue Lane;
10249   if (IsLaneOp) {
10250     Lane = N->getOperand(2);
10251     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10252     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10253       return SDValue();
10254   }
10255 
10256   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10257   EVT MemVT = LoadSDN->getMemoryVT();
10258   // Check if memory operand is the same type as the vector element.
10259   if (MemVT != VT.getVectorElementType())
10260     return SDValue();
10261 
10262   // Check if there are other uses. If so, do not combine as it will introduce
10263   // an extra load.
10264   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10265        ++UI) {
10266     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10267       continue;
10268     if (*UI != N)
10269       return SDValue();
10270   }
10271 
10272   SDValue Addr = LD->getOperand(1);
10273   SDValue Vector = N->getOperand(0);
10274   // Search for a use of the address operand that is an increment.
10275   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10276        Addr.getNode()->use_end(); UI != UE; ++UI) {
10277     SDNode *User = *UI;
10278     if (User->getOpcode() != ISD::ADD
10279         || UI.getUse().getResNo() != Addr.getResNo())
10280       continue;
10281 
10282     // If the increment is a constant, it must match the memory ref size.
10283     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10284     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10285       uint32_t IncVal = CInc->getZExtValue();
10286       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10287       if (IncVal != NumBytes)
10288         continue;
10289       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10290     }
10291 
10292     // To avoid cycle construction make sure that neither the load nor the add
10293     // are predecessors to each other or the Vector.
10294     SmallPtrSet<const SDNode *, 32> Visited;
10295     SmallVector<const SDNode *, 16> Worklist;
10296     Visited.insert(N);
10297     Worklist.push_back(User);
10298     Worklist.push_back(LD);
10299     Worklist.push_back(Vector.getNode());
10300     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10301         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10302       continue;
10303 
10304     SmallVector<SDValue, 8> Ops;
10305     Ops.push_back(LD->getOperand(0));  // Chain
10306     if (IsLaneOp) {
10307       Ops.push_back(Vector);           // The vector to be inserted
10308       Ops.push_back(Lane);             // The lane to be inserted in the vector
10309     }
10310     Ops.push_back(Addr);
10311     Ops.push_back(Inc);
10312 
10313     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10314     SDVTList SDTys = DAG.getVTList(Tys);
10315     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10316     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10317                                            MemVT,
10318                                            LoadSDN->getMemOperand());
10319 
10320     // Update the uses.
10321     SDValue NewResults[] = {
10322         SDValue(LD, 0),            // The result of load
10323         SDValue(UpdN.getNode(), 2) // Chain
10324     };
10325     DCI.CombineTo(LD, NewResults);
10326     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
10327     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
10328 
10329     break;
10330   }
10331   return SDValue();
10332 }
10333 
10334 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10335 /// address translation.
10336 static bool performTBISimplification(SDValue Addr,
10337                                      TargetLowering::DAGCombinerInfo &DCI,
10338                                      SelectionDAG &DAG) {
10339   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10340   KnownBits Known;
10341   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10342                                         !DCI.isBeforeLegalizeOps());
10343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10344   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10345     DCI.CommitTargetLoweringOpt(TLO);
10346     return true;
10347   }
10348   return false;
10349 }
10350 
10351 static SDValue performSTORECombine(SDNode *N,
10352                                    TargetLowering::DAGCombinerInfo &DCI,
10353                                    SelectionDAG &DAG,
10354                                    const AArch64Subtarget *Subtarget) {
10355   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10356     return Split;
10357 
10358   if (Subtarget->supportsAddressTopByteIgnored() &&
10359       performTBISimplification(N->getOperand(2), DCI, DAG))
10360     return SDValue(N, 0);
10361 
10362   return SDValue();
10363 }
10364 
10365 
10366 /// Target-specific DAG combine function for NEON load/store intrinsics
10367 /// to merge base address updates.
10368 static SDValue performNEONPostLDSTCombine(SDNode *N,
10369                                           TargetLowering::DAGCombinerInfo &DCI,
10370                                           SelectionDAG &DAG) {
10371   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10372     return SDValue();
10373 
10374   unsigned AddrOpIdx = N->getNumOperands() - 1;
10375   SDValue Addr = N->getOperand(AddrOpIdx);
10376 
10377   // Search for a use of the address operand that is an increment.
10378   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10379        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10380     SDNode *User = *UI;
10381     if (User->getOpcode() != ISD::ADD ||
10382         UI.getUse().getResNo() != Addr.getResNo())
10383       continue;
10384 
10385     // Check that the add is independent of the load/store.  Otherwise, folding
10386     // it would create a cycle.
10387     SmallPtrSet<const SDNode *, 32> Visited;
10388     SmallVector<const SDNode *, 16> Worklist;
10389     Visited.insert(Addr.getNode());
10390     Worklist.push_back(N);
10391     Worklist.push_back(User);
10392     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10393         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10394       continue;
10395 
10396     // Find the new opcode for the updating load/store.
10397     bool IsStore = false;
10398     bool IsLaneOp = false;
10399     bool IsDupOp = false;
10400     unsigned NewOpc = 0;
10401     unsigned NumVecs = 0;
10402     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10403     switch (IntNo) {
10404     default: llvm_unreachable("unexpected intrinsic for Neon base update");
10405     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
10406       NumVecs = 2; break;
10407     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
10408       NumVecs = 3; break;
10409     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
10410       NumVecs = 4; break;
10411     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
10412       NumVecs = 2; IsStore = true; break;
10413     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
10414       NumVecs = 3; IsStore = true; break;
10415     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
10416       NumVecs = 4; IsStore = true; break;
10417     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
10418       NumVecs = 2; break;
10419     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
10420       NumVecs = 3; break;
10421     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
10422       NumVecs = 4; break;
10423     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
10424       NumVecs = 2; IsStore = true; break;
10425     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
10426       NumVecs = 3; IsStore = true; break;
10427     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
10428       NumVecs = 4; IsStore = true; break;
10429     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
10430       NumVecs = 2; IsDupOp = true; break;
10431     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
10432       NumVecs = 3; IsDupOp = true; break;
10433     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
10434       NumVecs = 4; IsDupOp = true; break;
10435     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
10436       NumVecs = 2; IsLaneOp = true; break;
10437     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
10438       NumVecs = 3; IsLaneOp = true; break;
10439     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
10440       NumVecs = 4; IsLaneOp = true; break;
10441     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
10442       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10443     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
10444       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10445     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
10446       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10447     }
10448 
10449     EVT VecTy;
10450     if (IsStore)
10451       VecTy = N->getOperand(2).getValueType();
10452     else
10453       VecTy = N->getValueType(0);
10454 
10455     // If the increment is a constant, it must match the memory ref size.
10456     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10457     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10458       uint32_t IncVal = CInc->getZExtValue();
10459       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10460       if (IsLaneOp || IsDupOp)
10461         NumBytes /= VecTy.getVectorNumElements();
10462       if (IncVal != NumBytes)
10463         continue;
10464       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10465     }
10466     SmallVector<SDValue, 8> Ops;
10467     Ops.push_back(N->getOperand(0)); // Incoming chain
10468     // Load lane and store have vector list as input.
10469     if (IsLaneOp || IsStore)
10470       for (unsigned i = 2; i < AddrOpIdx; ++i)
10471         Ops.push_back(N->getOperand(i));
10472     Ops.push_back(Addr); // Base register
10473     Ops.push_back(Inc);
10474 
10475     // Return Types.
10476     EVT Tys[6];
10477     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10478     unsigned n;
10479     for (n = 0; n < NumResultVecs; ++n)
10480       Tys[n] = VecTy;
10481     Tys[n++] = MVT::i64;  // Type of write back register
10482     Tys[n] = MVT::Other;  // Type of the chain
10483     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
10484 
10485     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10486     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10487                                            MemInt->getMemoryVT(),
10488                                            MemInt->getMemOperand());
10489 
10490     // Update the uses.
10491     std::vector<SDValue> NewResults;
10492     for (unsigned i = 0; i < NumResultVecs; ++i) {
10493       NewResults.push_back(SDValue(UpdN.getNode(), i));
10494     }
10495     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10496     DCI.CombineTo(N, NewResults);
10497     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10498 
10499     break;
10500   }
10501   return SDValue();
10502 }
10503 
10504 // Checks to see if the value is the prescribed width and returns information
10505 // about its extension mode.
10506 static
10507 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10508   ExtType = ISD::NON_EXTLOAD;
10509   switch(V.getNode()->getOpcode()) {
10510   default:
10511     return false;
10512   case ISD::LOAD: {
10513     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10514     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10515        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10516       ExtType = LoadNode->getExtensionType();
10517       return true;
10518     }
10519     return false;
10520   }
10521   case ISD::AssertSext: {
10522     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10523     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10524        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10525       ExtType = ISD::SEXTLOAD;
10526       return true;
10527     }
10528     return false;
10529   }
10530   case ISD::AssertZext: {
10531     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10532     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10533        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10534       ExtType = ISD::ZEXTLOAD;
10535       return true;
10536     }
10537     return false;
10538   }
10539   case ISD::Constant:
10540   case ISD::TargetConstant: {
10541     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10542            1LL << (width - 1);
10543   }
10544   }
10545 
10546   return true;
10547 }
10548 
10549 // This function does a whole lot of voodoo to determine if the tests are
10550 // equivalent without and with a mask. Essentially what happens is that given a
10551 // DAG resembling:
10552 //
10553 //  +-------------+ +-------------+ +-------------+ +-------------+
10554 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
10555 //  +-------------+ +-------------+ +-------------+ +-------------+
10556 //           |           |           |               |
10557 //           V           V           |    +----------+
10558 //          +-------------+  +----+  |    |
10559 //          |     ADD     |  |0xff|  |    |
10560 //          +-------------+  +----+  |    |
10561 //                  |           |    |    |
10562 //                  V           V    |    |
10563 //                 +-------------+   |    |
10564 //                 |     AND     |   |    |
10565 //                 +-------------+   |    |
10566 //                      |            |    |
10567 //                      +-----+      |    |
10568 //                            |      |    |
10569 //                            V      V    V
10570 //                           +-------------+
10571 //                           |     CMP     |
10572 //                           +-------------+
10573 //
10574 // The AND node may be safely removed for some combinations of inputs. In
10575 // particular we need to take into account the extension type of the Input,
10576 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10577 // width of the input (this can work for any width inputs, the above graph is
10578 // specific to 8 bits.
10579 //
10580 // The specific equations were worked out by generating output tables for each
10581 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10582 // problem was simplified by working with 4 bit inputs, which means we only
10583 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10584 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10585 // patterns present in both extensions (0,7). For every distinct set of
10586 // AddConstant and CompConstants bit patterns we can consider the masked and
10587 // unmasked versions to be equivalent if the result of this function is true for
10588 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10589 //
10590 //   sub      w8, w0, w1
10591 //   and      w10, w8, #0x0f
10592 //   cmp      w8, w2
10593 //   cset     w9, AArch64CC
10594 //   cmp      w10, w2
10595 //   cset     w11, AArch64CC
10596 //   cmp      w9, w11
10597 //   cset     w0, eq
10598 //   ret
10599 //
10600 // Since the above function shows when the outputs are equivalent it defines
10601 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10602 // would be expensive to run during compiles. The equations below were written
10603 // in a test harness that confirmed they gave equivalent outputs to the above
10604 // for all inputs function, so they can be used determine if the removal is
10605 // legal instead.
10606 //
10607 // isEquivalentMaskless() is the code for testing if the AND can be removed
10608 // factored out of the DAG recognition as the DAG can take several forms.
10609 
10610 static bool isEquivalentMaskless(unsigned CC, unsigned width,
10611                                  ISD::LoadExtType ExtType, int AddConstant,
10612                                  int CompConstant) {
10613   // By being careful about our equations and only writing the in term
10614   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10615   // make them generally applicable to all bit widths.
10616   int MaxUInt = (1 << width);
10617 
10618   // For the purposes of these comparisons sign extending the type is
10619   // equivalent to zero extending the add and displacing it by half the integer
10620   // width. Provided we are careful and make sure our equations are valid over
10621   // the whole range we can just adjust the input and avoid writing equations
10622   // for sign extended inputs.
10623   if (ExtType == ISD::SEXTLOAD)
10624     AddConstant -= (1 << (width-1));
10625 
10626   switch(CC) {
10627   case AArch64CC::LE:
10628   case AArch64CC::GT:
10629     if ((AddConstant == 0) ||
10630         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10631         (AddConstant >= 0 && CompConstant < 0) ||
10632         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10633       return true;
10634     break;
10635   case AArch64CC::LT:
10636   case AArch64CC::GE:
10637     if ((AddConstant == 0) ||
10638         (AddConstant >= 0 && CompConstant <= 0) ||
10639         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10640       return true;
10641     break;
10642   case AArch64CC::HI:
10643   case AArch64CC::LS:
10644     if ((AddConstant >= 0 && CompConstant < 0) ||
10645        (AddConstant <= 0 && CompConstant >= -1 &&
10646         CompConstant < AddConstant + MaxUInt))
10647       return true;
10648    break;
10649   case AArch64CC::PL:
10650   case AArch64CC::MI:
10651     if ((AddConstant == 0) ||
10652         (AddConstant > 0 && CompConstant <= 0) ||
10653         (AddConstant < 0 && CompConstant <= AddConstant))
10654       return true;
10655     break;
10656   case AArch64CC::LO:
10657   case AArch64CC::HS:
10658     if ((AddConstant >= 0 && CompConstant <= 0) ||
10659         (AddConstant <= 0 && CompConstant >= 0 &&
10660          CompConstant <= AddConstant + MaxUInt))
10661       return true;
10662     break;
10663   case AArch64CC::EQ:
10664   case AArch64CC::NE:
10665     if ((AddConstant > 0 && CompConstant < 0) ||
10666         (AddConstant < 0 && CompConstant >= 0 &&
10667          CompConstant < AddConstant + MaxUInt) ||
10668         (AddConstant >= 0 && CompConstant >= 0 &&
10669          CompConstant >= AddConstant) ||
10670         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
10671       return true;
10672     break;
10673   case AArch64CC::VS:
10674   case AArch64CC::VC:
10675   case AArch64CC::AL:
10676   case AArch64CC::NV:
10677     return true;
10678   case AArch64CC::Invalid:
10679     break;
10680   }
10681 
10682   return false;
10683 }
10684 
10685 static
10686 SDValue performCONDCombine(SDNode *N,
10687                            TargetLowering::DAGCombinerInfo &DCI,
10688                            SelectionDAG &DAG, unsigned CCIndex,
10689                            unsigned CmpIndex) {
10690   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10691   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10692   unsigned CondOpcode = SubsNode->getOpcode();
10693 
10694   if (CondOpcode != AArch64ISD::SUBS)
10695     return SDValue();
10696 
10697   // There is a SUBS feeding this condition. Is it fed by a mask we can
10698   // use?
10699 
10700   SDNode *AndNode = SubsNode->getOperand(0).getNode();
10701   unsigned MaskBits = 0;
10702 
10703   if (AndNode->getOpcode() != ISD::AND)
10704     return SDValue();
10705 
10706   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10707     uint32_t CNV = CN->getZExtValue();
10708     if (CNV == 255)
10709       MaskBits = 8;
10710     else if (CNV == 65535)
10711       MaskBits = 16;
10712   }
10713 
10714   if (!MaskBits)
10715     return SDValue();
10716 
10717   SDValue AddValue = AndNode->getOperand(0);
10718 
10719   if (AddValue.getOpcode() != ISD::ADD)
10720     return SDValue();
10721 
10722   // The basic dag structure is correct, grab the inputs and validate them.
10723 
10724   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10725   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10726   SDValue SubsInputValue = SubsNode->getOperand(1);
10727 
10728   // The mask is present and the provenance of all the values is a smaller type,
10729   // lets see if the mask is superfluous.
10730 
10731   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10732       !isa<ConstantSDNode>(SubsInputValue.getNode()))
10733     return SDValue();
10734 
10735   ISD::LoadExtType ExtType;
10736 
10737   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10738       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10739       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10740     return SDValue();
10741 
10742   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10743                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10744                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10745     return SDValue();
10746 
10747   // The AND is not necessary, remove it.
10748 
10749   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10750                                SubsNode->getValueType(1));
10751   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10752 
10753   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10754   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10755 
10756   return SDValue(N, 0);
10757 }
10758 
10759 // Optimize compare with zero and branch.
10760 static SDValue performBRCONDCombine(SDNode *N,
10761                                     TargetLowering::DAGCombinerInfo &DCI,
10762                                     SelectionDAG &DAG) {
10763   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10764     N = NV.getNode();
10765   SDValue Chain = N->getOperand(0);
10766   SDValue Dest = N->getOperand(1);
10767   SDValue CCVal = N->getOperand(2);
10768   SDValue Cmp = N->getOperand(3);
10769 
10770   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10771   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10772   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10773     return SDValue();
10774 
10775   unsigned CmpOpc = Cmp.getOpcode();
10776   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10777     return SDValue();
10778 
10779   // Only attempt folding if there is only one use of the flag and no use of the
10780   // value.
10781   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10782     return SDValue();
10783 
10784   SDValue LHS = Cmp.getOperand(0);
10785   SDValue RHS = Cmp.getOperand(1);
10786 
10787   assert(LHS.getValueType() == RHS.getValueType() &&
10788          "Expected the value type to be the same for both operands!");
10789   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10790     return SDValue();
10791 
10792   if (isNullConstant(LHS))
10793     std::swap(LHS, RHS);
10794 
10795   if (!isNullConstant(RHS))
10796     return SDValue();
10797 
10798   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10799       LHS.getOpcode() == ISD::SRL)
10800     return SDValue();
10801 
10802   // Fold the compare into the branch instruction.
10803   SDValue BR;
10804   if (CC == AArch64CC::EQ)
10805     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10806   else
10807     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10808 
10809   // Do not add new nodes to DAG combiner worklist.
10810   DCI.CombineTo(N, BR, false);
10811 
10812   return SDValue();
10813 }
10814 
10815 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
10816 // as well as whether the test should be inverted.  This code is required to
10817 // catch these cases (as opposed to standard dag combines) because
10818 // AArch64ISD::TBZ is matched during legalization.
10819 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10820                                  SelectionDAG &DAG) {
10821 
10822   if (!Op->hasOneUse())
10823     return Op;
10824 
10825   // We don't handle undef/constant-fold cases below, as they should have
10826   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10827   // etc.)
10828 
10829   // (tbz (trunc x), b) -> (tbz x, b)
10830   // This case is just here to enable more of the below cases to be caught.
10831   if (Op->getOpcode() == ISD::TRUNCATE &&
10832       Bit < Op->getValueType(0).getSizeInBits()) {
10833     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10834   }
10835 
10836   if (Op->getNumOperands() != 2)
10837     return Op;
10838 
10839   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10840   if (!C)
10841     return Op;
10842 
10843   switch (Op->getOpcode()) {
10844   default:
10845     return Op;
10846 
10847   // (tbz (and x, m), b) -> (tbz x, b)
10848   case ISD::AND:
10849     if ((C->getZExtValue() >> Bit) & 1)
10850       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10851     return Op;
10852 
10853   // (tbz (shl x, c), b) -> (tbz x, b-c)
10854   case ISD::SHL:
10855     if (C->getZExtValue() <= Bit &&
10856         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10857       Bit = Bit - C->getZExtValue();
10858       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10859     }
10860     return Op;
10861 
10862   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10863   case ISD::SRA:
10864     Bit = Bit + C->getZExtValue();
10865     if (Bit >= Op->getValueType(0).getSizeInBits())
10866       Bit = Op->getValueType(0).getSizeInBits() - 1;
10867     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10868 
10869   // (tbz (srl x, c), b) -> (tbz x, b+c)
10870   case ISD::SRL:
10871     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10872       Bit = Bit + C->getZExtValue();
10873       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10874     }
10875     return Op;
10876 
10877   // (tbz (xor x, -1), b) -> (tbnz x, b)
10878   case ISD::XOR:
10879     if ((C->getZExtValue() >> Bit) & 1)
10880       Invert = !Invert;
10881     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10882   }
10883 }
10884 
10885 // Optimize test single bit zero/non-zero and branch.
10886 static SDValue performTBZCombine(SDNode *N,
10887                                  TargetLowering::DAGCombinerInfo &DCI,
10888                                  SelectionDAG &DAG) {
10889   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10890   bool Invert = false;
10891   SDValue TestSrc = N->getOperand(1);
10892   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10893 
10894   if (TestSrc == NewTestSrc)
10895     return SDValue();
10896 
10897   unsigned NewOpc = N->getOpcode();
10898   if (Invert) {
10899     if (NewOpc == AArch64ISD::TBZ)
10900       NewOpc = AArch64ISD::TBNZ;
10901     else {
10902       assert(NewOpc == AArch64ISD::TBNZ);
10903       NewOpc = AArch64ISD::TBZ;
10904     }
10905   }
10906 
10907   SDLoc DL(N);
10908   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10909                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10910 }
10911 
10912 // vselect (v1i1 setcc) ->
10913 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10914 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10915 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10916 // such VSELECT.
10917 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10918   SDValue N0 = N->getOperand(0);
10919   EVT CCVT = N0.getValueType();
10920 
10921   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10922       CCVT.getVectorElementType() != MVT::i1)
10923     return SDValue();
10924 
10925   EVT ResVT = N->getValueType(0);
10926   EVT CmpVT = N0.getOperand(0).getValueType();
10927   // Only combine when the result type is of the same size as the compared
10928   // operands.
10929   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10930     return SDValue();
10931 
10932   SDValue IfTrue = N->getOperand(1);
10933   SDValue IfFalse = N->getOperand(2);
10934   SDValue SetCC =
10935       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10936                    N0.getOperand(0), N0.getOperand(1),
10937                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10938   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10939                      IfTrue, IfFalse);
10940 }
10941 
10942 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10943 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10944 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10945 /// with a vector one followed by a DUP shuffle on the result.
10946 static SDValue performSelectCombine(SDNode *N,
10947                                     TargetLowering::DAGCombinerInfo &DCI) {
10948   SelectionDAG &DAG = DCI.DAG;
10949   SDValue N0 = N->getOperand(0);
10950   EVT ResVT = N->getValueType(0);
10951 
10952   if (N0.getOpcode() != ISD::SETCC)
10953     return SDValue();
10954 
10955   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10956   // scalar SetCCResultType. We also don't expect vectors, because we assume
10957   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10958   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10959          "Scalar-SETCC feeding SELECT has unexpected result type!");
10960 
10961   // If NumMaskElts == 0, the comparison is larger than select result. The
10962   // largest real NEON comparison is 64-bits per lane, which means the result is
10963   // at most 32-bits and an illegal vector. Just bail out for now.
10964   EVT SrcVT = N0.getOperand(0).getValueType();
10965 
10966   // Don't try to do this optimization when the setcc itself has i1 operands.
10967   // There are no legal vectors of i1, so this would be pointless.
10968   if (SrcVT == MVT::i1)
10969     return SDValue();
10970 
10971   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10972   if (!ResVT.isVector() || NumMaskElts == 0)
10973     return SDValue();
10974 
10975   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10976   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10977 
10978   // Also bail out if the vector CCVT isn't the same size as ResVT.
10979   // This can happen if the SETCC operand size doesn't divide the ResVT size
10980   // (e.g., f64 vs v3f32).
10981   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10982     return SDValue();
10983 
10984   // Make sure we didn't create illegal types, if we're not supposed to.
10985   assert(DCI.isBeforeLegalize() ||
10986          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10987 
10988   // First perform a vector comparison, where lane 0 is the one we're interested
10989   // in.
10990   SDLoc DL(N0);
10991   SDValue LHS =
10992       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10993   SDValue RHS =
10994       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10995   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10996 
10997   // Now duplicate the comparison mask we want across all other lanes.
10998   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10999   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11000   Mask = DAG.getNode(ISD::BITCAST, DL,
11001                      ResVT.changeVectorElementTypeToInteger(), Mask);
11002 
11003   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11004 }
11005 
11006 /// Get rid of unnecessary NVCASTs (that don't change the type).
11007 static SDValue performNVCASTCombine(SDNode *N) {
11008   if (N->getValueType(0) == N->getOperand(0).getValueType())
11009     return N->getOperand(0);
11010 
11011   return SDValue();
11012 }
11013 
11014 // If all users of the globaladdr are of the form (globaladdr + constant), find
11015 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11016 // globaladdr as (globaladdr + constant) - constant.
11017 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11018                                            const AArch64Subtarget *Subtarget,
11019                                            const TargetMachine &TM) {
11020   auto *GN = dyn_cast<GlobalAddressSDNode>(N);
11021   if (!GN || Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11022                  AArch64II::MO_NO_FLAG)
11023     return SDValue();
11024 
11025   uint64_t MinOffset = -1ull;
11026   for (SDNode *N : GN->uses()) {
11027     if (N->getOpcode() != ISD::ADD)
11028       return SDValue();
11029     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11030     if (!C)
11031       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11032     if (!C)
11033       return SDValue();
11034     MinOffset = std::min(MinOffset, C->getZExtValue());
11035   }
11036   uint64_t Offset = MinOffset + GN->getOffset();
11037 
11038   // Require that the new offset is larger than the existing one. Otherwise, we
11039   // can end up oscillating between two possible DAGs, for example,
11040   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11041   if (Offset <= uint64_t(GN->getOffset()))
11042     return SDValue();
11043 
11044   // Check whether folding this offset is legal. It must not go out of bounds of
11045   // the referenced object to avoid violating the code model, and must be
11046   // smaller than 2^21 because this is the largest offset expressible in all
11047   // object formats.
11048   //
11049   // This check also prevents us from folding negative offsets, which will end
11050   // up being treated in the same way as large positive ones. They could also
11051   // cause code model violations, and aren't really common enough to matter.
11052   if (Offset >= (1 << 21))
11053     return SDValue();
11054 
11055   const GlobalValue *GV = GN->getGlobal();
11056   Type *T = GV->getValueType();
11057   if (!T->isSized() ||
11058       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11059     return SDValue();
11060 
11061   SDLoc DL(GN);
11062   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11063   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11064                      DAG.getConstant(MinOffset, DL, MVT::i64));
11065 }
11066 
11067 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11068                                                  DAGCombinerInfo &DCI) const {
11069   SelectionDAG &DAG = DCI.DAG;
11070   switch (N->getOpcode()) {
11071   default:
11072     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11073     break;
11074   case ISD::ADD:
11075   case ISD::SUB:
11076     return performAddSubLongCombine(N, DCI, DAG);
11077   case ISD::XOR:
11078     return performXorCombine(N, DAG, DCI, Subtarget);
11079   case ISD::MUL:
11080     return performMulCombine(N, DAG, DCI, Subtarget);
11081   case ISD::SINT_TO_FP:
11082   case ISD::UINT_TO_FP:
11083     return performIntToFpCombine(N, DAG, Subtarget);
11084   case ISD::FP_TO_SINT:
11085   case ISD::FP_TO_UINT:
11086     return performFpToIntCombine(N, DAG, DCI, Subtarget);
11087   case ISD::FDIV:
11088     return performFDivCombine(N, DAG, DCI, Subtarget);
11089   case ISD::OR:
11090     return performORCombine(N, DCI, Subtarget);
11091   case ISD::SRL:
11092     return performSRLCombine(N, DCI);
11093   case ISD::INTRINSIC_WO_CHAIN:
11094     return performIntrinsicCombine(N, DCI, Subtarget);
11095   case ISD::ANY_EXTEND:
11096   case ISD::ZERO_EXTEND:
11097   case ISD::SIGN_EXTEND:
11098     return performExtendCombine(N, DCI, DAG);
11099   case ISD::BITCAST:
11100     return performBitcastCombine(N, DCI, DAG);
11101   case ISD::CONCAT_VECTORS:
11102     return performConcatVectorsCombine(N, DCI, DAG);
11103   case ISD::SELECT:
11104     return performSelectCombine(N, DCI);
11105   case ISD::VSELECT:
11106     return performVSelectCombine(N, DCI.DAG);
11107   case ISD::LOAD:
11108     if (performTBISimplification(N->getOperand(1), DCI, DAG))
11109       return SDValue(N, 0);
11110     break;
11111   case ISD::STORE:
11112     return performSTORECombine(N, DCI, DAG, Subtarget);
11113   case AArch64ISD::BRCOND:
11114     return performBRCONDCombine(N, DCI, DAG);
11115   case AArch64ISD::TBNZ:
11116   case AArch64ISD::TBZ:
11117     return performTBZCombine(N, DCI, DAG);
11118   case AArch64ISD::CSEL:
11119     return performCONDCombine(N, DCI, DAG, 2, 3);
11120   case AArch64ISD::DUP:
11121     return performPostLD1Combine(N, DCI, false);
11122   case AArch64ISD::NVCAST:
11123     return performNVCASTCombine(N);
11124   case ISD::INSERT_VECTOR_ELT:
11125     return performPostLD1Combine(N, DCI, true);
11126   case ISD::INTRINSIC_VOID:
11127   case ISD::INTRINSIC_W_CHAIN:
11128     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11129     case Intrinsic::aarch64_neon_ld2:
11130     case Intrinsic::aarch64_neon_ld3:
11131     case Intrinsic::aarch64_neon_ld4:
11132     case Intrinsic::aarch64_neon_ld1x2:
11133     case Intrinsic::aarch64_neon_ld1x3:
11134     case Intrinsic::aarch64_neon_ld1x4:
11135     case Intrinsic::aarch64_neon_ld2lane:
11136     case Intrinsic::aarch64_neon_ld3lane:
11137     case Intrinsic::aarch64_neon_ld4lane:
11138     case Intrinsic::aarch64_neon_ld2r:
11139     case Intrinsic::aarch64_neon_ld3r:
11140     case Intrinsic::aarch64_neon_ld4r:
11141     case Intrinsic::aarch64_neon_st2:
11142     case Intrinsic::aarch64_neon_st3:
11143     case Intrinsic::aarch64_neon_st4:
11144     case Intrinsic::aarch64_neon_st1x2:
11145     case Intrinsic::aarch64_neon_st1x3:
11146     case Intrinsic::aarch64_neon_st1x4:
11147     case Intrinsic::aarch64_neon_st2lane:
11148     case Intrinsic::aarch64_neon_st3lane:
11149     case Intrinsic::aarch64_neon_st4lane:
11150       return performNEONPostLDSTCombine(N, DCI, DAG);
11151     default:
11152       break;
11153     }
11154   case ISD::GlobalAddress:
11155     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11156   }
11157   return SDValue();
11158 }
11159 
11160 // Check if the return value is used as only a return value, as otherwise
11161 // we can't perform a tail-call. In particular, we need to check for
11162 // target ISD nodes that are returns and any other "odd" constructs
11163 // that the generic analysis code won't necessarily catch.
11164 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11165                                                SDValue &Chain) const {
11166   if (N->getNumValues() != 1)
11167     return false;
11168   if (!N->hasNUsesOfValue(1, 0))
11169     return false;
11170 
11171   SDValue TCChain = Chain;
11172   SDNode *Copy = *N->use_begin();
11173   if (Copy->getOpcode() == ISD::CopyToReg) {
11174     // If the copy has a glue operand, we conservatively assume it isn't safe to
11175     // perform a tail call.
11176     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11177         MVT::Glue)
11178       return false;
11179     TCChain = Copy->getOperand(0);
11180   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11181     return false;
11182 
11183   bool HasRet = false;
11184   for (SDNode *Node : Copy->uses()) {
11185     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11186       return false;
11187     HasRet = true;
11188   }
11189 
11190   if (!HasRet)
11191     return false;
11192 
11193   Chain = TCChain;
11194   return true;
11195 }
11196 
11197 // Return whether the an instruction can potentially be optimized to a tail
11198 // call. This will cause the optimizers to attempt to move, or duplicate,
11199 // return instructions to help enable tail call optimizations for this
11200 // instruction.
11201 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11202   return CI->isTailCall();
11203 }
11204 
11205 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11206                                                    SDValue &Offset,
11207                                                    ISD::MemIndexedMode &AM,
11208                                                    bool &IsInc,
11209                                                    SelectionDAG &DAG) const {
11210   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11211     return false;
11212 
11213   Base = Op->getOperand(0);
11214   // All of the indexed addressing mode instructions take a signed
11215   // 9 bit immediate offset.
11216   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11217     int64_t RHSC = RHS->getSExtValue();
11218     if (Op->getOpcode() == ISD::SUB)
11219       RHSC = -(uint64_t)RHSC;
11220     if (!isInt<9>(RHSC))
11221       return false;
11222     IsInc = (Op->getOpcode() == ISD::ADD);
11223     Offset = Op->getOperand(1);
11224     return true;
11225   }
11226   return false;
11227 }
11228 
11229 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11230                                                       SDValue &Offset,
11231                                                       ISD::MemIndexedMode &AM,
11232                                                       SelectionDAG &DAG) const {
11233   EVT VT;
11234   SDValue Ptr;
11235   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11236     VT = LD->getMemoryVT();
11237     Ptr = LD->getBasePtr();
11238   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11239     VT = ST->getMemoryVT();
11240     Ptr = ST->getBasePtr();
11241   } else
11242     return false;
11243 
11244   bool IsInc;
11245   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11246     return false;
11247   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11248   return true;
11249 }
11250 
11251 bool AArch64TargetLowering::getPostIndexedAddressParts(
11252     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11253     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11254   EVT VT;
11255   SDValue Ptr;
11256   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11257     VT = LD->getMemoryVT();
11258     Ptr = LD->getBasePtr();
11259   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11260     VT = ST->getMemoryVT();
11261     Ptr = ST->getBasePtr();
11262   } else
11263     return false;
11264 
11265   bool IsInc;
11266   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11267     return false;
11268   // Post-indexing updates the base, so it's not a valid transform
11269   // if that's not the same as the load's pointer.
11270   if (Ptr != Base)
11271     return false;
11272   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11273   return true;
11274 }
11275 
11276 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11277                                   SelectionDAG &DAG) {
11278   SDLoc DL(N);
11279   SDValue Op = N->getOperand(0);
11280 
11281   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11282     return;
11283 
11284   Op = SDValue(
11285       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11286                          DAG.getUNDEF(MVT::i32), Op,
11287                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11288       0);
11289   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11290   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11291 }
11292 
11293 static void ReplaceReductionResults(SDNode *N,
11294                                     SmallVectorImpl<SDValue> &Results,
11295                                     SelectionDAG &DAG, unsigned InterOp,
11296                                     unsigned AcrossOp) {
11297   EVT LoVT, HiVT;
11298   SDValue Lo, Hi;
11299   SDLoc dl(N);
11300   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11301   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11302   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11303   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11304   Results.push_back(SplitVal);
11305 }
11306 
11307 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11308   SDLoc DL(N);
11309   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11310   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11311                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11312                                        DAG.getConstant(64, DL, MVT::i64)));
11313   return std::make_pair(Lo, Hi);
11314 }
11315 
11316 // Create an even/odd pair of X registers holding integer value V.
11317 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11318   SDLoc dl(V.getNode());
11319   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11320   SDValue VHi = DAG.getAnyExtOrTrunc(
11321       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11322       dl, MVT::i64);
11323   if (DAG.getDataLayout().isBigEndian())
11324     std::swap (VLo, VHi);
11325   SDValue RegClass =
11326       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11327   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11328   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11329   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11330   return SDValue(
11331       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11332 }
11333 
11334 static void ReplaceCMP_SWAP_128Results(SDNode *N,
11335                                        SmallVectorImpl<SDValue> &Results,
11336                                        SelectionDAG &DAG,
11337                                        const AArch64Subtarget *Subtarget) {
11338   assert(N->getValueType(0) == MVT::i128 &&
11339          "AtomicCmpSwap on types less than 128 should be legal");
11340 
11341   if (Subtarget->hasLSE()) {
11342     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11343     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11344     SDValue Ops[] = {
11345         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11346         createGPRPairNode(DAG, N->getOperand(3)), // Store value
11347         N->getOperand(1), // Ptr
11348         N->getOperand(0), // Chain in
11349     };
11350 
11351     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11352 
11353     unsigned Opcode;
11354     switch (MemOp->getOrdering()) {
11355     case AtomicOrdering::Monotonic:
11356       Opcode = AArch64::CASPX;
11357       break;
11358     case AtomicOrdering::Acquire:
11359       Opcode = AArch64::CASPAX;
11360       break;
11361     case AtomicOrdering::Release:
11362       Opcode = AArch64::CASPLX;
11363       break;
11364     case AtomicOrdering::AcquireRelease:
11365     case AtomicOrdering::SequentiallyConsistent:
11366       Opcode = AArch64::CASPALX;
11367       break;
11368     default:
11369       llvm_unreachable("Unexpected ordering!");
11370     }
11371 
11372     MachineSDNode *CmpSwap = DAG.getMachineNode(
11373         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11374     DAG.setNodeMemRefs(CmpSwap, {MemOp});
11375 
11376     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11377     if (DAG.getDataLayout().isBigEndian())
11378       std::swap(SubReg1, SubReg2);
11379     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11380                                                  SDValue(CmpSwap, 0)));
11381     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11382                                                  SDValue(CmpSwap, 0)));
11383     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11384     return;
11385   }
11386 
11387   auto Desired = splitInt128(N->getOperand(2), DAG);
11388   auto New = splitInt128(N->getOperand(3), DAG);
11389   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11390                    New.first,        New.second,    N->getOperand(0)};
11391   SDNode *CmpSwap = DAG.getMachineNode(
11392       AArch64::CMP_SWAP_128, SDLoc(N),
11393       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11394 
11395   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11396   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11397 
11398   Results.push_back(SDValue(CmpSwap, 0));
11399   Results.push_back(SDValue(CmpSwap, 1));
11400   Results.push_back(SDValue(CmpSwap, 3));
11401 }
11402 
11403 void AArch64TargetLowering::ReplaceNodeResults(
11404     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11405   switch (N->getOpcode()) {
11406   default:
11407     llvm_unreachable("Don't know how to custom expand this");
11408   case ISD::BITCAST:
11409     ReplaceBITCASTResults(N, Results, DAG);
11410     return;
11411   case ISD::VECREDUCE_ADD:
11412   case ISD::VECREDUCE_SMAX:
11413   case ISD::VECREDUCE_SMIN:
11414   case ISD::VECREDUCE_UMAX:
11415   case ISD::VECREDUCE_UMIN:
11416     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11417     return;
11418 
11419   case AArch64ISD::SADDV:
11420     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11421     return;
11422   case AArch64ISD::UADDV:
11423     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11424     return;
11425   case AArch64ISD::SMINV:
11426     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11427     return;
11428   case AArch64ISD::UMINV:
11429     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11430     return;
11431   case AArch64ISD::SMAXV:
11432     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11433     return;
11434   case AArch64ISD::UMAXV:
11435     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11436     return;
11437   case ISD::FP_TO_UINT:
11438   case ISD::FP_TO_SINT:
11439     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11440     // Let normal code take care of it by not adding anything to Results.
11441     return;
11442   case ISD::ATOMIC_CMP_SWAP:
11443     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
11444     return;
11445   }
11446 }
11447 
11448 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11449   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11450     return TargetLowering::useLoadStackGuardNode();
11451   return true;
11452 }
11453 
11454 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11455   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11456   // reciprocal if there are three or more FDIVs.
11457   return 3;
11458 }
11459 
11460 TargetLoweringBase::LegalizeTypeAction
11461 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
11462   MVT SVT = VT.getSimpleVT();
11463   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
11464   // v4i16, v2i32 instead of to promote.
11465   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
11466       || SVT == MVT::v1f32)
11467     return TypeWidenVector;
11468 
11469   return TargetLoweringBase::getPreferredVectorAction(VT);
11470 }
11471 
11472 // Loads and stores less than 128-bits are already atomic; ones above that
11473 // are doomed anyway, so defer to the default libcall and blame the OS when
11474 // things go wrong.
11475 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11476   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11477   return Size == 128;
11478 }
11479 
11480 // Loads and stores less than 128-bits are already atomic; ones above that
11481 // are doomed anyway, so defer to the default libcall and blame the OS when
11482 // things go wrong.
11483 TargetLowering::AtomicExpansionKind
11484 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11485   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11486   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
11487 }
11488 
11489 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11490 TargetLowering::AtomicExpansionKind
11491 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11492   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11493   if (Size > 128) return AtomicExpansionKind::None;
11494   // Nand not supported in LSE.
11495   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
11496   // Leave 128 bits to LLSC.
11497   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
11498 }
11499 
11500 TargetLowering::AtomicExpansionKind
11501 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11502     AtomicCmpXchgInst *AI) const {
11503   // If subtarget has LSE, leave cmpxchg intact for codegen.
11504   if (Subtarget->hasLSE())
11505     return AtomicExpansionKind::None;
11506   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11507   // implement cmpxchg without spilling. If the address being exchanged is also
11508   // on the stack and close enough to the spill slot, this can lead to a
11509   // situation where the monitor always gets cleared and the atomic operation
11510   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11511   if (getTargetMachine().getOptLevel() == 0)
11512     return AtomicExpansionKind::None;
11513   return AtomicExpansionKind::LLSC;
11514 }
11515 
11516 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11517                                              AtomicOrdering Ord) const {
11518   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11519   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11520   bool IsAcquire = isAcquireOrStronger(Ord);
11521 
11522   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11523   // intrinsic must return {i64, i64} and we have to recombine them into a
11524   // single i128 here.
11525   if (ValTy->getPrimitiveSizeInBits() == 128) {
11526     Intrinsic::ID Int =
11527         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
11528     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
11529 
11530     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11531     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11532 
11533     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11534     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11535     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11536     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11537     return Builder.CreateOr(
11538         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11539   }
11540 
11541   Type *Tys[] = { Addr->getType() };
11542   Intrinsic::ID Int =
11543       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
11544   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
11545 
11546   return Builder.CreateTruncOrBitCast(
11547       Builder.CreateCall(Ldxr, Addr),
11548       cast<PointerType>(Addr->getType())->getElementType());
11549 }
11550 
11551 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11552     IRBuilder<> &Builder) const {
11553   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11554   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
11555 }
11556 
11557 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11558                                                    Value *Val, Value *Addr,
11559                                                    AtomicOrdering Ord) const {
11560   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11561   bool IsRelease = isReleaseOrStronger(Ord);
11562 
11563   // Since the intrinsics must have legal type, the i128 intrinsics take two
11564   // parameters: "i64, i64". We must marshal Val into the appropriate form
11565   // before the call.
11566   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11567     Intrinsic::ID Int =
11568         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11569     Function *Stxr = Intrinsic::getDeclaration(M, Int);
11570     Type *Int64Ty = Type::getInt64Ty(M->getContext());
11571 
11572     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11573     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11574     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11575     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
11576   }
11577 
11578   Intrinsic::ID Int =
11579       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11580   Type *Tys[] = { Addr->getType() };
11581   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11582 
11583   return Builder.CreateCall(Stxr,
11584                             {Builder.CreateZExtOrBitCast(
11585                                  Val, Stxr->getFunctionType()->getParamType(0)),
11586                              Addr});
11587 }
11588 
11589 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11590     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11591   return Ty->isArrayTy();
11592 }
11593 
11594 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11595                                                             EVT) const {
11596   return false;
11597 }
11598 
11599 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
11600   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11601   Function *ThreadPointerFunc =
11602       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
11603   return IRB.CreatePointerCast(
11604       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
11605       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
11606 }
11607 
11608 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11609   // Android provides a fixed TLS slot for the stack cookie. See the definition
11610   // of TLS_SLOT_STACK_GUARD in
11611   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11612   if (Subtarget->isTargetAndroid())
11613     return UseTlsOffset(IRB, 0x28);
11614 
11615   // Fuchsia is similar.
11616   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
11617   if (Subtarget->isTargetFuchsia())
11618     return UseTlsOffset(IRB, -0x10);
11619 
11620   return TargetLowering::getIRStackGuard(IRB);
11621 }
11622 
11623 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
11624   // Android provides a fixed TLS slot for the SafeStack pointer. See the
11625   // definition of TLS_SLOT_SAFESTACK in
11626   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11627   if (Subtarget->isTargetAndroid())
11628     return UseTlsOffset(IRB, 0x48);
11629 
11630   // Fuchsia is similar.
11631   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
11632   if (Subtarget->isTargetFuchsia())
11633     return UseTlsOffset(IRB, -0x8);
11634 
11635   return TargetLowering::getSafeStackPointerLocation(IRB);
11636 }
11637 
11638 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11639     const Instruction &AndI) const {
11640   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11641   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
11642   // may be beneficial to sink in other cases, but we would have to check that
11643   // the cmp would not get folded into the br to form a cbz for these to be
11644   // beneficial.
11645   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11646   if (!Mask)
11647     return false;
11648   return Mask->getValue().isPowerOf2();
11649 }
11650 
11651 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11652   // Update IsSplitCSR in AArch64unctionInfo.
11653   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11654   AFI->setIsSplitCSR(true);
11655 }
11656 
11657 void AArch64TargetLowering::insertCopiesSplitCSR(
11658     MachineBasicBlock *Entry,
11659     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11660   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11661   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11662   if (!IStart)
11663     return;
11664 
11665   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11666   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
11667   MachineBasicBlock::iterator MBBI = Entry->begin();
11668   for (const MCPhysReg *I = IStart; *I; ++I) {
11669     const TargetRegisterClass *RC = nullptr;
11670     if (AArch64::GPR64RegClass.contains(*I))
11671       RC = &AArch64::GPR64RegClass;
11672     else if (AArch64::FPR64RegClass.contains(*I))
11673       RC = &AArch64::FPR64RegClass;
11674     else
11675       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11676 
11677     unsigned NewVR = MRI->createVirtualRegister(RC);
11678     // Create copy from CSR to a virtual register.
11679     // FIXME: this currently does not emit CFI pseudo-instructions, it works
11680     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11681     // nounwind. If we want to generalize this later, we may need to emit
11682     // CFI pseudo-instructions.
11683     assert(Entry->getParent()->getFunction().hasFnAttribute(
11684                Attribute::NoUnwind) &&
11685            "Function should be nounwind in insertCopiesSplitCSR!");
11686     Entry->addLiveIn(*I);
11687     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
11688         .addReg(*I);
11689 
11690     // Insert the copy-back instructions right before the terminator.
11691     for (auto *Exit : Exits)
11692       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11693               TII->get(TargetOpcode::COPY), *I)
11694           .addReg(NewVR);
11695   }
11696 }
11697 
11698 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
11699   // Integer division on AArch64 is expensive. However, when aggressively
11700   // optimizing for code size, we prefer to use a div instruction, as it is
11701   // usually smaller than the alternative sequence.
11702   // The exception to this is vector division. Since AArch64 doesn't have vector
11703   // integer division, leaving the division as-is is a loss even in terms of
11704   // size, because it will have to be scalarized, while the alternative code
11705   // sequence can be performed in vector form.
11706   bool OptSize =
11707       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
11708   return OptSize && !VT.isVector();
11709 }
11710 
11711 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11712   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11713 }
11714 
11715 unsigned
11716 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
11717   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
11718     return getPointerTy(DL).getSizeInBits();
11719 
11720   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11721 }
11722 
11723 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11724   MF.getFrameInfo().computeMaxCallFrameSize(MF);
11725   TargetLoweringBase::finalizeLowering(MF);
11726 }
11727