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 "AArch64CallingConvention.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64ISelLowering.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/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.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/MachineValueType.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/MathExtras.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetCallingConv.h"
73 #include "llvm/Target/TargetInstrInfo.h"
74 #include "llvm/Target/TargetMachine.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <algorithm>
77 #include <bitset>
78 #include <cassert>
79 #include <cctype>
80 #include <cstdint>
81 #include <cstdlib>
82 #include <iterator>
83 #include <limits>
84 #include <tuple>
85 #include <utility>
86 #include <vector>
87 
88 using namespace llvm;
89 
90 #define DEBUG_TYPE "aarch64-lower"
91 
92 STATISTIC(NumTailCalls, "Number of tail calls");
93 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
94 
95 static cl::opt<bool>
96 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
97                            cl::desc("Allow AArch64 SLI/SRI formation"),
98                            cl::init(false));
99 
100 // FIXME: The necessary dtprel relocations don't seem to be supported
101 // well in the GNU bfd and gold linkers at the moment. Therefore, by
102 // default, for now, fall back to GeneralDynamic code generation.
103 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
104     "aarch64-elf-ldtls-generation", cl::Hidden,
105     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
106     cl::init(false));
107 
108 /// Value type used for condition codes.
109 static const MVT MVT_CC = MVT::i32;
110 
111 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
112                                              const AArch64Subtarget &STI)
113     : TargetLowering(TM), Subtarget(&STI) {
114   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
115   // we have to make something up. Arbitrarily, choose ZeroOrOne.
116   setBooleanContents(ZeroOrOneBooleanContent);
117   // When comparing vectors the result sets the different elements in the
118   // vector to all-one or all-zero.
119   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
120 
121   // Set up the register classes.
122   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
123   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
124 
125   if (Subtarget->hasFPARMv8()) {
126     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
127     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
128     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
129     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
130   }
131 
132   if (Subtarget->hasNEON()) {
133     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
134     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
135     // Someone set us up the NEON.
136     addDRTypeForNEON(MVT::v2f32);
137     addDRTypeForNEON(MVT::v8i8);
138     addDRTypeForNEON(MVT::v4i16);
139     addDRTypeForNEON(MVT::v2i32);
140     addDRTypeForNEON(MVT::v1i64);
141     addDRTypeForNEON(MVT::v1f64);
142     addDRTypeForNEON(MVT::v4f16);
143 
144     addQRTypeForNEON(MVT::v4f32);
145     addQRTypeForNEON(MVT::v2f64);
146     addQRTypeForNEON(MVT::v16i8);
147     addQRTypeForNEON(MVT::v8i16);
148     addQRTypeForNEON(MVT::v4i32);
149     addQRTypeForNEON(MVT::v2i64);
150     addQRTypeForNEON(MVT::v8f16);
151   }
152 
153   // Compute derived properties from the register classes
154   computeRegisterProperties(Subtarget->getRegisterInfo());
155 
156   // Provide all sorts of operation actions
157   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
158   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
159   setOperationAction(ISD::SETCC, MVT::i32, Custom);
160   setOperationAction(ISD::SETCC, MVT::i64, Custom);
161   setOperationAction(ISD::SETCC, MVT::f32, Custom);
162   setOperationAction(ISD::SETCC, MVT::f64, Custom);
163   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
164   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
165   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
166   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
167   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
168   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
169   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
170   setOperationAction(ISD::SELECT, MVT::i32, Custom);
171   setOperationAction(ISD::SELECT, MVT::i64, Custom);
172   setOperationAction(ISD::SELECT, MVT::f32, Custom);
173   setOperationAction(ISD::SELECT, MVT::f64, Custom);
174   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
175   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
176   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
177   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
178   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
180 
181   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
182   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
183   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
184 
185   setOperationAction(ISD::FREM, MVT::f32, Expand);
186   setOperationAction(ISD::FREM, MVT::f64, Expand);
187   setOperationAction(ISD::FREM, MVT::f80, Expand);
188 
189   // Custom lowering hooks are needed for XOR
190   // to fold it into CSINC/CSINV.
191   setOperationAction(ISD::XOR, MVT::i32, Custom);
192   setOperationAction(ISD::XOR, MVT::i64, Custom);
193 
194   // Virtually no operation on f128 is legal, but LLVM can't expand them when
195   // there's a valid register class, so we need custom operations in most cases.
196   setOperationAction(ISD::FABS, MVT::f128, Expand);
197   setOperationAction(ISD::FADD, MVT::f128, Custom);
198   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
199   setOperationAction(ISD::FCOS, MVT::f128, Expand);
200   setOperationAction(ISD::FDIV, MVT::f128, Custom);
201   setOperationAction(ISD::FMA, MVT::f128, Expand);
202   setOperationAction(ISD::FMUL, MVT::f128, Custom);
203   setOperationAction(ISD::FNEG, MVT::f128, Expand);
204   setOperationAction(ISD::FPOW, MVT::f128, Expand);
205   setOperationAction(ISD::FREM, MVT::f128, Expand);
206   setOperationAction(ISD::FRINT, MVT::f128, Expand);
207   setOperationAction(ISD::FSIN, MVT::f128, Expand);
208   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
209   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
210   setOperationAction(ISD::FSUB, MVT::f128, Custom);
211   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
212   setOperationAction(ISD::SETCC, MVT::f128, Custom);
213   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
214   setOperationAction(ISD::SELECT, MVT::f128, Custom);
215   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
216   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
217 
218   // Lowering for many of the conversions is actually specified by the non-f128
219   // type. The LowerXXX function will be trivial when f128 isn't involved.
220   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
221   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
222   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
223   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
224   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
225   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
226   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
227   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
228   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
229   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
230   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
231   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
232   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
233   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
234 
235   // Variable arguments.
236   setOperationAction(ISD::VASTART, MVT::Other, Custom);
237   setOperationAction(ISD::VAARG, MVT::Other, Custom);
238   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
239   setOperationAction(ISD::VAEND, MVT::Other, Expand);
240 
241   // Variable-sized objects.
242   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
243   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
244   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
245 
246   // Constant pool entries
247   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
248 
249   // BlockAddress
250   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
251 
252   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
253   setOperationAction(ISD::ADDC, MVT::i32, Custom);
254   setOperationAction(ISD::ADDE, MVT::i32, Custom);
255   setOperationAction(ISD::SUBC, MVT::i32, Custom);
256   setOperationAction(ISD::SUBE, MVT::i32, Custom);
257   setOperationAction(ISD::ADDC, MVT::i64, Custom);
258   setOperationAction(ISD::ADDE, MVT::i64, Custom);
259   setOperationAction(ISD::SUBC, MVT::i64, Custom);
260   setOperationAction(ISD::SUBE, MVT::i64, Custom);
261 
262   // AArch64 lacks both left-rotate and popcount instructions.
263   setOperationAction(ISD::ROTL, MVT::i32, Expand);
264   setOperationAction(ISD::ROTL, MVT::i64, Expand);
265   for (MVT VT : MVT::vector_valuetypes()) {
266     setOperationAction(ISD::ROTL, VT, Expand);
267     setOperationAction(ISD::ROTR, VT, Expand);
268   }
269 
270   // AArch64 doesn't have {U|S}MUL_LOHI.
271   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
272   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
273 
274   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
275   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
276 
277   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
278   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
279   for (MVT VT : MVT::vector_valuetypes()) {
280     setOperationAction(ISD::SDIVREM, VT, Expand);
281     setOperationAction(ISD::UDIVREM, VT, Expand);
282   }
283   setOperationAction(ISD::SREM, MVT::i32, Expand);
284   setOperationAction(ISD::SREM, MVT::i64, Expand);
285   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::UREM, MVT::i32, Expand);
288   setOperationAction(ISD::UREM, MVT::i64, Expand);
289 
290   // Custom lower Add/Sub/Mul with overflow.
291   setOperationAction(ISD::SADDO, MVT::i32, Custom);
292   setOperationAction(ISD::SADDO, MVT::i64, Custom);
293   setOperationAction(ISD::UADDO, MVT::i32, Custom);
294   setOperationAction(ISD::UADDO, MVT::i64, Custom);
295   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
296   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
297   setOperationAction(ISD::USUBO, MVT::i32, Custom);
298   setOperationAction(ISD::USUBO, MVT::i64, Custom);
299   setOperationAction(ISD::SMULO, MVT::i32, Custom);
300   setOperationAction(ISD::SMULO, MVT::i64, Custom);
301   setOperationAction(ISD::UMULO, MVT::i32, Custom);
302   setOperationAction(ISD::UMULO, MVT::i64, Custom);
303 
304   setOperationAction(ISD::FSIN, MVT::f32, Expand);
305   setOperationAction(ISD::FSIN, MVT::f64, Expand);
306   setOperationAction(ISD::FCOS, MVT::f32, Expand);
307   setOperationAction(ISD::FCOS, MVT::f64, Expand);
308   setOperationAction(ISD::FPOW, MVT::f32, Expand);
309   setOperationAction(ISD::FPOW, MVT::f64, Expand);
310   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
311   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
312 
313   // f16 is a storage-only type, always promote it to f32.
314   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
315   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
316   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
317   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
318   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
319   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
320   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
321   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
322   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
323   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
324   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
325   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
326   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
327   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
328   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
329   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
330   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
331   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
332   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
333   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
334   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
335   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
336   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
337   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
338   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
339   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
340   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
341   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
342   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
343   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
344   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
345   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
346   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
347   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
348 
349   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
350   // known to be safe.
351   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
352   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
353   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
354   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
355   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
356   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
357   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
358   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
359   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
360   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
361   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
362   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
363 
364   // Expand all other v4f16 operations.
365   // FIXME: We could generate better code by promoting some operations to
366   // a pair of v4f32s
367   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
368   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
369   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
370   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
371   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
372   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
373   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
374   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
375   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
376   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
377   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
378   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
379   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
380   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
381   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
382   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
383   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
384   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
385   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
386   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
387   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
388   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
389   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
390   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
391   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
392   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
393 
394 
395   // v8f16 is also a storage-only type, so expand it.
396   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
397   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
398   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
399   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
400   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
401   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
402   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
403   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
404   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
405   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
406   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
407   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
408   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
409   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
410   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
411   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
412   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
413   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
414   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
415   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
416   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
417   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
418   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
419   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
420   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
421   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
422   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
423   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
424   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
425   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
426   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
427 
428   // AArch64 has implementations of a lot of rounding-like FP operations.
429   for (MVT Ty : {MVT::f32, MVT::f64}) {
430     setOperationAction(ISD::FFLOOR, Ty, Legal);
431     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
432     setOperationAction(ISD::FCEIL, Ty, Legal);
433     setOperationAction(ISD::FRINT, Ty, Legal);
434     setOperationAction(ISD::FTRUNC, Ty, Legal);
435     setOperationAction(ISD::FROUND, Ty, Legal);
436     setOperationAction(ISD::FMINNUM, Ty, Legal);
437     setOperationAction(ISD::FMAXNUM, Ty, Legal);
438     setOperationAction(ISD::FMINNAN, Ty, Legal);
439     setOperationAction(ISD::FMAXNAN, Ty, Legal);
440   }
441 
442   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
443 
444   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
445 
446   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
447   // This requires the Performance Monitors extension.
448   if (Subtarget->hasPerfMon())
449     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
450 
451   if (Subtarget->isTargetMachO()) {
452     // For iOS, we don't want to the normal expansion of a libcall to
453     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
454     // traffic.
455     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
456     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
457   } else {
458     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
459     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
460   }
461 
462   // Make floating-point constants legal for the large code model, so they don't
463   // become loads from the constant pool.
464   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
465     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
466     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
467   }
468 
469   // AArch64 does not have floating-point extending loads, i1 sign-extending
470   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
471   for (MVT VT : MVT::fp_valuetypes()) {
472     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
473     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
474     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
475     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
476   }
477   for (MVT VT : MVT::integer_valuetypes())
478     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
479 
480   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
481   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
482   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
483   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
484   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
485   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
486   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
487 
488   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
489   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
490 
491   // Indexed loads and stores are supported.
492   for (unsigned im = (unsigned)ISD::PRE_INC;
493        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
494     setIndexedLoadAction(im, MVT::i8, Legal);
495     setIndexedLoadAction(im, MVT::i16, Legal);
496     setIndexedLoadAction(im, MVT::i32, Legal);
497     setIndexedLoadAction(im, MVT::i64, Legal);
498     setIndexedLoadAction(im, MVT::f64, Legal);
499     setIndexedLoadAction(im, MVT::f32, Legal);
500     setIndexedLoadAction(im, MVT::f16, Legal);
501     setIndexedStoreAction(im, MVT::i8, Legal);
502     setIndexedStoreAction(im, MVT::i16, Legal);
503     setIndexedStoreAction(im, MVT::i32, Legal);
504     setIndexedStoreAction(im, MVT::i64, Legal);
505     setIndexedStoreAction(im, MVT::f64, Legal);
506     setIndexedStoreAction(im, MVT::f32, Legal);
507     setIndexedStoreAction(im, MVT::f16, Legal);
508   }
509 
510   // Trap.
511   setOperationAction(ISD::TRAP, MVT::Other, Legal);
512 
513   // We combine OR nodes for bitfield operations.
514   setTargetDAGCombine(ISD::OR);
515 
516   // Vector add and sub nodes may conceal a high-half opportunity.
517   // Also, try to fold ADD into CSINC/CSINV..
518   setTargetDAGCombine(ISD::ADD);
519   setTargetDAGCombine(ISD::SUB);
520   setTargetDAGCombine(ISD::SRL);
521   setTargetDAGCombine(ISD::XOR);
522   setTargetDAGCombine(ISD::SINT_TO_FP);
523   setTargetDAGCombine(ISD::UINT_TO_FP);
524 
525   setTargetDAGCombine(ISD::FP_TO_SINT);
526   setTargetDAGCombine(ISD::FP_TO_UINT);
527   setTargetDAGCombine(ISD::FDIV);
528 
529   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
530 
531   setTargetDAGCombine(ISD::ANY_EXTEND);
532   setTargetDAGCombine(ISD::ZERO_EXTEND);
533   setTargetDAGCombine(ISD::SIGN_EXTEND);
534   setTargetDAGCombine(ISD::BITCAST);
535   setTargetDAGCombine(ISD::CONCAT_VECTORS);
536   setTargetDAGCombine(ISD::STORE);
537   if (Subtarget->supportsAddressTopByteIgnored())
538     setTargetDAGCombine(ISD::LOAD);
539 
540   setTargetDAGCombine(ISD::MUL);
541 
542   setTargetDAGCombine(ISD::SELECT);
543   setTargetDAGCombine(ISD::VSELECT);
544 
545   setTargetDAGCombine(ISD::INTRINSIC_VOID);
546   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
547   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
548   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
549 
550   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
551   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
552   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
553 
554   setStackPointerRegisterToSaveRestore(AArch64::SP);
555 
556   setSchedulingPreference(Sched::Hybrid);
557 
558   EnableExtLdPromotion = true;
559 
560   // Set required alignment.
561   setMinFunctionAlignment(2);
562   // Set preferred alignments.
563   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
564   setPrefLoopAlignment(STI.getPrefLoopAlignment());
565 
566   // Only change the limit for entries in a jump table if specified by
567   // the subtarget, but not at the command line.
568   unsigned MaxJT = STI.getMaximumJumpTableSize();
569   if (MaxJT && getMaximumJumpTableSize() == 0)
570     setMaximumJumpTableSize(MaxJT);
571 
572   setHasExtractBitsInsn(true);
573 
574   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
575 
576   if (Subtarget->hasNEON()) {
577     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
578     // silliness like this:
579     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
580     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
581     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
582     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
583     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
584     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
585     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
586     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
587     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
588     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
589     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
590     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
591     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
592     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
593     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
594     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
595     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
596     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
597     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
598     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
599     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
600     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
601     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
602     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
603     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
604 
605     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
606     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
607     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
608     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
609     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
610 
611     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
612 
613     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
614     // elements smaller than i32, so promote the input to i32 first.
615     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
616     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
617     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
618     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
619     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
620     // -> v8f16 conversions.
621     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
622     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
623     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
624     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
625     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
626     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
627     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
628     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
629     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
630     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
631     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
632     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
633     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
634 
635     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
636     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
637 
638     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
639     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
640     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
641     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
642     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
643     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
644     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
645     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
646 
647     // AArch64 doesn't have MUL.2d:
648     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
649     // Custom handling for some quad-vector types to detect MULL.
650     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
651     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
652     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
653 
654     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
655     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
656     // Likewise, narrowing and extending vector loads/stores aren't handled
657     // directly.
658     for (MVT VT : MVT::vector_valuetypes()) {
659       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
660 
661       setOperationAction(ISD::MULHS, VT, Expand);
662       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
663       setOperationAction(ISD::MULHU, VT, Expand);
664       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
665 
666       setOperationAction(ISD::BSWAP, VT, Expand);
667 
668       for (MVT InnerVT : MVT::vector_valuetypes()) {
669         setTruncStoreAction(VT, InnerVT, Expand);
670         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
671         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
672         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
673       }
674     }
675 
676     // AArch64 has implementations of a lot of rounding-like FP operations.
677     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
678       setOperationAction(ISD::FFLOOR, Ty, Legal);
679       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
680       setOperationAction(ISD::FCEIL, Ty, Legal);
681       setOperationAction(ISD::FRINT, Ty, Legal);
682       setOperationAction(ISD::FTRUNC, Ty, Legal);
683       setOperationAction(ISD::FROUND, Ty, Legal);
684     }
685   }
686 
687   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
688 }
689 
690 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
691   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
692     setOperationAction(ISD::LOAD, VT, Promote);
693     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
694 
695     setOperationAction(ISD::STORE, VT, Promote);
696     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
697   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
698     setOperationAction(ISD::LOAD, VT, Promote);
699     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
700 
701     setOperationAction(ISD::STORE, VT, Promote);
702     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
703   }
704 
705   // Mark vector float intrinsics as expand.
706   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
707     setOperationAction(ISD::FSIN, VT, Expand);
708     setOperationAction(ISD::FCOS, VT, Expand);
709     setOperationAction(ISD::FPOWI, VT, Expand);
710     setOperationAction(ISD::FPOW, VT, Expand);
711     setOperationAction(ISD::FLOG, VT, Expand);
712     setOperationAction(ISD::FLOG2, VT, Expand);
713     setOperationAction(ISD::FLOG10, VT, Expand);
714     setOperationAction(ISD::FEXP, VT, Expand);
715     setOperationAction(ISD::FEXP2, VT, Expand);
716 
717     // But we do support custom-lowering for FCOPYSIGN.
718     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
719   }
720 
721   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
722   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
723   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
724   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
725   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
726   setOperationAction(ISD::SRA, VT, Custom);
727   setOperationAction(ISD::SRL, VT, Custom);
728   setOperationAction(ISD::SHL, VT, Custom);
729   setOperationAction(ISD::AND, VT, Custom);
730   setOperationAction(ISD::OR, VT, Custom);
731   setOperationAction(ISD::SETCC, VT, Custom);
732   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
733 
734   setOperationAction(ISD::SELECT, VT, Expand);
735   setOperationAction(ISD::SELECT_CC, VT, Expand);
736   setOperationAction(ISD::VSELECT, VT, Expand);
737   for (MVT InnerVT : MVT::all_valuetypes())
738     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
739 
740   // CNT supports only B element sizes.
741   if (VT != MVT::v8i8 && VT != MVT::v16i8)
742     setOperationAction(ISD::CTPOP, VT, Expand);
743 
744   setOperationAction(ISD::UDIV, VT, Expand);
745   setOperationAction(ISD::SDIV, VT, Expand);
746   setOperationAction(ISD::UREM, VT, Expand);
747   setOperationAction(ISD::SREM, VT, Expand);
748   setOperationAction(ISD::FREM, VT, Expand);
749 
750   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
751   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
752 
753   // [SU][MIN|MAX] are available for all NEON types apart from i64.
754   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
755     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
756       setOperationAction(Opcode, VT, Legal);
757 
758   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
759   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
760     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
761                             ISD::FMINNUM, ISD::FMAXNUM})
762       setOperationAction(Opcode, VT, Legal);
763 
764   if (Subtarget->isLittleEndian()) {
765     for (unsigned im = (unsigned)ISD::PRE_INC;
766          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
767       setIndexedLoadAction(im, VT, Legal);
768       setIndexedStoreAction(im, VT, Legal);
769     }
770   }
771 }
772 
773 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
774   addRegisterClass(VT, &AArch64::FPR64RegClass);
775   addTypeForNEON(VT, MVT::v2i32);
776 }
777 
778 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
779   addRegisterClass(VT, &AArch64::FPR128RegClass);
780   addTypeForNEON(VT, MVT::v4i32);
781 }
782 
783 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
784                                               EVT VT) const {
785   if (!VT.isVector())
786     return MVT::i32;
787   return VT.changeVectorElementTypeToInteger();
788 }
789 
790 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
791 /// Mask are known to be either zero or one and return them in the
792 /// KnownZero/KnownOne bitsets.
793 void AArch64TargetLowering::computeKnownBitsForTargetNode(
794     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
795     const SelectionDAG &DAG, unsigned Depth) const {
796   switch (Op.getOpcode()) {
797   default:
798     break;
799   case AArch64ISD::CSEL: {
800     APInt KnownZero2, KnownOne2;
801     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
802     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
803     KnownZero &= KnownZero2;
804     KnownOne &= KnownOne2;
805     break;
806   }
807   case ISD::INTRINSIC_W_CHAIN: {
808     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
809     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
810     switch (IntID) {
811     default: return;
812     case Intrinsic::aarch64_ldaxr:
813     case Intrinsic::aarch64_ldxr: {
814       unsigned BitWidth = KnownOne.getBitWidth();
815       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
816       unsigned MemBits = VT.getScalarSizeInBits();
817       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
818       return;
819     }
820     }
821     break;
822   }
823   case ISD::INTRINSIC_WO_CHAIN:
824   case ISD::INTRINSIC_VOID: {
825     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
826     switch (IntNo) {
827     default:
828       break;
829     case Intrinsic::aarch64_neon_umaxv:
830     case Intrinsic::aarch64_neon_uminv: {
831       // Figure out the datatype of the vector operand. The UMINV instruction
832       // will zero extend the result, so we can mark as known zero all the
833       // bits larger than the element datatype. 32-bit or larget doesn't need
834       // this as those are legal types and will be handled by isel directly.
835       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
836       unsigned BitWidth = KnownZero.getBitWidth();
837       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
838         assert(BitWidth >= 8 && "Unexpected width!");
839         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
840         KnownZero |= Mask;
841       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
842         assert(BitWidth >= 16 && "Unexpected width!");
843         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
844         KnownZero |= Mask;
845       }
846       break;
847     } break;
848     }
849   }
850   }
851 }
852 
853 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
854                                                   EVT) const {
855   return MVT::i64;
856 }
857 
858 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
859                                                            unsigned AddrSpace,
860                                                            unsigned Align,
861                                                            bool *Fast) const {
862   if (Subtarget->requiresStrictAlign())
863     return false;
864 
865   if (Fast) {
866     // Some CPUs are fine with unaligned stores except for 128-bit ones.
867     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
868             // See comments in performSTORECombine() for more details about
869             // these conditions.
870 
871             // Code that uses clang vector extensions can mark that it
872             // wants unaligned accesses to be treated as fast by
873             // underspecifying alignment to be 1 or 2.
874             Align <= 2 ||
875 
876             // Disregard v2i64. Memcpy lowering produces those and splitting
877             // them regresses performance on micro-benchmarks and olden/bh.
878             VT == MVT::v2i64;
879   }
880   return true;
881 }
882 
883 FastISel *
884 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
885                                       const TargetLibraryInfo *libInfo) const {
886   return AArch64::createFastISel(funcInfo, libInfo);
887 }
888 
889 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
890   switch ((AArch64ISD::NodeType)Opcode) {
891   case AArch64ISD::FIRST_NUMBER:      break;
892   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
893   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
894   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
895   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
896   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
897   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
898   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
899   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
900   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
901   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
902   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
903   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
904   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
905   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
906   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
907   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
908   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
909   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
910   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
911   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
912   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
913   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
914   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
915   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
916   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
917   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
918   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
919   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
920   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
921   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
922   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
923   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
924   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
925   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
926   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
927   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
928   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
929   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
930   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
931   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
932   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
933   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
934   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
935   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
936   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
937   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
938   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
939   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
940   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
941   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
942   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
943   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
944   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
945   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
946   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
947   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
948   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
949   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
950   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
951   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
952   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
953   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
954   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
955   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
956   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
957   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
958   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
959   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
960   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
961   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
962   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
963   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
964   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
965   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
966   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
967   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
968   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
969   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
970   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
971   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
972   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
973   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
974   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
975   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
976   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
977   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
978   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
979   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
980   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
981   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
982   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
983   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
984   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
985   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
986   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
987   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
988   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
989   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
990   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
991   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
992   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
993   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
994   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
995   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
996   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
997   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
998   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
999   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1000   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1001   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1002   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1003   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1004   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1005   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1006   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1007   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1008   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1009   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1010   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1011   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1012   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1013   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1014   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1015   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1016   }
1017   return nullptr;
1018 }
1019 
1020 MachineBasicBlock *
1021 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1022                                     MachineBasicBlock *MBB) const {
1023   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1024   // phi node:
1025 
1026   // OrigBB:
1027   //     [... previous instrs leading to comparison ...]
1028   //     b.ne TrueBB
1029   //     b EndBB
1030   // TrueBB:
1031   //     ; Fallthrough
1032   // EndBB:
1033   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1034 
1035   MachineFunction *MF = MBB->getParent();
1036   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1037   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1038   DebugLoc DL = MI.getDebugLoc();
1039   MachineFunction::iterator It = ++MBB->getIterator();
1040 
1041   unsigned DestReg = MI.getOperand(0).getReg();
1042   unsigned IfTrueReg = MI.getOperand(1).getReg();
1043   unsigned IfFalseReg = MI.getOperand(2).getReg();
1044   unsigned CondCode = MI.getOperand(3).getImm();
1045   bool NZCVKilled = MI.getOperand(4).isKill();
1046 
1047   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049   MF->insert(It, TrueBB);
1050   MF->insert(It, EndBB);
1051 
1052   // Transfer rest of current basic-block to EndBB
1053   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1054                 MBB->end());
1055   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1056 
1057   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1058   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1059   MBB->addSuccessor(TrueBB);
1060   MBB->addSuccessor(EndBB);
1061 
1062   // TrueBB falls through to the end.
1063   TrueBB->addSuccessor(EndBB);
1064 
1065   if (!NZCVKilled) {
1066     TrueBB->addLiveIn(AArch64::NZCV);
1067     EndBB->addLiveIn(AArch64::NZCV);
1068   }
1069 
1070   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1071       .addReg(IfTrueReg)
1072       .addMBB(TrueBB)
1073       .addReg(IfFalseReg)
1074       .addMBB(MBB);
1075 
1076   MI.eraseFromParent();
1077   return EndBB;
1078 }
1079 
1080 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1081     MachineInstr &MI, MachineBasicBlock *BB) const {
1082   switch (MI.getOpcode()) {
1083   default:
1084 #ifndef NDEBUG
1085     MI.dump();
1086 #endif
1087     llvm_unreachable("Unexpected instruction for custom inserter!");
1088 
1089   case AArch64::F128CSEL:
1090     return EmitF128CSEL(MI, BB);
1091 
1092   case TargetOpcode::STACKMAP:
1093   case TargetOpcode::PATCHPOINT:
1094     return emitPatchPoint(MI, BB);
1095   }
1096 }
1097 
1098 //===----------------------------------------------------------------------===//
1099 // AArch64 Lowering private implementation.
1100 //===----------------------------------------------------------------------===//
1101 
1102 //===----------------------------------------------------------------------===//
1103 // Lowering Code
1104 //===----------------------------------------------------------------------===//
1105 
1106 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1107 /// CC
1108 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1109   switch (CC) {
1110   default:
1111     llvm_unreachable("Unknown condition code!");
1112   case ISD::SETNE:
1113     return AArch64CC::NE;
1114   case ISD::SETEQ:
1115     return AArch64CC::EQ;
1116   case ISD::SETGT:
1117     return AArch64CC::GT;
1118   case ISD::SETGE:
1119     return AArch64CC::GE;
1120   case ISD::SETLT:
1121     return AArch64CC::LT;
1122   case ISD::SETLE:
1123     return AArch64CC::LE;
1124   case ISD::SETUGT:
1125     return AArch64CC::HI;
1126   case ISD::SETUGE:
1127     return AArch64CC::HS;
1128   case ISD::SETULT:
1129     return AArch64CC::LO;
1130   case ISD::SETULE:
1131     return AArch64CC::LS;
1132   }
1133 }
1134 
1135 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1136 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1137                                   AArch64CC::CondCode &CondCode,
1138                                   AArch64CC::CondCode &CondCode2) {
1139   CondCode2 = AArch64CC::AL;
1140   switch (CC) {
1141   default:
1142     llvm_unreachable("Unknown FP condition!");
1143   case ISD::SETEQ:
1144   case ISD::SETOEQ:
1145     CondCode = AArch64CC::EQ;
1146     break;
1147   case ISD::SETGT:
1148   case ISD::SETOGT:
1149     CondCode = AArch64CC::GT;
1150     break;
1151   case ISD::SETGE:
1152   case ISD::SETOGE:
1153     CondCode = AArch64CC::GE;
1154     break;
1155   case ISD::SETOLT:
1156     CondCode = AArch64CC::MI;
1157     break;
1158   case ISD::SETOLE:
1159     CondCode = AArch64CC::LS;
1160     break;
1161   case ISD::SETONE:
1162     CondCode = AArch64CC::MI;
1163     CondCode2 = AArch64CC::GT;
1164     break;
1165   case ISD::SETO:
1166     CondCode = AArch64CC::VC;
1167     break;
1168   case ISD::SETUO:
1169     CondCode = AArch64CC::VS;
1170     break;
1171   case ISD::SETUEQ:
1172     CondCode = AArch64CC::EQ;
1173     CondCode2 = AArch64CC::VS;
1174     break;
1175   case ISD::SETUGT:
1176     CondCode = AArch64CC::HI;
1177     break;
1178   case ISD::SETUGE:
1179     CondCode = AArch64CC::PL;
1180     break;
1181   case ISD::SETLT:
1182   case ISD::SETULT:
1183     CondCode = AArch64CC::LT;
1184     break;
1185   case ISD::SETLE:
1186   case ISD::SETULE:
1187     CondCode = AArch64CC::LE;
1188     break;
1189   case ISD::SETNE:
1190   case ISD::SETUNE:
1191     CondCode = AArch64CC::NE;
1192     break;
1193   }
1194 }
1195 
1196 /// Convert a DAG fp condition code to an AArch64 CC.
1197 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1198 /// should be AND'ed instead of OR'ed.
1199 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1200                                      AArch64CC::CondCode &CondCode,
1201                                      AArch64CC::CondCode &CondCode2) {
1202   CondCode2 = AArch64CC::AL;
1203   switch (CC) {
1204   default:
1205     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1206     assert(CondCode2 == AArch64CC::AL);
1207     break;
1208   case ISD::SETONE:
1209     // (a one b)
1210     // == ((a olt b) || (a ogt b))
1211     // == ((a ord b) && (a une b))
1212     CondCode = AArch64CC::VC;
1213     CondCode2 = AArch64CC::NE;
1214     break;
1215   case ISD::SETUEQ:
1216     // (a ueq b)
1217     // == ((a uno b) || (a oeq b))
1218     // == ((a ule b) && (a uge b))
1219     CondCode = AArch64CC::PL;
1220     CondCode2 = AArch64CC::LE;
1221     break;
1222   }
1223 }
1224 
1225 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1226 /// CC usable with the vector instructions. Fewer operations are available
1227 /// without a real NZCV register, so we have to use less efficient combinations
1228 /// to get the same effect.
1229 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1230                                         AArch64CC::CondCode &CondCode,
1231                                         AArch64CC::CondCode &CondCode2,
1232                                         bool &Invert) {
1233   Invert = false;
1234   switch (CC) {
1235   default:
1236     // Mostly the scalar mappings work fine.
1237     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1238     break;
1239   case ISD::SETUO:
1240     Invert = true;
1241     LLVM_FALLTHROUGH;
1242   case ISD::SETO:
1243     CondCode = AArch64CC::MI;
1244     CondCode2 = AArch64CC::GE;
1245     break;
1246   case ISD::SETUEQ:
1247   case ISD::SETULT:
1248   case ISD::SETULE:
1249   case ISD::SETUGT:
1250   case ISD::SETUGE:
1251     // All of the compare-mask comparisons are ordered, but we can switch
1252     // between the two by a double inversion. E.g. ULE == !OGT.
1253     Invert = true;
1254     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1255     break;
1256   }
1257 }
1258 
1259 static bool isLegalArithImmed(uint64_t C) {
1260   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1261   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1262 }
1263 
1264 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1265                               const SDLoc &dl, SelectionDAG &DAG) {
1266   EVT VT = LHS.getValueType();
1267 
1268   if (VT.isFloatingPoint()) {
1269     assert(VT != MVT::f128);
1270     if (VT == MVT::f16) {
1271       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1272       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1273       VT = MVT::f32;
1274     }
1275     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1276   }
1277 
1278   // The CMP instruction is just an alias for SUBS, and representing it as
1279   // SUBS means that it's possible to get CSE with subtract operations.
1280   // A later phase can perform the optimization of setting the destination
1281   // register to WZR/XZR if it ends up being unused.
1282   unsigned Opcode = AArch64ISD::SUBS;
1283 
1284   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1285       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1286     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1287     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1288     // can be set differently by this operation. It comes down to whether
1289     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1290     // everything is fine. If not then the optimization is wrong. Thus general
1291     // comparisons are only valid if op2 != 0.
1292 
1293     // So, finally, the only LLVM-native comparisons that don't mention C and V
1294     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1295     // the absence of information about op2.
1296     Opcode = AArch64ISD::ADDS;
1297     RHS = RHS.getOperand(1);
1298   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1299              !isUnsignedIntSetCC(CC)) {
1300     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1301     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1302     // of the signed comparisons.
1303     Opcode = AArch64ISD::ANDS;
1304     RHS = LHS.getOperand(1);
1305     LHS = LHS.getOperand(0);
1306   }
1307 
1308   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1309       .getValue(1);
1310 }
1311 
1312 /// \defgroup AArch64CCMP CMP;CCMP matching
1313 ///
1314 /// These functions deal with the formation of CMP;CCMP;... sequences.
1315 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1316 /// a comparison. They set the NZCV flags to a predefined value if their
1317 /// predicate is false. This allows to express arbitrary conjunctions, for
1318 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1319 /// expressed as:
1320 ///   cmp A
1321 ///   ccmp B, inv(CB), CA
1322 ///   check for CB flags
1323 ///
1324 /// In general we can create code for arbitrary "... (and (and A B) C)"
1325 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1326 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1327 /// negation operations:
1328 /// We can negate the results of a single comparison by inverting the flags
1329 /// used when the predicate fails and inverting the flags tested in the next
1330 /// instruction; We can also negate the results of the whole previous
1331 /// conditional compare sequence by inverting the flags tested in the next
1332 /// instruction. However there is no way to negate the result of a partial
1333 /// sequence.
1334 ///
1335 /// Therefore on encountering an "or" expression we can negate the subtree on
1336 /// one side and have to be able to push the negate to the leafs of the subtree
1337 /// on the other side (see also the comments in code). As complete example:
1338 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1339 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1340 /// is transformed to
1341 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1342 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1343 /// and implemented as:
1344 ///   cmp C
1345 ///   ccmp D, inv(CD), CC
1346 ///   ccmp A, CA, inv(CD)
1347 ///   ccmp B, CB, inv(CA)
1348 ///   check for CB flags
1349 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1350 /// by conditional compare sequences.
1351 /// @{
1352 
1353 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1354 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1355                                          ISD::CondCode CC, SDValue CCOp,
1356                                          AArch64CC::CondCode Predicate,
1357                                          AArch64CC::CondCode OutCC,
1358                                          const SDLoc &DL, SelectionDAG &DAG) {
1359   unsigned Opcode = 0;
1360   if (LHS.getValueType().isFloatingPoint()) {
1361     assert(LHS.getValueType() != MVT::f128);
1362     if (LHS.getValueType() == MVT::f16) {
1363       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1364       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1365     }
1366     Opcode = AArch64ISD::FCCMP;
1367   } else if (RHS.getOpcode() == ISD::SUB) {
1368     SDValue SubOp0 = RHS.getOperand(0);
1369     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1370       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1371       Opcode = AArch64ISD::CCMN;
1372       RHS = RHS.getOperand(1);
1373     }
1374   }
1375   if (Opcode == 0)
1376     Opcode = AArch64ISD::CCMP;
1377 
1378   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1379   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1380   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1381   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1382   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1383 }
1384 
1385 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1386 /// CanPushNegate is set to true if we can push a negate operation through
1387 /// the tree in a was that we are left with AND operations and negate operations
1388 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1389 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1390 /// brought into such a form.
1391 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1392                                          unsigned Depth = 0) {
1393   if (!Val.hasOneUse())
1394     return false;
1395   unsigned Opcode = Val->getOpcode();
1396   if (Opcode == ISD::SETCC) {
1397     if (Val->getOperand(0).getValueType() == MVT::f128)
1398       return false;
1399     CanNegate = true;
1400     return true;
1401   }
1402   // Protect against exponential runtime and stack overflow.
1403   if (Depth > 6)
1404     return false;
1405   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1406     SDValue O0 = Val->getOperand(0);
1407     SDValue O1 = Val->getOperand(1);
1408     bool CanNegateL;
1409     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1410       return false;
1411     bool CanNegateR;
1412     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1413       return false;
1414 
1415     if (Opcode == ISD::OR) {
1416       // For an OR expression we need to be able to negate at least one side or
1417       // we cannot do the transformation at all.
1418       if (!CanNegateL && !CanNegateR)
1419         return false;
1420       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1421       // can negate the x and y subtrees.
1422       CanNegate = CanNegateL && CanNegateR;
1423     } else {
1424       // If the operands are OR expressions then we finally need to negate their
1425       // outputs, we can only do that for the operand with emitted last by
1426       // negating OutCC, not for both operands.
1427       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1428       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1429       if (NeedsNegOutL && NeedsNegOutR)
1430         return false;
1431       // We cannot negate an AND operation (it would become an OR),
1432       CanNegate = false;
1433     }
1434     return true;
1435   }
1436   return false;
1437 }
1438 
1439 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1440 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1441 /// Tries to transform the given i1 producing node @p Val to a series compare
1442 /// and conditional compare operations. @returns an NZCV flags producing node
1443 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1444 /// transformation was not possible.
1445 /// On recursive invocations @p PushNegate may be set to true to have negation
1446 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1447 /// for the comparisons in the current subtree; @p Depth limits the search
1448 /// depth to avoid stack overflow.
1449 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1450     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1451     AArch64CC::CondCode Predicate) {
1452   // We're at a tree leaf, produce a conditional comparison operation.
1453   unsigned Opcode = Val->getOpcode();
1454   if (Opcode == ISD::SETCC) {
1455     SDValue LHS = Val->getOperand(0);
1456     SDValue RHS = Val->getOperand(1);
1457     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1458     bool isInteger = LHS.getValueType().isInteger();
1459     if (Negate)
1460       CC = getSetCCInverse(CC, isInteger);
1461     SDLoc DL(Val);
1462     // Determine OutCC and handle FP special case.
1463     if (isInteger) {
1464       OutCC = changeIntCCToAArch64CC(CC);
1465     } else {
1466       assert(LHS.getValueType().isFloatingPoint());
1467       AArch64CC::CondCode ExtraCC;
1468       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1469       // Some floating point conditions can't be tested with a single condition
1470       // code. Construct an additional comparison in this case.
1471       if (ExtraCC != AArch64CC::AL) {
1472         SDValue ExtraCmp;
1473         if (!CCOp.getNode())
1474           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1475         else
1476           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1477                                                ExtraCC, DL, DAG);
1478         CCOp = ExtraCmp;
1479         Predicate = ExtraCC;
1480       }
1481     }
1482 
1483     // Produce a normal comparison if we are first in the chain
1484     if (!CCOp)
1485       return emitComparison(LHS, RHS, CC, DL, DAG);
1486     // Otherwise produce a ccmp.
1487     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1488                                      DAG);
1489   }
1490   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1491          "Valid conjunction/disjunction tree");
1492 
1493   // Check if both sides can be transformed.
1494   SDValue LHS = Val->getOperand(0);
1495   SDValue RHS = Val->getOperand(1);
1496 
1497   // In case of an OR we need to negate our operands and the result.
1498   // (A v B) <=> not(not(A) ^ not(B))
1499   bool NegateOpsAndResult = Opcode == ISD::OR;
1500   // We can negate the results of all previous operations by inverting the
1501   // predicate flags giving us a free negation for one side. The other side
1502   // must be negatable by itself.
1503   if (NegateOpsAndResult) {
1504     // See which side we can negate.
1505     bool CanNegateL;
1506     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1507     assert(isValidL && "Valid conjunction/disjunction tree");
1508     (void)isValidL;
1509 
1510 #ifndef NDEBUG
1511     bool CanNegateR;
1512     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1513     assert(isValidR && "Valid conjunction/disjunction tree");
1514     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1515 #endif
1516 
1517     // Order the side which we cannot negate to RHS so we can emit it first.
1518     if (!CanNegateL)
1519       std::swap(LHS, RHS);
1520   } else {
1521     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1522     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1523            "Valid conjunction/disjunction tree");
1524     // Order the side where we need to negate the output flags to RHS so it
1525     // gets emitted first.
1526     if (NeedsNegOutL)
1527       std::swap(LHS, RHS);
1528   }
1529 
1530   // Emit RHS. If we want to negate the tree we only need to push a negate
1531   // through if we are already in a PushNegate case, otherwise we can negate
1532   // the "flags to test" afterwards.
1533   AArch64CC::CondCode RHSCC;
1534   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1535                                                    CCOp, Predicate);
1536   if (NegateOpsAndResult && !Negate)
1537     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1538   // Emit LHS. We may need to negate it.
1539   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1540                                                    NegateOpsAndResult, CmpR,
1541                                                    RHSCC);
1542   // If we transformed an OR to and AND then we have to negate the result
1543   // (or absorb the Negate parameter).
1544   if (NegateOpsAndResult && !Negate)
1545     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1546   return CmpL;
1547 }
1548 
1549 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1550 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1551 /// \see emitConjunctionDisjunctionTreeRec().
1552 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1553                                               AArch64CC::CondCode &OutCC) {
1554   bool CanNegate;
1555   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1556     return SDValue();
1557 
1558   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1559                                            AArch64CC::AL);
1560 }
1561 
1562 /// @}
1563 
1564 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1565                              SDValue &AArch64cc, SelectionDAG &DAG,
1566                              const SDLoc &dl) {
1567   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1568     EVT VT = RHS.getValueType();
1569     uint64_t C = RHSC->getZExtValue();
1570     if (!isLegalArithImmed(C)) {
1571       // Constant does not fit, try adjusting it by one?
1572       switch (CC) {
1573       default:
1574         break;
1575       case ISD::SETLT:
1576       case ISD::SETGE:
1577         if ((VT == MVT::i32 && C != 0x80000000 &&
1578              isLegalArithImmed((uint32_t)(C - 1))) ||
1579             (VT == MVT::i64 && C != 0x80000000ULL &&
1580              isLegalArithImmed(C - 1ULL))) {
1581           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1582           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1583           RHS = DAG.getConstant(C, dl, VT);
1584         }
1585         break;
1586       case ISD::SETULT:
1587       case ISD::SETUGE:
1588         if ((VT == MVT::i32 && C != 0 &&
1589              isLegalArithImmed((uint32_t)(C - 1))) ||
1590             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1591           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1592           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1593           RHS = DAG.getConstant(C, dl, VT);
1594         }
1595         break;
1596       case ISD::SETLE:
1597       case ISD::SETGT:
1598         if ((VT == MVT::i32 && C != INT32_MAX &&
1599              isLegalArithImmed((uint32_t)(C + 1))) ||
1600             (VT == MVT::i64 && C != INT64_MAX &&
1601              isLegalArithImmed(C + 1ULL))) {
1602           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1603           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1604           RHS = DAG.getConstant(C, dl, VT);
1605         }
1606         break;
1607       case ISD::SETULE:
1608       case ISD::SETUGT:
1609         if ((VT == MVT::i32 && C != UINT32_MAX &&
1610              isLegalArithImmed((uint32_t)(C + 1))) ||
1611             (VT == MVT::i64 && C != UINT64_MAX &&
1612              isLegalArithImmed(C + 1ULL))) {
1613           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1614           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1615           RHS = DAG.getConstant(C, dl, VT);
1616         }
1617         break;
1618       }
1619     }
1620   }
1621   SDValue Cmp;
1622   AArch64CC::CondCode AArch64CC;
1623   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1624     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1625 
1626     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1627     // For the i8 operand, the largest immediate is 255, so this can be easily
1628     // encoded in the compare instruction. For the i16 operand, however, the
1629     // largest immediate cannot be encoded in the compare.
1630     // Therefore, use a sign extending load and cmn to avoid materializing the
1631     // -1 constant. For example,
1632     // movz w1, #65535
1633     // ldrh w0, [x0, #0]
1634     // cmp w0, w1
1635     // >
1636     // ldrsh w0, [x0, #0]
1637     // cmn w0, #1
1638     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1639     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1640     // ensure both the LHS and RHS are truly zero extended and to make sure the
1641     // transformation is profitable.
1642     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1643         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1644         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1645         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1646       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1647       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1648         SDValue SExt =
1649             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1650                         DAG.getValueType(MVT::i16));
1651         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1652                                                    RHS.getValueType()),
1653                              CC, dl, DAG);
1654         AArch64CC = changeIntCCToAArch64CC(CC);
1655       }
1656     }
1657 
1658     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1659       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1660         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1661           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1662       }
1663     }
1664   }
1665 
1666   if (!Cmp) {
1667     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1668     AArch64CC = changeIntCCToAArch64CC(CC);
1669   }
1670   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1671   return Cmp;
1672 }
1673 
1674 static std::pair<SDValue, SDValue>
1675 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1676   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1677          "Unsupported value type");
1678   SDValue Value, Overflow;
1679   SDLoc DL(Op);
1680   SDValue LHS = Op.getOperand(0);
1681   SDValue RHS = Op.getOperand(1);
1682   unsigned Opc = 0;
1683   switch (Op.getOpcode()) {
1684   default:
1685     llvm_unreachable("Unknown overflow instruction!");
1686   case ISD::SADDO:
1687     Opc = AArch64ISD::ADDS;
1688     CC = AArch64CC::VS;
1689     break;
1690   case ISD::UADDO:
1691     Opc = AArch64ISD::ADDS;
1692     CC = AArch64CC::HS;
1693     break;
1694   case ISD::SSUBO:
1695     Opc = AArch64ISD::SUBS;
1696     CC = AArch64CC::VS;
1697     break;
1698   case ISD::USUBO:
1699     Opc = AArch64ISD::SUBS;
1700     CC = AArch64CC::LO;
1701     break;
1702   // Multiply needs a little bit extra work.
1703   case ISD::SMULO:
1704   case ISD::UMULO: {
1705     CC = AArch64CC::NE;
1706     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1707     if (Op.getValueType() == MVT::i32) {
1708       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1709       // For a 32 bit multiply with overflow check we want the instruction
1710       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1711       // need to generate the following pattern:
1712       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1713       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1714       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1715       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1716       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1717                                 DAG.getConstant(0, DL, MVT::i64));
1718       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1719       // operation. We need to clear out the upper 32 bits, because we used a
1720       // widening multiply that wrote all 64 bits. In the end this should be a
1721       // noop.
1722       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1723       if (IsSigned) {
1724         // The signed overflow check requires more than just a simple check for
1725         // any bit set in the upper 32 bits of the result. These bits could be
1726         // just the sign bits of a negative number. To perform the overflow
1727         // check we have to arithmetic shift right the 32nd bit of the result by
1728         // 31 bits. Then we compare the result to the upper 32 bits.
1729         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1730                                         DAG.getConstant(32, DL, MVT::i64));
1731         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1732         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1733                                         DAG.getConstant(31, DL, MVT::i64));
1734         // It is important that LowerBits is last, otherwise the arithmetic
1735         // shift will not be folded into the compare (SUBS).
1736         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1737         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1738                        .getValue(1);
1739       } else {
1740         // The overflow check for unsigned multiply is easy. We only need to
1741         // check if any of the upper 32 bits are set. This can be done with a
1742         // CMP (shifted register). For that we need to generate the following
1743         // pattern:
1744         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1745         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1746                                         DAG.getConstant(32, DL, MVT::i64));
1747         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1748         Overflow =
1749             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1750                         DAG.getConstant(0, DL, MVT::i64),
1751                         UpperBits).getValue(1);
1752       }
1753       break;
1754     }
1755     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1756     // For the 64 bit multiply
1757     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1758     if (IsSigned) {
1759       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1760       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1761                                       DAG.getConstant(63, DL, MVT::i64));
1762       // It is important that LowerBits is last, otherwise the arithmetic
1763       // shift will not be folded into the compare (SUBS).
1764       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1765       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1766                      .getValue(1);
1767     } else {
1768       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1769       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1770       Overflow =
1771           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1772                       DAG.getConstant(0, DL, MVT::i64),
1773                       UpperBits).getValue(1);
1774     }
1775     break;
1776   }
1777   } // switch (...)
1778 
1779   if (Opc) {
1780     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1781 
1782     // Emit the AArch64 operation with overflow check.
1783     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1784     Overflow = Value.getValue(1);
1785   }
1786   return std::make_pair(Value, Overflow);
1787 }
1788 
1789 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1790                                              RTLIB::Libcall Call) const {
1791   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1792   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1793 }
1794 
1795 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1796   SDValue Sel = Op.getOperand(0);
1797   SDValue Other = Op.getOperand(1);
1798 
1799   // If neither operand is a SELECT_CC, give up.
1800   if (Sel.getOpcode() != ISD::SELECT_CC)
1801     std::swap(Sel, Other);
1802   if (Sel.getOpcode() != ISD::SELECT_CC)
1803     return Op;
1804 
1805   // The folding we want to perform is:
1806   // (xor x, (select_cc a, b, cc, 0, -1) )
1807   //   -->
1808   // (csel x, (xor x, -1), cc ...)
1809   //
1810   // The latter will get matched to a CSINV instruction.
1811 
1812   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1813   SDValue LHS = Sel.getOperand(0);
1814   SDValue RHS = Sel.getOperand(1);
1815   SDValue TVal = Sel.getOperand(2);
1816   SDValue FVal = Sel.getOperand(3);
1817   SDLoc dl(Sel);
1818 
1819   // FIXME: This could be generalized to non-integer comparisons.
1820   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1821     return Op;
1822 
1823   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1824   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1825 
1826   // The values aren't constants, this isn't the pattern we're looking for.
1827   if (!CFVal || !CTVal)
1828     return Op;
1829 
1830   // We can commute the SELECT_CC by inverting the condition.  This
1831   // might be needed to make this fit into a CSINV pattern.
1832   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1833     std::swap(TVal, FVal);
1834     std::swap(CTVal, CFVal);
1835     CC = ISD::getSetCCInverse(CC, true);
1836   }
1837 
1838   // If the constants line up, perform the transform!
1839   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1840     SDValue CCVal;
1841     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1842 
1843     FVal = Other;
1844     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1845                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1846 
1847     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1848                        CCVal, Cmp);
1849   }
1850 
1851   return Op;
1852 }
1853 
1854 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1855   EVT VT = Op.getValueType();
1856 
1857   // Let legalize expand this if it isn't a legal type yet.
1858   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1859     return SDValue();
1860 
1861   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1862 
1863   unsigned Opc;
1864   bool ExtraOp = false;
1865   switch (Op.getOpcode()) {
1866   default:
1867     llvm_unreachable("Invalid code");
1868   case ISD::ADDC:
1869     Opc = AArch64ISD::ADDS;
1870     break;
1871   case ISD::SUBC:
1872     Opc = AArch64ISD::SUBS;
1873     break;
1874   case ISD::ADDE:
1875     Opc = AArch64ISD::ADCS;
1876     ExtraOp = true;
1877     break;
1878   case ISD::SUBE:
1879     Opc = AArch64ISD::SBCS;
1880     ExtraOp = true;
1881     break;
1882   }
1883 
1884   if (!ExtraOp)
1885     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1886   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1887                      Op.getOperand(2));
1888 }
1889 
1890 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1891   // Let legalize expand this if it isn't a legal type yet.
1892   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1893     return SDValue();
1894 
1895   SDLoc dl(Op);
1896   AArch64CC::CondCode CC;
1897   // The actual operation that sets the overflow or carry flag.
1898   SDValue Value, Overflow;
1899   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1900 
1901   // We use 0 and 1 as false and true values.
1902   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1903   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1904 
1905   // We use an inverted condition, because the conditional select is inverted
1906   // too. This will allow it to be selected to a single instruction:
1907   // CSINC Wd, WZR, WZR, invert(cond).
1908   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1909   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1910                          CCVal, Overflow);
1911 
1912   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1913   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1914 }
1915 
1916 // Prefetch operands are:
1917 // 1: Address to prefetch
1918 // 2: bool isWrite
1919 // 3: int locality (0 = no locality ... 3 = extreme locality)
1920 // 4: bool isDataCache
1921 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1922   SDLoc DL(Op);
1923   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1924   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1925   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1926 
1927   bool IsStream = !Locality;
1928   // When the locality number is set
1929   if (Locality) {
1930     // The front-end should have filtered out the out-of-range values
1931     assert(Locality <= 3 && "Prefetch locality out-of-range");
1932     // The locality degree is the opposite of the cache speed.
1933     // Put the number the other way around.
1934     // The encoding starts at 0 for level 1
1935     Locality = 3 - Locality;
1936   }
1937 
1938   // built the mask value encoding the expected behavior.
1939   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1940                    (!IsData << 3) |     // IsDataCache bit
1941                    (Locality << 1) |    // Cache level bits
1942                    (unsigned)IsStream;  // Stream bit
1943   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1944                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1945 }
1946 
1947 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1948                                               SelectionDAG &DAG) const {
1949   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1950 
1951   RTLIB::Libcall LC;
1952   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1953 
1954   return LowerF128Call(Op, DAG, LC);
1955 }
1956 
1957 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1958                                              SelectionDAG &DAG) const {
1959   if (Op.getOperand(0).getValueType() != MVT::f128) {
1960     // It's legal except when f128 is involved
1961     return Op;
1962   }
1963 
1964   RTLIB::Libcall LC;
1965   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1966 
1967   // FP_ROUND node has a second operand indicating whether it is known to be
1968   // precise. That doesn't take part in the LibCall so we can't directly use
1969   // LowerF128Call.
1970   SDValue SrcVal = Op.getOperand(0);
1971   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1972                      SDLoc(Op)).first;
1973 }
1974 
1975 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1976   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1977   // Any additional optimization in this function should be recorded
1978   // in the cost tables.
1979   EVT InVT = Op.getOperand(0).getValueType();
1980   EVT VT = Op.getValueType();
1981   unsigned NumElts = InVT.getVectorNumElements();
1982 
1983   // f16 vectors are promoted to f32 before a conversion.
1984   if (InVT.getVectorElementType() == MVT::f16) {
1985     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1986     SDLoc dl(Op);
1987     return DAG.getNode(
1988         Op.getOpcode(), dl, Op.getValueType(),
1989         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1990   }
1991 
1992   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1993     SDLoc dl(Op);
1994     SDValue Cv =
1995         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1996                     Op.getOperand(0));
1997     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1998   }
1999 
2000   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2001     SDLoc dl(Op);
2002     MVT ExtVT =
2003         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2004                          VT.getVectorNumElements());
2005     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2006     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2007   }
2008 
2009   // Type changing conversions are illegal.
2010   return Op;
2011 }
2012 
2013 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2014                                               SelectionDAG &DAG) const {
2015   if (Op.getOperand(0).getValueType().isVector())
2016     return LowerVectorFP_TO_INT(Op, DAG);
2017 
2018   // f16 conversions are promoted to f32.
2019   if (Op.getOperand(0).getValueType() == MVT::f16) {
2020     SDLoc dl(Op);
2021     return DAG.getNode(
2022         Op.getOpcode(), dl, Op.getValueType(),
2023         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2024   }
2025 
2026   if (Op.getOperand(0).getValueType() != MVT::f128) {
2027     // It's legal except when f128 is involved
2028     return Op;
2029   }
2030 
2031   RTLIB::Libcall LC;
2032   if (Op.getOpcode() == ISD::FP_TO_SINT)
2033     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2034   else
2035     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2036 
2037   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2038   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2039 }
2040 
2041 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2042   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2043   // Any additional optimization in this function should be recorded
2044   // in the cost tables.
2045   EVT VT = Op.getValueType();
2046   SDLoc dl(Op);
2047   SDValue In = Op.getOperand(0);
2048   EVT InVT = In.getValueType();
2049 
2050   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2051     MVT CastVT =
2052         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2053                          InVT.getVectorNumElements());
2054     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2055     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2056   }
2057 
2058   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2059     unsigned CastOpc =
2060         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2061     EVT CastVT = VT.changeVectorElementTypeToInteger();
2062     In = DAG.getNode(CastOpc, dl, CastVT, In);
2063     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2064   }
2065 
2066   return Op;
2067 }
2068 
2069 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2070                                             SelectionDAG &DAG) const {
2071   if (Op.getValueType().isVector())
2072     return LowerVectorINT_TO_FP(Op, DAG);
2073 
2074   // f16 conversions are promoted to f32.
2075   if (Op.getValueType() == MVT::f16) {
2076     SDLoc dl(Op);
2077     return DAG.getNode(
2078         ISD::FP_ROUND, dl, MVT::f16,
2079         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2080         DAG.getIntPtrConstant(0, dl));
2081   }
2082 
2083   // i128 conversions are libcalls.
2084   if (Op.getOperand(0).getValueType() == MVT::i128)
2085     return SDValue();
2086 
2087   // Other conversions are legal, unless it's to the completely software-based
2088   // fp128.
2089   if (Op.getValueType() != MVT::f128)
2090     return Op;
2091 
2092   RTLIB::Libcall LC;
2093   if (Op.getOpcode() == ISD::SINT_TO_FP)
2094     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2095   else
2096     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2097 
2098   return LowerF128Call(Op, DAG, LC);
2099 }
2100 
2101 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2102                                             SelectionDAG &DAG) const {
2103   // For iOS, we want to call an alternative entry point: __sincos_stret,
2104   // which returns the values in two S / D registers.
2105   SDLoc dl(Op);
2106   SDValue Arg = Op.getOperand(0);
2107   EVT ArgVT = Arg.getValueType();
2108   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2109 
2110   ArgListTy Args;
2111   ArgListEntry Entry;
2112 
2113   Entry.Node = Arg;
2114   Entry.Ty = ArgTy;
2115   Entry.isSExt = false;
2116   Entry.isZExt = false;
2117   Args.push_back(Entry);
2118 
2119   const char *LibcallName =
2120       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2121   SDValue Callee =
2122       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2123 
2124   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2125   TargetLowering::CallLoweringInfo CLI(DAG);
2126   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2127     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2128 
2129   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2130   return CallResult.first;
2131 }
2132 
2133 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2134   if (Op.getValueType() != MVT::f16)
2135     return SDValue();
2136 
2137   assert(Op.getOperand(0).getValueType() == MVT::i16);
2138   SDLoc DL(Op);
2139 
2140   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2141   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2142   return SDValue(
2143       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2144                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2145       0);
2146 }
2147 
2148 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2149   if (OrigVT.getSizeInBits() >= 64)
2150     return OrigVT;
2151 
2152   assert(OrigVT.isSimple() && "Expecting a simple value type");
2153 
2154   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2155   switch (OrigSimpleTy) {
2156   default: llvm_unreachable("Unexpected Vector Type");
2157   case MVT::v2i8:
2158   case MVT::v2i16:
2159      return MVT::v2i32;
2160   case MVT::v4i8:
2161     return  MVT::v4i16;
2162   }
2163 }
2164 
2165 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2166                                                  const EVT &OrigTy,
2167                                                  const EVT &ExtTy,
2168                                                  unsigned ExtOpcode) {
2169   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2170   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2171   // 64-bits we need to insert a new extension so that it will be 64-bits.
2172   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2173   if (OrigTy.getSizeInBits() >= 64)
2174     return N;
2175 
2176   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2177   EVT NewVT = getExtensionTo64Bits(OrigTy);
2178 
2179   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2180 }
2181 
2182 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2183                                    bool isSigned) {
2184   EVT VT = N->getValueType(0);
2185 
2186   if (N->getOpcode() != ISD::BUILD_VECTOR)
2187     return false;
2188 
2189   for (const SDValue &Elt : N->op_values()) {
2190     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2191       unsigned EltSize = VT.getScalarSizeInBits();
2192       unsigned HalfSize = EltSize / 2;
2193       if (isSigned) {
2194         if (!isIntN(HalfSize, C->getSExtValue()))
2195           return false;
2196       } else {
2197         if (!isUIntN(HalfSize, C->getZExtValue()))
2198           return false;
2199       }
2200       continue;
2201     }
2202     return false;
2203   }
2204 
2205   return true;
2206 }
2207 
2208 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2209   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2210     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2211                                              N->getOperand(0)->getValueType(0),
2212                                              N->getValueType(0),
2213                                              N->getOpcode());
2214 
2215   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2216   EVT VT = N->getValueType(0);
2217   SDLoc dl(N);
2218   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2219   unsigned NumElts = VT.getVectorNumElements();
2220   MVT TruncVT = MVT::getIntegerVT(EltSize);
2221   SmallVector<SDValue, 8> Ops;
2222   for (unsigned i = 0; i != NumElts; ++i) {
2223     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2224     const APInt &CInt = C->getAPIntValue();
2225     // Element types smaller than 32 bits are not legal, so use i32 elements.
2226     // The values are implicitly truncated so sext vs. zext doesn't matter.
2227     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2228   }
2229   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2230 }
2231 
2232 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2233   if (N->getOpcode() == ISD::SIGN_EXTEND)
2234     return true;
2235   if (isExtendedBUILD_VECTOR(N, DAG, true))
2236     return true;
2237   return false;
2238 }
2239 
2240 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2241   if (N->getOpcode() == ISD::ZERO_EXTEND)
2242     return true;
2243   if (isExtendedBUILD_VECTOR(N, DAG, false))
2244     return true;
2245   return false;
2246 }
2247 
2248 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2249   unsigned Opcode = N->getOpcode();
2250   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2251     SDNode *N0 = N->getOperand(0).getNode();
2252     SDNode *N1 = N->getOperand(1).getNode();
2253     return N0->hasOneUse() && N1->hasOneUse() &&
2254       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2255   }
2256   return false;
2257 }
2258 
2259 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2260   unsigned Opcode = N->getOpcode();
2261   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2262     SDNode *N0 = N->getOperand(0).getNode();
2263     SDNode *N1 = N->getOperand(1).getNode();
2264     return N0->hasOneUse() && N1->hasOneUse() &&
2265       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2266   }
2267   return false;
2268 }
2269 
2270 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2271   // Multiplications are only custom-lowered for 128-bit vectors so that
2272   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2273   EVT VT = Op.getValueType();
2274   assert(VT.is128BitVector() && VT.isInteger() &&
2275          "unexpected type for custom-lowering ISD::MUL");
2276   SDNode *N0 = Op.getOperand(0).getNode();
2277   SDNode *N1 = Op.getOperand(1).getNode();
2278   unsigned NewOpc = 0;
2279   bool isMLA = false;
2280   bool isN0SExt = isSignExtended(N0, DAG);
2281   bool isN1SExt = isSignExtended(N1, DAG);
2282   if (isN0SExt && isN1SExt)
2283     NewOpc = AArch64ISD::SMULL;
2284   else {
2285     bool isN0ZExt = isZeroExtended(N0, DAG);
2286     bool isN1ZExt = isZeroExtended(N1, DAG);
2287     if (isN0ZExt && isN1ZExt)
2288       NewOpc = AArch64ISD::UMULL;
2289     else if (isN1SExt || isN1ZExt) {
2290       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2291       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2292       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2293         NewOpc = AArch64ISD::SMULL;
2294         isMLA = true;
2295       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2296         NewOpc =  AArch64ISD::UMULL;
2297         isMLA = true;
2298       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2299         std::swap(N0, N1);
2300         NewOpc =  AArch64ISD::UMULL;
2301         isMLA = true;
2302       }
2303     }
2304 
2305     if (!NewOpc) {
2306       if (VT == MVT::v2i64)
2307         // Fall through to expand this.  It is not legal.
2308         return SDValue();
2309       else
2310         // Other vector multiplications are legal.
2311         return Op;
2312     }
2313   }
2314 
2315   // Legalize to a S/UMULL instruction
2316   SDLoc DL(Op);
2317   SDValue Op0;
2318   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2319   if (!isMLA) {
2320     Op0 = skipExtensionForVectorMULL(N0, DAG);
2321     assert(Op0.getValueType().is64BitVector() &&
2322            Op1.getValueType().is64BitVector() &&
2323            "unexpected types for extended operands to VMULL");
2324     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2325   }
2326   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2327   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2328   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2329   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2330   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2331   EVT Op1VT = Op1.getValueType();
2332   return DAG.getNode(N0->getOpcode(), DL, VT,
2333                      DAG.getNode(NewOpc, DL, VT,
2334                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2335                      DAG.getNode(NewOpc, DL, VT,
2336                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2337 }
2338 
2339 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2340                                                      SelectionDAG &DAG) const {
2341   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2342   SDLoc dl(Op);
2343   switch (IntNo) {
2344   default: return SDValue();    // Don't custom lower most intrinsics.
2345   case Intrinsic::thread_pointer: {
2346     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2347     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2348   }
2349   case Intrinsic::aarch64_neon_smax:
2350     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2351                        Op.getOperand(1), Op.getOperand(2));
2352   case Intrinsic::aarch64_neon_umax:
2353     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2354                        Op.getOperand(1), Op.getOperand(2));
2355   case Intrinsic::aarch64_neon_smin:
2356     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2357                        Op.getOperand(1), Op.getOperand(2));
2358   case Intrinsic::aarch64_neon_umin:
2359     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2360                        Op.getOperand(1), Op.getOperand(2));
2361   }
2362 }
2363 
2364 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2365                                               SelectionDAG &DAG) const {
2366   switch (Op.getOpcode()) {
2367   default:
2368     llvm_unreachable("unimplemented operand");
2369     return SDValue();
2370   case ISD::BITCAST:
2371     return LowerBITCAST(Op, DAG);
2372   case ISD::GlobalAddress:
2373     return LowerGlobalAddress(Op, DAG);
2374   case ISD::GlobalTLSAddress:
2375     return LowerGlobalTLSAddress(Op, DAG);
2376   case ISD::SETCC:
2377     return LowerSETCC(Op, DAG);
2378   case ISD::BR_CC:
2379     return LowerBR_CC(Op, DAG);
2380   case ISD::SELECT:
2381     return LowerSELECT(Op, DAG);
2382   case ISD::SELECT_CC:
2383     return LowerSELECT_CC(Op, DAG);
2384   case ISD::JumpTable:
2385     return LowerJumpTable(Op, DAG);
2386   case ISD::ConstantPool:
2387     return LowerConstantPool(Op, DAG);
2388   case ISD::BlockAddress:
2389     return LowerBlockAddress(Op, DAG);
2390   case ISD::VASTART:
2391     return LowerVASTART(Op, DAG);
2392   case ISD::VACOPY:
2393     return LowerVACOPY(Op, DAG);
2394   case ISD::VAARG:
2395     return LowerVAARG(Op, DAG);
2396   case ISD::ADDC:
2397   case ISD::ADDE:
2398   case ISD::SUBC:
2399   case ISD::SUBE:
2400     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2401   case ISD::SADDO:
2402   case ISD::UADDO:
2403   case ISD::SSUBO:
2404   case ISD::USUBO:
2405   case ISD::SMULO:
2406   case ISD::UMULO:
2407     return LowerXALUO(Op, DAG);
2408   case ISD::FADD:
2409     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2410   case ISD::FSUB:
2411     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2412   case ISD::FMUL:
2413     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2414   case ISD::FDIV:
2415     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2416   case ISD::FP_ROUND:
2417     return LowerFP_ROUND(Op, DAG);
2418   case ISD::FP_EXTEND:
2419     return LowerFP_EXTEND(Op, DAG);
2420   case ISD::FRAMEADDR:
2421     return LowerFRAMEADDR(Op, DAG);
2422   case ISD::RETURNADDR:
2423     return LowerRETURNADDR(Op, DAG);
2424   case ISD::INSERT_VECTOR_ELT:
2425     return LowerINSERT_VECTOR_ELT(Op, DAG);
2426   case ISD::EXTRACT_VECTOR_ELT:
2427     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2428   case ISD::BUILD_VECTOR:
2429     return LowerBUILD_VECTOR(Op, DAG);
2430   case ISD::VECTOR_SHUFFLE:
2431     return LowerVECTOR_SHUFFLE(Op, DAG);
2432   case ISD::EXTRACT_SUBVECTOR:
2433     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2434   case ISD::SRA:
2435   case ISD::SRL:
2436   case ISD::SHL:
2437     return LowerVectorSRA_SRL_SHL(Op, DAG);
2438   case ISD::SHL_PARTS:
2439     return LowerShiftLeftParts(Op, DAG);
2440   case ISD::SRL_PARTS:
2441   case ISD::SRA_PARTS:
2442     return LowerShiftRightParts(Op, DAG);
2443   case ISD::CTPOP:
2444     return LowerCTPOP(Op, DAG);
2445   case ISD::FCOPYSIGN:
2446     return LowerFCOPYSIGN(Op, DAG);
2447   case ISD::AND:
2448     return LowerVectorAND(Op, DAG);
2449   case ISD::OR:
2450     return LowerVectorOR(Op, DAG);
2451   case ISD::XOR:
2452     return LowerXOR(Op, DAG);
2453   case ISD::PREFETCH:
2454     return LowerPREFETCH(Op, DAG);
2455   case ISD::SINT_TO_FP:
2456   case ISD::UINT_TO_FP:
2457     return LowerINT_TO_FP(Op, DAG);
2458   case ISD::FP_TO_SINT:
2459   case ISD::FP_TO_UINT:
2460     return LowerFP_TO_INT(Op, DAG);
2461   case ISD::FSINCOS:
2462     return LowerFSINCOS(Op, DAG);
2463   case ISD::MUL:
2464     return LowerMUL(Op, DAG);
2465   case ISD::INTRINSIC_WO_CHAIN:
2466     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2467   }
2468 }
2469 
2470 //===----------------------------------------------------------------------===//
2471 //                      Calling Convention Implementation
2472 //===----------------------------------------------------------------------===//
2473 
2474 #include "AArch64GenCallingConv.inc"
2475 
2476 /// Selects the correct CCAssignFn for a given CallingConvention value.
2477 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2478                                                      bool IsVarArg) const {
2479   switch (CC) {
2480   default:
2481     llvm_unreachable("Unsupported calling convention.");
2482   case CallingConv::WebKit_JS:
2483     return CC_AArch64_WebKit_JS;
2484   case CallingConv::GHC:
2485     return CC_AArch64_GHC;
2486   case CallingConv::C:
2487   case CallingConv::Fast:
2488   case CallingConv::PreserveMost:
2489   case CallingConv::CXX_FAST_TLS:
2490   case CallingConv::Swift:
2491     if (!Subtarget->isTargetDarwin())
2492       return CC_AArch64_AAPCS;
2493     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2494   }
2495 }
2496 
2497 CCAssignFn *
2498 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2499   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2500                                       : RetCC_AArch64_AAPCS;
2501 }
2502 
2503 SDValue AArch64TargetLowering::LowerFormalArguments(
2504     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2505     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2506     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2507   MachineFunction &MF = DAG.getMachineFunction();
2508   MachineFrameInfo &MFI = MF.getFrameInfo();
2509 
2510   // Assign locations to all of the incoming arguments.
2511   SmallVector<CCValAssign, 16> ArgLocs;
2512   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2513                  *DAG.getContext());
2514 
2515   // At this point, Ins[].VT may already be promoted to i32. To correctly
2516   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2517   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2518   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2519   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2520   // LocVT.
2521   unsigned NumArgs = Ins.size();
2522   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2523   unsigned CurArgIdx = 0;
2524   for (unsigned i = 0; i != NumArgs; ++i) {
2525     MVT ValVT = Ins[i].VT;
2526     if (Ins[i].isOrigArg()) {
2527       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2528       CurArgIdx = Ins[i].getOrigArgIndex();
2529 
2530       // Get type of the original argument.
2531       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2532                                   /*AllowUnknown*/ true);
2533       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2534       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2535       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2536         ValVT = MVT::i8;
2537       else if (ActualMVT == MVT::i16)
2538         ValVT = MVT::i16;
2539     }
2540     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2541     bool Res =
2542         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2543     assert(!Res && "Call operand has unhandled type");
2544     (void)Res;
2545   }
2546   assert(ArgLocs.size() == Ins.size());
2547   SmallVector<SDValue, 16> ArgValues;
2548   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2549     CCValAssign &VA = ArgLocs[i];
2550 
2551     if (Ins[i].Flags.isByVal()) {
2552       // Byval is used for HFAs in the PCS, but the system should work in a
2553       // non-compliant manner for larger structs.
2554       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2555       int Size = Ins[i].Flags.getByValSize();
2556       unsigned NumRegs = (Size + 7) / 8;
2557 
2558       // FIXME: This works on big-endian for composite byvals, which are the common
2559       // case. It should also work for fundamental types too.
2560       unsigned FrameIdx =
2561         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2562       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2563       InVals.push_back(FrameIdxN);
2564 
2565       continue;
2566     }
2567 
2568     if (VA.isRegLoc()) {
2569       // Arguments stored in registers.
2570       EVT RegVT = VA.getLocVT();
2571 
2572       SDValue ArgValue;
2573       const TargetRegisterClass *RC;
2574 
2575       if (RegVT == MVT::i32)
2576         RC = &AArch64::GPR32RegClass;
2577       else if (RegVT == MVT::i64)
2578         RC = &AArch64::GPR64RegClass;
2579       else if (RegVT == MVT::f16)
2580         RC = &AArch64::FPR16RegClass;
2581       else if (RegVT == MVT::f32)
2582         RC = &AArch64::FPR32RegClass;
2583       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2584         RC = &AArch64::FPR64RegClass;
2585       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2586         RC = &AArch64::FPR128RegClass;
2587       else
2588         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2589 
2590       // Transform the arguments in physical registers into virtual ones.
2591       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2592       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2593 
2594       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2595       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2596       // truncate to the right size.
2597       switch (VA.getLocInfo()) {
2598       default:
2599         llvm_unreachable("Unknown loc info!");
2600       case CCValAssign::Full:
2601         break;
2602       case CCValAssign::BCvt:
2603         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2604         break;
2605       case CCValAssign::AExt:
2606       case CCValAssign::SExt:
2607       case CCValAssign::ZExt:
2608         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2609         // nodes after our lowering.
2610         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2611         break;
2612       }
2613 
2614       InVals.push_back(ArgValue);
2615 
2616     } else { // VA.isRegLoc()
2617       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2618       unsigned ArgOffset = VA.getLocMemOffset();
2619       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2620 
2621       uint32_t BEAlign = 0;
2622       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2623           !Ins[i].Flags.isInConsecutiveRegs())
2624         BEAlign = 8 - ArgSize;
2625 
2626       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2627 
2628       // Create load nodes to retrieve arguments from the stack.
2629       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2630       SDValue ArgValue;
2631 
2632       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2633       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2634       MVT MemVT = VA.getValVT();
2635 
2636       switch (VA.getLocInfo()) {
2637       default:
2638         break;
2639       case CCValAssign::BCvt:
2640         MemVT = VA.getLocVT();
2641         break;
2642       case CCValAssign::SExt:
2643         ExtType = ISD::SEXTLOAD;
2644         break;
2645       case CCValAssign::ZExt:
2646         ExtType = ISD::ZEXTLOAD;
2647         break;
2648       case CCValAssign::AExt:
2649         ExtType = ISD::EXTLOAD;
2650         break;
2651       }
2652 
2653       ArgValue = DAG.getExtLoad(
2654           ExtType, DL, VA.getLocVT(), Chain, FIN,
2655           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2656           MemVT);
2657 
2658       InVals.push_back(ArgValue);
2659     }
2660   }
2661 
2662   // varargs
2663   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2664   if (isVarArg) {
2665     if (!Subtarget->isTargetDarwin()) {
2666       // The AAPCS variadic function ABI is identical to the non-variadic
2667       // one. As a result there may be more arguments in registers and we should
2668       // save them for future reference.
2669       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2670     }
2671 
2672     // This will point to the next argument passed via stack.
2673     unsigned StackOffset = CCInfo.getNextStackOffset();
2674     // We currently pass all varargs at 8-byte alignment.
2675     StackOffset = ((StackOffset + 7) & ~7);
2676     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2677   }
2678 
2679   unsigned StackArgSize = CCInfo.getNextStackOffset();
2680   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2681   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2682     // This is a non-standard ABI so by fiat I say we're allowed to make full
2683     // use of the stack area to be popped, which must be aligned to 16 bytes in
2684     // any case:
2685     StackArgSize = alignTo(StackArgSize, 16);
2686 
2687     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2688     // a multiple of 16.
2689     FuncInfo->setArgumentStackToRestore(StackArgSize);
2690 
2691     // This realignment carries over to the available bytes below. Our own
2692     // callers will guarantee the space is free by giving an aligned value to
2693     // CALLSEQ_START.
2694   }
2695   // Even if we're not expected to free up the space, it's useful to know how
2696   // much is there while considering tail calls (because we can reuse it).
2697   FuncInfo->setBytesInStackArgArea(StackArgSize);
2698 
2699   return Chain;
2700 }
2701 
2702 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2703                                                 SelectionDAG &DAG,
2704                                                 const SDLoc &DL,
2705                                                 SDValue &Chain) const {
2706   MachineFunction &MF = DAG.getMachineFunction();
2707   MachineFrameInfo &MFI = MF.getFrameInfo();
2708   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2709   auto PtrVT = getPointerTy(DAG.getDataLayout());
2710 
2711   SmallVector<SDValue, 8> MemOps;
2712 
2713   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2714                                           AArch64::X3, AArch64::X4, AArch64::X5,
2715                                           AArch64::X6, AArch64::X7 };
2716   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2717   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2718 
2719   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2720   int GPRIdx = 0;
2721   if (GPRSaveSize != 0) {
2722     GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2723 
2724     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2725 
2726     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2727       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2728       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2729       SDValue Store = DAG.getStore(
2730           Val.getValue(1), DL, Val, FIN,
2731           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2732       MemOps.push_back(Store);
2733       FIN =
2734           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2735     }
2736   }
2737   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2738   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2739 
2740   if (Subtarget->hasFPARMv8()) {
2741     static const MCPhysReg FPRArgRegs[] = {
2742         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2743         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2744     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2745     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2746 
2747     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2748     int FPRIdx = 0;
2749     if (FPRSaveSize != 0) {
2750       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2751 
2752       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2753 
2754       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2755         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2756         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2757 
2758         SDValue Store = DAG.getStore(
2759             Val.getValue(1), DL, Val, FIN,
2760             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2761         MemOps.push_back(Store);
2762         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2763                           DAG.getConstant(16, DL, PtrVT));
2764       }
2765     }
2766     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2767     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2768   }
2769 
2770   if (!MemOps.empty()) {
2771     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2772   }
2773 }
2774 
2775 /// LowerCallResult - Lower the result values of a call into the
2776 /// appropriate copies out of appropriate physical registers.
2777 SDValue AArch64TargetLowering::LowerCallResult(
2778     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2779     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2780     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2781     SDValue ThisVal) const {
2782   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2783                           ? RetCC_AArch64_WebKit_JS
2784                           : RetCC_AArch64_AAPCS;
2785   // Assign locations to each value returned by this call.
2786   SmallVector<CCValAssign, 16> RVLocs;
2787   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2788                  *DAG.getContext());
2789   CCInfo.AnalyzeCallResult(Ins, RetCC);
2790 
2791   // Copy all of the result registers out of their specified physreg.
2792   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2793     CCValAssign VA = RVLocs[i];
2794 
2795     // Pass 'this' value directly from the argument to return value, to avoid
2796     // reg unit interference
2797     if (i == 0 && isThisReturn) {
2798       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2799              "unexpected return calling convention register assignment");
2800       InVals.push_back(ThisVal);
2801       continue;
2802     }
2803 
2804     SDValue Val =
2805         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2806     Chain = Val.getValue(1);
2807     InFlag = Val.getValue(2);
2808 
2809     switch (VA.getLocInfo()) {
2810     default:
2811       llvm_unreachable("Unknown loc info!");
2812     case CCValAssign::Full:
2813       break;
2814     case CCValAssign::BCvt:
2815       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2816       break;
2817     }
2818 
2819     InVals.push_back(Val);
2820   }
2821 
2822   return Chain;
2823 }
2824 
2825 /// Return true if the calling convention is one that we can guarantee TCO for.
2826 static bool canGuaranteeTCO(CallingConv::ID CC) {
2827   return CC == CallingConv::Fast;
2828 }
2829 
2830 /// Return true if we might ever do TCO for calls with this calling convention.
2831 static bool mayTailCallThisCC(CallingConv::ID CC) {
2832   switch (CC) {
2833   case CallingConv::C:
2834   case CallingConv::PreserveMost:
2835   case CallingConv::Swift:
2836     return true;
2837   default:
2838     return canGuaranteeTCO(CC);
2839   }
2840 }
2841 
2842 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2843     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2844     const SmallVectorImpl<ISD::OutputArg> &Outs,
2845     const SmallVectorImpl<SDValue> &OutVals,
2846     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2847   if (!mayTailCallThisCC(CalleeCC))
2848     return false;
2849 
2850   MachineFunction &MF = DAG.getMachineFunction();
2851   const Function *CallerF = MF.getFunction();
2852   CallingConv::ID CallerCC = CallerF->getCallingConv();
2853   bool CCMatch = CallerCC == CalleeCC;
2854 
2855   // Byval parameters hand the function a pointer directly into the stack area
2856   // we want to reuse during a tail call. Working around this *is* possible (see
2857   // X86) but less efficient and uglier in LowerCall.
2858   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2859                                     e = CallerF->arg_end();
2860        i != e; ++i)
2861     if (i->hasByValAttr())
2862       return false;
2863 
2864   if (getTargetMachine().Options.GuaranteedTailCallOpt)
2865     return canGuaranteeTCO(CalleeCC) && CCMatch;
2866 
2867   // Externally-defined functions with weak linkage should not be
2868   // tail-called on AArch64 when the OS does not support dynamic
2869   // pre-emption of symbols, as the AAELF spec requires normal calls
2870   // to undefined weak functions to be replaced with a NOP or jump to the
2871   // next instruction. The behaviour of branch instructions in this
2872   // situation (as used for tail calls) is implementation-defined, so we
2873   // cannot rely on the linker replacing the tail call with a return.
2874   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2875     const GlobalValue *GV = G->getGlobal();
2876     const Triple &TT = getTargetMachine().getTargetTriple();
2877     if (GV->hasExternalWeakLinkage() &&
2878         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2879       return false;
2880   }
2881 
2882   // Now we search for cases where we can use a tail call without changing the
2883   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2884   // concept.
2885 
2886   // I want anyone implementing a new calling convention to think long and hard
2887   // about this assert.
2888   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2889          "Unexpected variadic calling convention");
2890 
2891   LLVMContext &C = *DAG.getContext();
2892   if (isVarArg && !Outs.empty()) {
2893     // At least two cases here: if caller is fastcc then we can't have any
2894     // memory arguments (we'd be expected to clean up the stack afterwards). If
2895     // caller is C then we could potentially use its argument area.
2896 
2897     // FIXME: for now we take the most conservative of these in both cases:
2898     // disallow all variadic memory operands.
2899     SmallVector<CCValAssign, 16> ArgLocs;
2900     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2901 
2902     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2903     for (const CCValAssign &ArgLoc : ArgLocs)
2904       if (!ArgLoc.isRegLoc())
2905         return false;
2906   }
2907 
2908   // Check that the call results are passed in the same way.
2909   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2910                                   CCAssignFnForCall(CalleeCC, isVarArg),
2911                                   CCAssignFnForCall(CallerCC, isVarArg)))
2912     return false;
2913   // The callee has to preserve all registers the caller needs to preserve.
2914   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2915   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2916   if (!CCMatch) {
2917     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2918     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2919       return false;
2920   }
2921 
2922   // Nothing more to check if the callee is taking no arguments
2923   if (Outs.empty())
2924     return true;
2925 
2926   SmallVector<CCValAssign, 16> ArgLocs;
2927   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2928 
2929   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2930 
2931   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2932 
2933   // If the stack arguments for this call do not fit into our own save area then
2934   // the call cannot be made tail.
2935   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2936     return false;
2937 
2938   const MachineRegisterInfo &MRI = MF.getRegInfo();
2939   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2940     return false;
2941 
2942   return true;
2943 }
2944 
2945 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2946                                                    SelectionDAG &DAG,
2947                                                    MachineFrameInfo &MFI,
2948                                                    int ClobberedFI) const {
2949   SmallVector<SDValue, 8> ArgChains;
2950   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2951   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2952 
2953   // Include the original chain at the beginning of the list. When this is
2954   // used by target LowerCall hooks, this helps legalize find the
2955   // CALLSEQ_BEGIN node.
2956   ArgChains.push_back(Chain);
2957 
2958   // Add a chain value for each stack argument corresponding
2959   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2960                             UE = DAG.getEntryNode().getNode()->use_end();
2961        U != UE; ++U)
2962     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2963       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2964         if (FI->getIndex() < 0) {
2965           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2966           int64_t InLastByte = InFirstByte;
2967           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2968 
2969           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2970               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2971             ArgChains.push_back(SDValue(L, 1));
2972         }
2973 
2974   // Build a tokenfactor for all the chains.
2975   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2976 }
2977 
2978 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2979                                                    bool TailCallOpt) const {
2980   return CallCC == CallingConv::Fast && TailCallOpt;
2981 }
2982 
2983 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2984 /// and add input and output parameter nodes.
2985 SDValue
2986 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2987                                  SmallVectorImpl<SDValue> &InVals) const {
2988   SelectionDAG &DAG = CLI.DAG;
2989   SDLoc &DL = CLI.DL;
2990   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2991   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2992   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2993   SDValue Chain = CLI.Chain;
2994   SDValue Callee = CLI.Callee;
2995   bool &IsTailCall = CLI.IsTailCall;
2996   CallingConv::ID CallConv = CLI.CallConv;
2997   bool IsVarArg = CLI.IsVarArg;
2998 
2999   MachineFunction &MF = DAG.getMachineFunction();
3000   bool IsThisReturn = false;
3001 
3002   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3003   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3004   bool IsSibCall = false;
3005 
3006   if (IsTailCall) {
3007     // Check if it's really possible to do a tail call.
3008     IsTailCall = isEligibleForTailCallOptimization(
3009         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3010     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3011       report_fatal_error("failed to perform tail call elimination on a call "
3012                          "site marked musttail");
3013 
3014     // A sibling call is one where we're under the usual C ABI and not planning
3015     // to change that but can still do a tail call:
3016     if (!TailCallOpt && IsTailCall)
3017       IsSibCall = true;
3018 
3019     if (IsTailCall)
3020       ++NumTailCalls;
3021   }
3022 
3023   // Analyze operands of the call, assigning locations to each operand.
3024   SmallVector<CCValAssign, 16> ArgLocs;
3025   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3026                  *DAG.getContext());
3027 
3028   if (IsVarArg) {
3029     // Handle fixed and variable vector arguments differently.
3030     // Variable vector arguments always go into memory.
3031     unsigned NumArgs = Outs.size();
3032 
3033     for (unsigned i = 0; i != NumArgs; ++i) {
3034       MVT ArgVT = Outs[i].VT;
3035       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3036       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3037                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3038       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3039       assert(!Res && "Call operand has unhandled type");
3040       (void)Res;
3041     }
3042   } else {
3043     // At this point, Outs[].VT may already be promoted to i32. To correctly
3044     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3045     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3046     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3047     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3048     // LocVT.
3049     unsigned NumArgs = Outs.size();
3050     for (unsigned i = 0; i != NumArgs; ++i) {
3051       MVT ValVT = Outs[i].VT;
3052       // Get type of the original argument.
3053       EVT ActualVT = getValueType(DAG.getDataLayout(),
3054                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3055                                   /*AllowUnknown*/ true);
3056       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3057       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3058       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3059       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3060         ValVT = MVT::i8;
3061       else if (ActualMVT == MVT::i16)
3062         ValVT = MVT::i16;
3063 
3064       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3065       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3066       assert(!Res && "Call operand has unhandled type");
3067       (void)Res;
3068     }
3069   }
3070 
3071   // Get a count of how many bytes are to be pushed on the stack.
3072   unsigned NumBytes = CCInfo.getNextStackOffset();
3073 
3074   if (IsSibCall) {
3075     // Since we're not changing the ABI to make this a tail call, the memory
3076     // operands are already available in the caller's incoming argument space.
3077     NumBytes = 0;
3078   }
3079 
3080   // FPDiff is the byte offset of the call's argument area from the callee's.
3081   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3082   // by this amount for a tail call. In a sibling call it must be 0 because the
3083   // caller will deallocate the entire stack and the callee still expects its
3084   // arguments to begin at SP+0. Completely unused for non-tail calls.
3085   int FPDiff = 0;
3086 
3087   if (IsTailCall && !IsSibCall) {
3088     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3089 
3090     // Since callee will pop argument stack as a tail call, we must keep the
3091     // popped size 16-byte aligned.
3092     NumBytes = alignTo(NumBytes, 16);
3093 
3094     // FPDiff will be negative if this tail call requires more space than we
3095     // would automatically have in our incoming argument space. Positive if we
3096     // can actually shrink the stack.
3097     FPDiff = NumReusableBytes - NumBytes;
3098 
3099     // The stack pointer must be 16-byte aligned at all times it's used for a
3100     // memory operation, which in practice means at *all* times and in
3101     // particular across call boundaries. Therefore our own arguments started at
3102     // a 16-byte aligned SP and the delta applied for the tail call should
3103     // satisfy the same constraint.
3104     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3105   }
3106 
3107   // Adjust the stack pointer for the new arguments...
3108   // These operations are automatically eliminated by the prolog/epilog pass
3109   if (!IsSibCall)
3110     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3111                                                               true),
3112                                  DL);
3113 
3114   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3115                                         getPointerTy(DAG.getDataLayout()));
3116 
3117   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3118   SmallVector<SDValue, 8> MemOpChains;
3119   auto PtrVT = getPointerTy(DAG.getDataLayout());
3120 
3121   // Walk the register/memloc assignments, inserting copies/loads.
3122   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3123        ++i, ++realArgIdx) {
3124     CCValAssign &VA = ArgLocs[i];
3125     SDValue Arg = OutVals[realArgIdx];
3126     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3127 
3128     // Promote the value if needed.
3129     switch (VA.getLocInfo()) {
3130     default:
3131       llvm_unreachable("Unknown loc info!");
3132     case CCValAssign::Full:
3133       break;
3134     case CCValAssign::SExt:
3135       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3136       break;
3137     case CCValAssign::ZExt:
3138       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3139       break;
3140     case CCValAssign::AExt:
3141       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3142         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3143         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3144         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3145       }
3146       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3147       break;
3148     case CCValAssign::BCvt:
3149       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3150       break;
3151     case CCValAssign::FPExt:
3152       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3153       break;
3154     }
3155 
3156     if (VA.isRegLoc()) {
3157       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3158           Outs[0].VT == MVT::i64) {
3159         assert(VA.getLocVT() == MVT::i64 &&
3160                "unexpected calling convention register assignment");
3161         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3162                "unexpected use of 'returned'");
3163         IsThisReturn = true;
3164       }
3165       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3166     } else {
3167       assert(VA.isMemLoc());
3168 
3169       SDValue DstAddr;
3170       MachinePointerInfo DstInfo;
3171 
3172       // FIXME: This works on big-endian for composite byvals, which are the
3173       // common case. It should also work for fundamental types too.
3174       uint32_t BEAlign = 0;
3175       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3176                                         : VA.getValVT().getSizeInBits();
3177       OpSize = (OpSize + 7) / 8;
3178       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3179           !Flags.isInConsecutiveRegs()) {
3180         if (OpSize < 8)
3181           BEAlign = 8 - OpSize;
3182       }
3183       unsigned LocMemOffset = VA.getLocMemOffset();
3184       int32_t Offset = LocMemOffset + BEAlign;
3185       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3186       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3187 
3188       if (IsTailCall) {
3189         Offset = Offset + FPDiff;
3190         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3191 
3192         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3193         DstInfo =
3194             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3195 
3196         // Make sure any stack arguments overlapping with where we're storing
3197         // are loaded before this eventual operation. Otherwise they'll be
3198         // clobbered.
3199         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3200       } else {
3201         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3202 
3203         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3204         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3205                                                LocMemOffset);
3206       }
3207 
3208       if (Outs[i].Flags.isByVal()) {
3209         SDValue SizeNode =
3210             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3211         SDValue Cpy = DAG.getMemcpy(
3212             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3213             /*isVol = */ false, /*AlwaysInline = */ false,
3214             /*isTailCall = */ false,
3215             DstInfo, MachinePointerInfo());
3216 
3217         MemOpChains.push_back(Cpy);
3218       } else {
3219         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3220         // promoted to a legal register type i32, we should truncate Arg back to
3221         // i1/i8/i16.
3222         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3223             VA.getValVT() == MVT::i16)
3224           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3225 
3226         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3227         MemOpChains.push_back(Store);
3228       }
3229     }
3230   }
3231 
3232   if (!MemOpChains.empty())
3233     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3234 
3235   // Build a sequence of copy-to-reg nodes chained together with token chain
3236   // and flag operands which copy the outgoing args into the appropriate regs.
3237   SDValue InFlag;
3238   for (auto &RegToPass : RegsToPass) {
3239     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3240                              RegToPass.second, InFlag);
3241     InFlag = Chain.getValue(1);
3242   }
3243 
3244   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3245   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3246   // node so that legalize doesn't hack it.
3247   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3248       Subtarget->isTargetMachO()) {
3249     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3250       const GlobalValue *GV = G->getGlobal();
3251       bool InternalLinkage = GV->hasInternalLinkage();
3252       if (InternalLinkage)
3253         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3254       else {
3255         Callee =
3256             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3257         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3258       }
3259     } else if (ExternalSymbolSDNode *S =
3260                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3261       const char *Sym = S->getSymbol();
3262       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3263       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3264     }
3265   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3266     const GlobalValue *GV = G->getGlobal();
3267     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3268   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3269     const char *Sym = S->getSymbol();
3270     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3271   }
3272 
3273   // We don't usually want to end the call-sequence here because we would tidy
3274   // the frame up *after* the call, however in the ABI-changing tail-call case
3275   // we've carefully laid out the parameters so that when sp is reset they'll be
3276   // in the correct location.
3277   if (IsTailCall && !IsSibCall) {
3278     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3279                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3280     InFlag = Chain.getValue(1);
3281   }
3282 
3283   std::vector<SDValue> Ops;
3284   Ops.push_back(Chain);
3285   Ops.push_back(Callee);
3286 
3287   if (IsTailCall) {
3288     // Each tail call may have to adjust the stack by a different amount, so
3289     // this information must travel along with the operation for eventual
3290     // consumption by emitEpilogue.
3291     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3292   }
3293 
3294   // Add argument registers to the end of the list so that they are known live
3295   // into the call.
3296   for (auto &RegToPass : RegsToPass)
3297     Ops.push_back(DAG.getRegister(RegToPass.first,
3298                                   RegToPass.second.getValueType()));
3299 
3300   // Add a register mask operand representing the call-preserved registers.
3301   const uint32_t *Mask;
3302   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3303   if (IsThisReturn) {
3304     // For 'this' returns, use the X0-preserving mask if applicable
3305     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3306     if (!Mask) {
3307       IsThisReturn = false;
3308       Mask = TRI->getCallPreservedMask(MF, CallConv);
3309     }
3310   } else
3311     Mask = TRI->getCallPreservedMask(MF, CallConv);
3312 
3313   assert(Mask && "Missing call preserved mask for calling convention");
3314   Ops.push_back(DAG.getRegisterMask(Mask));
3315 
3316   if (InFlag.getNode())
3317     Ops.push_back(InFlag);
3318 
3319   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3320 
3321   // If we're doing a tall call, use a TC_RETURN here rather than an
3322   // actual call instruction.
3323   if (IsTailCall) {
3324     MF.getFrameInfo().setHasTailCall();
3325     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3326   }
3327 
3328   // Returns a chain and a flag for retval copy to use.
3329   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3330   InFlag = Chain.getValue(1);
3331 
3332   uint64_t CalleePopBytes =
3333       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3334 
3335   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3336                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3337                              InFlag, DL);
3338   if (!Ins.empty())
3339     InFlag = Chain.getValue(1);
3340 
3341   // Handle result values, copying them out of physregs into vregs that we
3342   // return.
3343   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3344                          InVals, IsThisReturn,
3345                          IsThisReturn ? OutVals[0] : SDValue());
3346 }
3347 
3348 bool AArch64TargetLowering::CanLowerReturn(
3349     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3350     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3351   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3352                           ? RetCC_AArch64_WebKit_JS
3353                           : RetCC_AArch64_AAPCS;
3354   SmallVector<CCValAssign, 16> RVLocs;
3355   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3356   return CCInfo.CheckReturn(Outs, RetCC);
3357 }
3358 
3359 SDValue
3360 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3361                                    bool isVarArg,
3362                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3363                                    const SmallVectorImpl<SDValue> &OutVals,
3364                                    const SDLoc &DL, SelectionDAG &DAG) const {
3365   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3366                           ? RetCC_AArch64_WebKit_JS
3367                           : RetCC_AArch64_AAPCS;
3368   SmallVector<CCValAssign, 16> RVLocs;
3369   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3370                  *DAG.getContext());
3371   CCInfo.AnalyzeReturn(Outs, RetCC);
3372 
3373   // Copy the result values into the output registers.
3374   SDValue Flag;
3375   SmallVector<SDValue, 4> RetOps(1, Chain);
3376   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3377        ++i, ++realRVLocIdx) {
3378     CCValAssign &VA = RVLocs[i];
3379     assert(VA.isRegLoc() && "Can only return in registers!");
3380     SDValue Arg = OutVals[realRVLocIdx];
3381 
3382     switch (VA.getLocInfo()) {
3383     default:
3384       llvm_unreachable("Unknown loc info!");
3385     case CCValAssign::Full:
3386       if (Outs[i].ArgVT == MVT::i1) {
3387         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3388         // value. This is strictly redundant on Darwin (which uses "zeroext
3389         // i1"), but will be optimised out before ISel.
3390         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3391         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3392       }
3393       break;
3394     case CCValAssign::BCvt:
3395       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3396       break;
3397     }
3398 
3399     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3400     Flag = Chain.getValue(1);
3401     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3402   }
3403   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3404   const MCPhysReg *I =
3405       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3406   if (I) {
3407     for (; *I; ++I) {
3408       if (AArch64::GPR64RegClass.contains(*I))
3409         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3410       else if (AArch64::FPR64RegClass.contains(*I))
3411         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3412       else
3413         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3414     }
3415   }
3416 
3417   RetOps[0] = Chain; // Update chain.
3418 
3419   // Add the flag if we have it.
3420   if (Flag.getNode())
3421     RetOps.push_back(Flag);
3422 
3423   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3424 }
3425 
3426 //===----------------------------------------------------------------------===//
3427 //  Other Lowering Code
3428 //===----------------------------------------------------------------------===//
3429 
3430 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3431                                                   SelectionDAG &DAG) const {
3432   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3433   SDLoc DL(Op);
3434   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3435   const GlobalValue *GV = GN->getGlobal();
3436   unsigned char OpFlags =
3437       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3438 
3439   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3440          "unexpected offset in global node");
3441 
3442   // This also catched the large code model case for Darwin.
3443   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3444     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3445     // FIXME: Once remat is capable of dealing with instructions with register
3446     // operands, expand this into two nodes instead of using a wrapper node.
3447     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3448   }
3449 
3450   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3451     const unsigned char MO_NC = AArch64II::MO_NC;
3452     return DAG.getNode(
3453         AArch64ISD::WrapperLarge, DL, PtrVT,
3454         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3455         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3456         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3457         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3458   } else {
3459     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3460     // the only correct model on Darwin.
3461     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3462                                             OpFlags | AArch64II::MO_PAGE);
3463     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3464     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3465 
3466     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3467     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3468   }
3469 }
3470 
3471 /// \brief Convert a TLS address reference into the correct sequence of loads
3472 /// and calls to compute the variable's address (for Darwin, currently) and
3473 /// return an SDValue containing the final node.
3474 
3475 /// Darwin only has one TLS scheme which must be capable of dealing with the
3476 /// fully general situation, in the worst case. This means:
3477 ///     + "extern __thread" declaration.
3478 ///     + Defined in a possibly unknown dynamic library.
3479 ///
3480 /// The general system is that each __thread variable has a [3 x i64] descriptor
3481 /// which contains information used by the runtime to calculate the address. The
3482 /// only part of this the compiler needs to know about is the first xword, which
3483 /// contains a function pointer that must be called with the address of the
3484 /// entire descriptor in "x0".
3485 ///
3486 /// Since this descriptor may be in a different unit, in general even the
3487 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3488 /// is:
3489 ///     adrp x0, _var@TLVPPAGE
3490 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3491 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3492 ///                                      ; the function pointer
3493 ///     blr x1                           ; Uses descriptor address in x0
3494 ///     ; Address of _var is now in x0.
3495 ///
3496 /// If the address of _var's descriptor *is* known to the linker, then it can
3497 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3498 /// a slight efficiency gain.
3499 SDValue
3500 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3501                                                    SelectionDAG &DAG) const {
3502   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3503 
3504   SDLoc DL(Op);
3505   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3506   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3507 
3508   SDValue TLVPAddr =
3509       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3510   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3511 
3512   // The first entry in the descriptor is a function pointer that we must call
3513   // to obtain the address of the variable.
3514   SDValue Chain = DAG.getEntryNode();
3515   SDValue FuncTLVGet = DAG.getLoad(
3516       MVT::i64, DL, Chain, DescAddr,
3517       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3518       /* Alignment = */ 8,
3519       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3520           MachineMemOperand::MODereferenceable);
3521   Chain = FuncTLVGet.getValue(1);
3522 
3523   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3524   MFI.setAdjustsStack(true);
3525 
3526   // TLS calls preserve all registers except those that absolutely must be
3527   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3528   // silly).
3529   const uint32_t *Mask =
3530       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3531 
3532   // Finally, we can make the call. This is just a degenerate version of a
3533   // normal AArch64 call node: x0 takes the address of the descriptor, and
3534   // returns the address of the variable in this thread.
3535   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3536   Chain =
3537       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3538                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3539                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3540   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3541 }
3542 
3543 /// When accessing thread-local variables under either the general-dynamic or
3544 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3545 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3546 /// is a function pointer to carry out the resolution.
3547 ///
3548 /// The sequence is:
3549 ///    adrp  x0, :tlsdesc:var
3550 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3551 ///    add   x0, x0, #:tlsdesc_lo12:var
3552 ///    .tlsdesccall var
3553 ///    blr   x1
3554 ///    (TPIDR_EL0 offset now in x0)
3555 ///
3556 ///  The above sequence must be produced unscheduled, to enable the linker to
3557 ///  optimize/relax this sequence.
3558 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3559 ///  above sequence, and expanded really late in the compilation flow, to ensure
3560 ///  the sequence is produced as per above.
3561 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3562                                                       const SDLoc &DL,
3563                                                       SelectionDAG &DAG) const {
3564   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3565 
3566   SDValue Chain = DAG.getEntryNode();
3567   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3568 
3569   Chain =
3570       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3571   SDValue Glue = Chain.getValue(1);
3572 
3573   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3574 }
3575 
3576 SDValue
3577 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3578                                                 SelectionDAG &DAG) const {
3579   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3580   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3581          "ELF TLS only supported in small memory model");
3582   // Different choices can be made for the maximum size of the TLS area for a
3583   // module. For the small address model, the default TLS size is 16MiB and the
3584   // maximum TLS size is 4GiB.
3585   // FIXME: add -mtls-size command line option and make it control the 16MiB
3586   // vs. 4GiB code sequence generation.
3587   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3588 
3589   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3590 
3591   if (DAG.getTarget().Options.EmulatedTLS)
3592     return LowerToTLSEmulatedModel(GA, DAG);
3593 
3594   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3595     if (Model == TLSModel::LocalDynamic)
3596       Model = TLSModel::GeneralDynamic;
3597   }
3598 
3599   SDValue TPOff;
3600   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3601   SDLoc DL(Op);
3602   const GlobalValue *GV = GA->getGlobal();
3603 
3604   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3605 
3606   if (Model == TLSModel::LocalExec) {
3607     SDValue HiVar = DAG.getTargetGlobalAddress(
3608         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3609     SDValue LoVar = DAG.getTargetGlobalAddress(
3610         GV, DL, PtrVT, 0,
3611         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3612 
3613     SDValue TPWithOff_lo =
3614         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3615                                    HiVar,
3616                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3617                 0);
3618     SDValue TPWithOff =
3619         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3620                                    LoVar,
3621                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3622                 0);
3623     return TPWithOff;
3624   } else if (Model == TLSModel::InitialExec) {
3625     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3626     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3627   } else if (Model == TLSModel::LocalDynamic) {
3628     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3629     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3630     // the beginning of the module's TLS region, followed by a DTPREL offset
3631     // calculation.
3632 
3633     // These accesses will need deduplicating if there's more than one.
3634     AArch64FunctionInfo *MFI =
3635         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3636     MFI->incNumLocalDynamicTLSAccesses();
3637 
3638     // The call needs a relocation too for linker relaxation. It doesn't make
3639     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3640     // the address.
3641     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3642                                                   AArch64II::MO_TLS);
3643 
3644     // Now we can calculate the offset from TPIDR_EL0 to this module's
3645     // thread-local area.
3646     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3647 
3648     // Now use :dtprel_whatever: operations to calculate this variable's offset
3649     // in its thread-storage area.
3650     SDValue HiVar = DAG.getTargetGlobalAddress(
3651         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3652     SDValue LoVar = DAG.getTargetGlobalAddress(
3653         GV, DL, MVT::i64, 0,
3654         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3655 
3656     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3657                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3658                     0);
3659     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3660                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3661                     0);
3662   } else if (Model == TLSModel::GeneralDynamic) {
3663     // The call needs a relocation too for linker relaxation. It doesn't make
3664     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3665     // the address.
3666     SDValue SymAddr =
3667         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3668 
3669     // Finally we can make a call to calculate the offset from tpidr_el0.
3670     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3671   } else
3672     llvm_unreachable("Unsupported ELF TLS access model");
3673 
3674   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3675 }
3676 
3677 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3678                                                      SelectionDAG &DAG) const {
3679   if (Subtarget->isTargetDarwin())
3680     return LowerDarwinGlobalTLSAddress(Op, DAG);
3681   else if (Subtarget->isTargetELF())
3682     return LowerELFGlobalTLSAddress(Op, DAG);
3683 
3684   llvm_unreachable("Unexpected platform trying to use TLS");
3685 }
3686 
3687 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3688   SDValue Chain = Op.getOperand(0);
3689   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3690   SDValue LHS = Op.getOperand(2);
3691   SDValue RHS = Op.getOperand(3);
3692   SDValue Dest = Op.getOperand(4);
3693   SDLoc dl(Op);
3694 
3695   // Handle f128 first, since lowering it will result in comparing the return
3696   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3697   // is expecting to deal with.
3698   if (LHS.getValueType() == MVT::f128) {
3699     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3700 
3701     // If softenSetCCOperands returned a scalar, we need to compare the result
3702     // against zero to select between true and false values.
3703     if (!RHS.getNode()) {
3704       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3705       CC = ISD::SETNE;
3706     }
3707   }
3708 
3709   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3710   // instruction.
3711   unsigned Opc = LHS.getOpcode();
3712   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3713       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3714        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3715     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3716            "Unexpected condition code.");
3717     // Only lower legal XALUO ops.
3718     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3719       return SDValue();
3720 
3721     // The actual operation with overflow check.
3722     AArch64CC::CondCode OFCC;
3723     SDValue Value, Overflow;
3724     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3725 
3726     if (CC == ISD::SETNE)
3727       OFCC = getInvertedCondCode(OFCC);
3728     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3729 
3730     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3731                        Overflow);
3732   }
3733 
3734   if (LHS.getValueType().isInteger()) {
3735     assert((LHS.getValueType() == RHS.getValueType()) &&
3736            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3737 
3738     // If the RHS of the comparison is zero, we can potentially fold this
3739     // to a specialized branch.
3740     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3741     if (RHSC && RHSC->getZExtValue() == 0) {
3742       if (CC == ISD::SETEQ) {
3743         // See if we can use a TBZ to fold in an AND as well.
3744         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3745         // out of bounds, a late MI-layer pass rewrites branches.
3746         // 403.gcc is an example that hits this case.
3747         if (LHS.getOpcode() == ISD::AND &&
3748             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3749             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3750           SDValue Test = LHS.getOperand(0);
3751           uint64_t Mask = LHS.getConstantOperandVal(1);
3752           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3753                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3754                              Dest);
3755         }
3756 
3757         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3758       } else if (CC == ISD::SETNE) {
3759         // See if we can use a TBZ to fold in an AND as well.
3760         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3761         // out of bounds, a late MI-layer pass rewrites branches.
3762         // 403.gcc is an example that hits this case.
3763         if (LHS.getOpcode() == ISD::AND &&
3764             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3765             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3766           SDValue Test = LHS.getOperand(0);
3767           uint64_t Mask = LHS.getConstantOperandVal(1);
3768           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3769                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3770                              Dest);
3771         }
3772 
3773         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3774       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3775         // Don't combine AND since emitComparison converts the AND to an ANDS
3776         // (a.k.a. TST) and the test in the test bit and branch instruction
3777         // becomes redundant.  This would also increase register pressure.
3778         uint64_t Mask = LHS.getValueSizeInBits() - 1;
3779         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3780                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3781       }
3782     }
3783     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3784         LHS.getOpcode() != ISD::AND) {
3785       // Don't combine AND since emitComparison converts the AND to an ANDS
3786       // (a.k.a. TST) and the test in the test bit and branch instruction
3787       // becomes redundant.  This would also increase register pressure.
3788       uint64_t Mask = LHS.getValueSizeInBits() - 1;
3789       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3790                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3791     }
3792 
3793     SDValue CCVal;
3794     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3795     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3796                        Cmp);
3797   }
3798 
3799   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3800 
3801   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3802   // clean.  Some of them require two branches to implement.
3803   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3804   AArch64CC::CondCode CC1, CC2;
3805   changeFPCCToAArch64CC(CC, CC1, CC2);
3806   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3807   SDValue BR1 =
3808       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3809   if (CC2 != AArch64CC::AL) {
3810     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3811     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3812                        Cmp);
3813   }
3814 
3815   return BR1;
3816 }
3817 
3818 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3819                                               SelectionDAG &DAG) const {
3820   EVT VT = Op.getValueType();
3821   SDLoc DL(Op);
3822 
3823   SDValue In1 = Op.getOperand(0);
3824   SDValue In2 = Op.getOperand(1);
3825   EVT SrcVT = In2.getValueType();
3826 
3827   if (SrcVT.bitsLT(VT))
3828     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3829   else if (SrcVT.bitsGT(VT))
3830     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3831 
3832   EVT VecVT;
3833   EVT EltVT;
3834   uint64_t EltMask;
3835   SDValue VecVal1, VecVal2;
3836   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3837     EltVT = MVT::i32;
3838     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3839     EltMask = 0x80000000ULL;
3840 
3841     if (!VT.isVector()) {
3842       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3843                                           DAG.getUNDEF(VecVT), In1);
3844       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3845                                           DAG.getUNDEF(VecVT), In2);
3846     } else {
3847       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3848       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3849     }
3850   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3851     EltVT = MVT::i64;
3852     VecVT = MVT::v2i64;
3853 
3854     // We want to materialize a mask with the high bit set, but the AdvSIMD
3855     // immediate moves cannot materialize that in a single instruction for
3856     // 64-bit elements. Instead, materialize zero and then negate it.
3857     EltMask = 0;
3858 
3859     if (!VT.isVector()) {
3860       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3861                                           DAG.getUNDEF(VecVT), In1);
3862       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3863                                           DAG.getUNDEF(VecVT), In2);
3864     } else {
3865       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3866       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3867     }
3868   } else {
3869     llvm_unreachable("Invalid type for copysign!");
3870   }
3871 
3872   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3873 
3874   // If we couldn't materialize the mask above, then the mask vector will be
3875   // the zero vector, and we need to negate it here.
3876   if (VT == MVT::f64 || VT == MVT::v2f64) {
3877     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3878     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3879     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3880   }
3881 
3882   SDValue Sel =
3883       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3884 
3885   if (VT == MVT::f32)
3886     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3887   else if (VT == MVT::f64)
3888     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3889   else
3890     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3891 }
3892 
3893 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3894   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3895           Attribute::NoImplicitFloat))
3896     return SDValue();
3897 
3898   if (!Subtarget->hasNEON())
3899     return SDValue();
3900 
3901   // While there is no integer popcount instruction, it can
3902   // be more efficiently lowered to the following sequence that uses
3903   // AdvSIMD registers/instructions as long as the copies to/from
3904   // the AdvSIMD registers are cheap.
3905   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3906   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3907   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3908   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3909   SDValue Val = Op.getOperand(0);
3910   SDLoc DL(Op);
3911   EVT VT = Op.getValueType();
3912 
3913   if (VT == MVT::i32)
3914     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3915   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3916 
3917   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3918   SDValue UaddLV = DAG.getNode(
3919       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3920       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3921 
3922   if (VT == MVT::i64)
3923     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3924   return UaddLV;
3925 }
3926 
3927 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3928 
3929   if (Op.getValueType().isVector())
3930     return LowerVSETCC(Op, DAG);
3931 
3932   SDValue LHS = Op.getOperand(0);
3933   SDValue RHS = Op.getOperand(1);
3934   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3935   SDLoc dl(Op);
3936 
3937   // We chose ZeroOrOneBooleanContents, so use zero and one.
3938   EVT VT = Op.getValueType();
3939   SDValue TVal = DAG.getConstant(1, dl, VT);
3940   SDValue FVal = DAG.getConstant(0, dl, VT);
3941 
3942   // Handle f128 first, since one possible outcome is a normal integer
3943   // comparison which gets picked up by the next if statement.
3944   if (LHS.getValueType() == MVT::f128) {
3945     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3946 
3947     // If softenSetCCOperands returned a scalar, use it.
3948     if (!RHS.getNode()) {
3949       assert(LHS.getValueType() == Op.getValueType() &&
3950              "Unexpected setcc expansion!");
3951       return LHS;
3952     }
3953   }
3954 
3955   if (LHS.getValueType().isInteger()) {
3956     SDValue CCVal;
3957     SDValue Cmp =
3958         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3959 
3960     // Note that we inverted the condition above, so we reverse the order of
3961     // the true and false operands here.  This will allow the setcc to be
3962     // matched to a single CSINC instruction.
3963     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3964   }
3965 
3966   // Now we know we're dealing with FP values.
3967   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3968 
3969   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3970   // and do the comparison.
3971   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3972 
3973   AArch64CC::CondCode CC1, CC2;
3974   changeFPCCToAArch64CC(CC, CC1, CC2);
3975   if (CC2 == AArch64CC::AL) {
3976     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3977     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3978 
3979     // Note that we inverted the condition above, so we reverse the order of
3980     // the true and false operands here.  This will allow the setcc to be
3981     // matched to a single CSINC instruction.
3982     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3983   } else {
3984     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3985     // totally clean.  Some of them require two CSELs to implement.  As is in
3986     // this case, we emit the first CSEL and then emit a second using the output
3987     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3988 
3989     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3990     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3991     SDValue CS1 =
3992         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3993 
3994     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3995     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3996   }
3997 }
3998 
3999 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4000                                               SDValue RHS, SDValue TVal,
4001                                               SDValue FVal, const SDLoc &dl,
4002                                               SelectionDAG &DAG) const {
4003   // Handle f128 first, because it will result in a comparison of some RTLIB
4004   // call result against zero.
4005   if (LHS.getValueType() == MVT::f128) {
4006     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4007 
4008     // If softenSetCCOperands returned a scalar, we need to compare the result
4009     // against zero to select between true and false values.
4010     if (!RHS.getNode()) {
4011       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4012       CC = ISD::SETNE;
4013     }
4014   }
4015 
4016   // Also handle f16, for which we need to do a f32 comparison.
4017   if (LHS.getValueType() == MVT::f16) {
4018     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4019     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4020   }
4021 
4022   // Next, handle integers.
4023   if (LHS.getValueType().isInteger()) {
4024     assert((LHS.getValueType() == RHS.getValueType()) &&
4025            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4026 
4027     unsigned Opcode = AArch64ISD::CSEL;
4028 
4029     // If both the TVal and the FVal are constants, see if we can swap them in
4030     // order to for a CSINV or CSINC out of them.
4031     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4032     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4033 
4034     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4035       std::swap(TVal, FVal);
4036       std::swap(CTVal, CFVal);
4037       CC = ISD::getSetCCInverse(CC, true);
4038     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4039       std::swap(TVal, FVal);
4040       std::swap(CTVal, CFVal);
4041       CC = ISD::getSetCCInverse(CC, true);
4042     } else if (TVal.getOpcode() == ISD::XOR) {
4043       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4044       // with a CSINV rather than a CSEL.
4045       if (isAllOnesConstant(TVal.getOperand(1))) {
4046         std::swap(TVal, FVal);
4047         std::swap(CTVal, CFVal);
4048         CC = ISD::getSetCCInverse(CC, true);
4049       }
4050     } else if (TVal.getOpcode() == ISD::SUB) {
4051       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4052       // that we can match with a CSNEG rather than a CSEL.
4053       if (isNullConstant(TVal.getOperand(0))) {
4054         std::swap(TVal, FVal);
4055         std::swap(CTVal, CFVal);
4056         CC = ISD::getSetCCInverse(CC, true);
4057       }
4058     } else if (CTVal && CFVal) {
4059       const int64_t TrueVal = CTVal->getSExtValue();
4060       const int64_t FalseVal = CFVal->getSExtValue();
4061       bool Swap = false;
4062 
4063       // If both TVal and FVal are constants, see if FVal is the
4064       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4065       // instead of a CSEL in that case.
4066       if (TrueVal == ~FalseVal) {
4067         Opcode = AArch64ISD::CSINV;
4068       } else if (TrueVal == -FalseVal) {
4069         Opcode = AArch64ISD::CSNEG;
4070       } else if (TVal.getValueType() == MVT::i32) {
4071         // If our operands are only 32-bit wide, make sure we use 32-bit
4072         // arithmetic for the check whether we can use CSINC. This ensures that
4073         // the addition in the check will wrap around properly in case there is
4074         // an overflow (which would not be the case if we do the check with
4075         // 64-bit arithmetic).
4076         const uint32_t TrueVal32 = CTVal->getZExtValue();
4077         const uint32_t FalseVal32 = CFVal->getZExtValue();
4078 
4079         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4080           Opcode = AArch64ISD::CSINC;
4081 
4082           if (TrueVal32 > FalseVal32) {
4083             Swap = true;
4084           }
4085         }
4086         // 64-bit check whether we can use CSINC.
4087       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4088         Opcode = AArch64ISD::CSINC;
4089 
4090         if (TrueVal > FalseVal) {
4091           Swap = true;
4092         }
4093       }
4094 
4095       // Swap TVal and FVal if necessary.
4096       if (Swap) {
4097         std::swap(TVal, FVal);
4098         std::swap(CTVal, CFVal);
4099         CC = ISD::getSetCCInverse(CC, true);
4100       }
4101 
4102       if (Opcode != AArch64ISD::CSEL) {
4103         // Drop FVal since we can get its value by simply inverting/negating
4104         // TVal.
4105         FVal = TVal;
4106       }
4107     }
4108 
4109     // Avoid materializing a constant when possible by reusing a known value in
4110     // a register.  However, don't perform this optimization if the known value
4111     // is one, zero or negative one in the case of a CSEL.  We can always
4112     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4113     // FVal, respectively.
4114     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4115     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4116         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4117       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4118       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4119       // "a != C ? x : a" to avoid materializing C.
4120       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4121         TVal = LHS;
4122       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4123         FVal = LHS;
4124     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4125       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4126       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4127       // avoid materializing C.
4128       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4129       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4130         Opcode = AArch64ISD::CSINV;
4131         TVal = LHS;
4132         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4133       }
4134     }
4135 
4136     SDValue CCVal;
4137     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4138 
4139     EVT VT = TVal.getValueType();
4140     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4141   }
4142 
4143   // Now we know we're dealing with FP values.
4144   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4145   assert(LHS.getValueType() == RHS.getValueType());
4146   EVT VT = TVal.getValueType();
4147   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4148 
4149   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4150   // clean.  Some of them require two CSELs to implement.
4151   AArch64CC::CondCode CC1, CC2;
4152   changeFPCCToAArch64CC(CC, CC1, CC2);
4153 
4154   if (DAG.getTarget().Options.UnsafeFPMath) {
4155     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4156     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4157     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4158     if (RHSVal && RHSVal->isZero()) {
4159       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4160       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4161 
4162       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4163           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4164         TVal = LHS;
4165       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4166                CFVal && CFVal->isZero() &&
4167                FVal.getValueType() == LHS.getValueType())
4168         FVal = LHS;
4169     }
4170   }
4171 
4172   // Emit first, and possibly only, CSEL.
4173   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4174   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4175 
4176   // If we need a second CSEL, emit it, using the output of the first as the
4177   // RHS.  We're effectively OR'ing the two CC's together.
4178   if (CC2 != AArch64CC::AL) {
4179     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4180     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4181   }
4182 
4183   // Otherwise, return the output of the first CSEL.
4184   return CS1;
4185 }
4186 
4187 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4188                                               SelectionDAG &DAG) const {
4189   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4190   SDValue LHS = Op.getOperand(0);
4191   SDValue RHS = Op.getOperand(1);
4192   SDValue TVal = Op.getOperand(2);
4193   SDValue FVal = Op.getOperand(3);
4194   SDLoc DL(Op);
4195   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4196 }
4197 
4198 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4199                                            SelectionDAG &DAG) const {
4200   SDValue CCVal = Op->getOperand(0);
4201   SDValue TVal = Op->getOperand(1);
4202   SDValue FVal = Op->getOperand(2);
4203   SDLoc DL(Op);
4204 
4205   unsigned Opc = CCVal.getOpcode();
4206   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4207   // instruction.
4208   if (CCVal.getResNo() == 1 &&
4209       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4210        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4211     // Only lower legal XALUO ops.
4212     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4213       return SDValue();
4214 
4215     AArch64CC::CondCode OFCC;
4216     SDValue Value, Overflow;
4217     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4218     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4219 
4220     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4221                        CCVal, Overflow);
4222   }
4223 
4224   // Lower it the same way as we would lower a SELECT_CC node.
4225   ISD::CondCode CC;
4226   SDValue LHS, RHS;
4227   if (CCVal.getOpcode() == ISD::SETCC) {
4228     LHS = CCVal.getOperand(0);
4229     RHS = CCVal.getOperand(1);
4230     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4231   } else {
4232     LHS = CCVal;
4233     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4234     CC = ISD::SETNE;
4235   }
4236   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4237 }
4238 
4239 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4240                                               SelectionDAG &DAG) const {
4241   // Jump table entries as PC relative offsets. No additional tweaking
4242   // is necessary here. Just get the address of the jump table.
4243   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4244   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4245   SDLoc DL(Op);
4246 
4247   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4248       !Subtarget->isTargetMachO()) {
4249     const unsigned char MO_NC = AArch64II::MO_NC;
4250     return DAG.getNode(
4251         AArch64ISD::WrapperLarge, DL, PtrVT,
4252         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4253         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4254         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4255         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4256                                AArch64II::MO_G0 | MO_NC));
4257   }
4258 
4259   SDValue Hi =
4260       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4261   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4262                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4263   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4264   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4265 }
4266 
4267 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4268                                                  SelectionDAG &DAG) const {
4269   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4270   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4271   SDLoc DL(Op);
4272 
4273   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4274     // Use the GOT for the large code model on iOS.
4275     if (Subtarget->isTargetMachO()) {
4276       SDValue GotAddr = DAG.getTargetConstantPool(
4277           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4278           AArch64II::MO_GOT);
4279       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4280     }
4281 
4282     const unsigned char MO_NC = AArch64II::MO_NC;
4283     return DAG.getNode(
4284         AArch64ISD::WrapperLarge, DL, PtrVT,
4285         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4286                                   CP->getOffset(), AArch64II::MO_G3),
4287         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4288                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4289         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4290                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4291         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4292                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4293   } else {
4294     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4295     // ELF, the only valid one on Darwin.
4296     SDValue Hi =
4297         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4298                                   CP->getOffset(), AArch64II::MO_PAGE);
4299     SDValue Lo = DAG.getTargetConstantPool(
4300         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4301         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4302 
4303     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4304     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4305   }
4306 }
4307 
4308 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4309                                                SelectionDAG &DAG) const {
4310   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4311   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4312   SDLoc DL(Op);
4313   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4314       !Subtarget->isTargetMachO()) {
4315     const unsigned char MO_NC = AArch64II::MO_NC;
4316     return DAG.getNode(
4317         AArch64ISD::WrapperLarge, DL, PtrVT,
4318         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4319         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4320         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4321         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4322   } else {
4323     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4324     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4325                                                              AArch64II::MO_NC);
4326     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4327     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4328   }
4329 }
4330 
4331 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4332                                                  SelectionDAG &DAG) const {
4333   AArch64FunctionInfo *FuncInfo =
4334       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4335 
4336   SDLoc DL(Op);
4337   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4338                                  getPointerTy(DAG.getDataLayout()));
4339   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4340   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4341                       MachinePointerInfo(SV));
4342 }
4343 
4344 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4345                                                 SelectionDAG &DAG) const {
4346   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4347   // Standard, section B.3.
4348   MachineFunction &MF = DAG.getMachineFunction();
4349   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4350   auto PtrVT = getPointerTy(DAG.getDataLayout());
4351   SDLoc DL(Op);
4352 
4353   SDValue Chain = Op.getOperand(0);
4354   SDValue VAList = Op.getOperand(1);
4355   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4356   SmallVector<SDValue, 4> MemOps;
4357 
4358   // void *__stack at offset 0
4359   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4360   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4361                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4362 
4363   // void *__gr_top at offset 8
4364   int GPRSize = FuncInfo->getVarArgsGPRSize();
4365   if (GPRSize > 0) {
4366     SDValue GRTop, GRTopAddr;
4367 
4368     GRTopAddr =
4369         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4370 
4371     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4372     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4373                         DAG.getConstant(GPRSize, DL, PtrVT));
4374 
4375     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4376                                   MachinePointerInfo(SV, 8),
4377                                   /* Alignment = */ 8));
4378   }
4379 
4380   // void *__vr_top at offset 16
4381   int FPRSize = FuncInfo->getVarArgsFPRSize();
4382   if (FPRSize > 0) {
4383     SDValue VRTop, VRTopAddr;
4384     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4385                             DAG.getConstant(16, DL, PtrVT));
4386 
4387     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4388     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4389                         DAG.getConstant(FPRSize, DL, PtrVT));
4390 
4391     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4392                                   MachinePointerInfo(SV, 16),
4393                                   /* Alignment = */ 8));
4394   }
4395 
4396   // int __gr_offs at offset 24
4397   SDValue GROffsAddr =
4398       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4399   MemOps.push_back(DAG.getStore(
4400       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4401       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4402 
4403   // int __vr_offs at offset 28
4404   SDValue VROffsAddr =
4405       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4406   MemOps.push_back(DAG.getStore(
4407       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4408       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4409 
4410   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4411 }
4412 
4413 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4414                                             SelectionDAG &DAG) const {
4415   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4416                                      : LowerAAPCS_VASTART(Op, DAG);
4417 }
4418 
4419 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4420                                            SelectionDAG &DAG) const {
4421   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4422   // pointer.
4423   SDLoc DL(Op);
4424   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4425   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4426   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4427 
4428   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4429                        Op.getOperand(2),
4430                        DAG.getConstant(VaListSize, DL, MVT::i32),
4431                        8, false, false, false, MachinePointerInfo(DestSV),
4432                        MachinePointerInfo(SrcSV));
4433 }
4434 
4435 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4436   assert(Subtarget->isTargetDarwin() &&
4437          "automatic va_arg instruction only works on Darwin");
4438 
4439   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4440   EVT VT = Op.getValueType();
4441   SDLoc DL(Op);
4442   SDValue Chain = Op.getOperand(0);
4443   SDValue Addr = Op.getOperand(1);
4444   unsigned Align = Op.getConstantOperandVal(3);
4445   auto PtrVT = getPointerTy(DAG.getDataLayout());
4446 
4447   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4448   Chain = VAList.getValue(1);
4449 
4450   if (Align > 8) {
4451     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4452     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4453                          DAG.getConstant(Align - 1, DL, PtrVT));
4454     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4455                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4456   }
4457 
4458   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4459   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4460 
4461   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4462   // up to 64 bits.  At the very least, we have to increase the striding of the
4463   // vaargs list to match this, and for FP values we need to introduce
4464   // FP_ROUND nodes as well.
4465   if (VT.isInteger() && !VT.isVector())
4466     ArgSize = 8;
4467   bool NeedFPTrunc = false;
4468   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4469     ArgSize = 8;
4470     NeedFPTrunc = true;
4471   }
4472 
4473   // Increment the pointer, VAList, to the next vaarg
4474   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4475                                DAG.getConstant(ArgSize, DL, PtrVT));
4476   // Store the incremented VAList to the legalized pointer
4477   SDValue APStore =
4478       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4479 
4480   // Load the actual argument out of the pointer VAList
4481   if (NeedFPTrunc) {
4482     // Load the value as an f64.
4483     SDValue WideFP =
4484         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4485     // Round the value down to an f32.
4486     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4487                                    DAG.getIntPtrConstant(1, DL));
4488     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4489     // Merge the rounded value with the chain output of the load.
4490     return DAG.getMergeValues(Ops, DL);
4491   }
4492 
4493   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4494 }
4495 
4496 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4497                                               SelectionDAG &DAG) const {
4498   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4499   MFI.setFrameAddressIsTaken(true);
4500 
4501   EVT VT = Op.getValueType();
4502   SDLoc DL(Op);
4503   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4504   SDValue FrameAddr =
4505       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4506   while (Depth--)
4507     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4508                             MachinePointerInfo());
4509   return FrameAddr;
4510 }
4511 
4512 // FIXME? Maybe this could be a TableGen attribute on some registers and
4513 // this table could be generated automatically from RegInfo.
4514 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4515                                                   SelectionDAG &DAG) const {
4516   unsigned Reg = StringSwitch<unsigned>(RegName)
4517                        .Case("sp", AArch64::SP)
4518                        .Default(0);
4519   if (Reg)
4520     return Reg;
4521   report_fatal_error(Twine("Invalid register name \""
4522                               + StringRef(RegName)  + "\"."));
4523 }
4524 
4525 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4526                                                SelectionDAG &DAG) const {
4527   MachineFunction &MF = DAG.getMachineFunction();
4528   MachineFrameInfo &MFI = MF.getFrameInfo();
4529   MFI.setReturnAddressIsTaken(true);
4530 
4531   EVT VT = Op.getValueType();
4532   SDLoc DL(Op);
4533   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4534   if (Depth) {
4535     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4536     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4537     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4538                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4539                        MachinePointerInfo());
4540   }
4541 
4542   // Return LR, which contains the return address. Mark it an implicit live-in.
4543   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4544   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4545 }
4546 
4547 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4548 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4549 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4550                                                     SelectionDAG &DAG) const {
4551   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4552   EVT VT = Op.getValueType();
4553   unsigned VTBits = VT.getSizeInBits();
4554   SDLoc dl(Op);
4555   SDValue ShOpLo = Op.getOperand(0);
4556   SDValue ShOpHi = Op.getOperand(1);
4557   SDValue ShAmt = Op.getOperand(2);
4558   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4559 
4560   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4561 
4562   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4563                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4564   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4565 
4566   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4567   // is "undef". We wanted 0, so CSEL it directly.
4568   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4569                                ISD::SETEQ, dl, DAG);
4570   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4571   HiBitsForLo =
4572       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4573                   HiBitsForLo, CCVal, Cmp);
4574 
4575   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4576                                    DAG.getConstant(VTBits, dl, MVT::i64));
4577 
4578   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4579   SDValue LoForNormalShift =
4580       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4581 
4582   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4583                        dl, DAG);
4584   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4585   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4586   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4587                            LoForNormalShift, CCVal, Cmp);
4588 
4589   // AArch64 shifts larger than the register width are wrapped rather than
4590   // clamped, so we can't just emit "hi >> x".
4591   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4592   SDValue HiForBigShift =
4593       Opc == ISD::SRA
4594           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4595                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4596           : DAG.getConstant(0, dl, VT);
4597   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4598                            HiForNormalShift, CCVal, Cmp);
4599 
4600   SDValue Ops[2] = { Lo, Hi };
4601   return DAG.getMergeValues(Ops, dl);
4602 }
4603 
4604 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4605 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4606 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4607                                                    SelectionDAG &DAG) const {
4608   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4609   EVT VT = Op.getValueType();
4610   unsigned VTBits = VT.getSizeInBits();
4611   SDLoc dl(Op);
4612   SDValue ShOpLo = Op.getOperand(0);
4613   SDValue ShOpHi = Op.getOperand(1);
4614   SDValue ShAmt = Op.getOperand(2);
4615 
4616   assert(Op.getOpcode() == ISD::SHL_PARTS);
4617   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4618                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4619   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4620 
4621   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4622   // is "undef". We wanted 0, so CSEL it directly.
4623   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4624                                ISD::SETEQ, dl, DAG);
4625   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4626   LoBitsForHi =
4627       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4628                   LoBitsForHi, CCVal, Cmp);
4629 
4630   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4631                                    DAG.getConstant(VTBits, dl, MVT::i64));
4632   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4633   SDValue HiForNormalShift =
4634       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4635 
4636   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4637 
4638   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4639                        dl, DAG);
4640   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4641   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4642                            HiForNormalShift, CCVal, Cmp);
4643 
4644   // AArch64 shifts of larger than register sizes are wrapped rather than
4645   // clamped, so we can't just emit "lo << a" if a is too big.
4646   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4647   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4648   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4649                            LoForNormalShift, CCVal, Cmp);
4650 
4651   SDValue Ops[2] = { Lo, Hi };
4652   return DAG.getMergeValues(Ops, dl);
4653 }
4654 
4655 bool AArch64TargetLowering::isOffsetFoldingLegal(
4656     const GlobalAddressSDNode *GA) const {
4657   // The AArch64 target doesn't support folding offsets into global addresses.
4658   return false;
4659 }
4660 
4661 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4662   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4663   // FIXME: We should be able to handle f128 as well with a clever lowering.
4664   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4665     return true;
4666 
4667   if (VT == MVT::f64)
4668     return AArch64_AM::getFP64Imm(Imm) != -1;
4669   else if (VT == MVT::f32)
4670     return AArch64_AM::getFP32Imm(Imm) != -1;
4671   return false;
4672 }
4673 
4674 //===----------------------------------------------------------------------===//
4675 //                          AArch64 Optimization Hooks
4676 //===----------------------------------------------------------------------===//
4677 
4678 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4679                            SDValue Operand, SelectionDAG &DAG,
4680                            int &ExtraSteps) {
4681   EVT VT = Operand.getValueType();
4682   if (ST->hasNEON() &&
4683       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4684        VT == MVT::f32 || VT == MVT::v1f32 ||
4685        VT == MVT::v2f32 || VT == MVT::v4f32)) {
4686     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4687       // For the reciprocal estimates, convergence is quadratic, so the number
4688       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
4689       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
4690       // the result for float (23 mantissa bits) is 2 and for double (52
4691       // mantissa bits) is 3.
4692       ExtraSteps = VT == MVT::f64 ? 3 : 2;
4693 
4694     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4695   }
4696 
4697   return SDValue();
4698 }
4699 
4700 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4701                                                SelectionDAG &DAG, int Enabled,
4702                                                int &ExtraSteps,
4703                                                bool &UseOneConst,
4704                                                bool Reciprocal) const {
4705   if (Enabled == ReciprocalEstimate::Enabled ||
4706       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4707     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4708                                        DAG, ExtraSteps)) {
4709       SDLoc DL(Operand);
4710       EVT VT = Operand.getValueType();
4711 
4712       SDNodeFlags Flags;
4713       Flags.setUnsafeAlgebra(true);
4714 
4715       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4716       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4717       for (int i = ExtraSteps; i > 0; --i) {
4718         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4719                                    &Flags);
4720         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4721         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4722       }
4723 
4724       if (!Reciprocal) {
4725         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4726                                       VT);
4727         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4728         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4729 
4730         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4731         // Correct the result if the operand is 0.0.
4732         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4733                                VT, Eq, Operand, Estimate);
4734       }
4735 
4736       ExtraSteps = 0;
4737       return Estimate;
4738     }
4739 
4740   return SDValue();
4741 }
4742 
4743 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4744                                                 SelectionDAG &DAG, int Enabled,
4745                                                 int &ExtraSteps) const {
4746   if (Enabled == ReciprocalEstimate::Enabled)
4747     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4748                                        DAG, ExtraSteps)) {
4749       SDLoc DL(Operand);
4750       EVT VT = Operand.getValueType();
4751 
4752       SDNodeFlags Flags;
4753       Flags.setUnsafeAlgebra(true);
4754 
4755       // Newton reciprocal iteration: E * (2 - X * E)
4756       // AArch64 reciprocal iteration instruction: (2 - M * N)
4757       for (int i = ExtraSteps; i > 0; --i) {
4758         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4759                                    Estimate, &Flags);
4760         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4761       }
4762 
4763       ExtraSteps = 0;
4764       return Estimate;
4765     }
4766 
4767   return SDValue();
4768 }
4769 
4770 //===----------------------------------------------------------------------===//
4771 //                          AArch64 Inline Assembly Support
4772 //===----------------------------------------------------------------------===//
4773 
4774 // Table of Constraints
4775 // TODO: This is the current set of constraints supported by ARM for the
4776 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4777 //
4778 // r - A general register
4779 // w - An FP/SIMD register of some size in the range v0-v31
4780 // x - An FP/SIMD register of some size in the range v0-v15
4781 // I - Constant that can be used with an ADD instruction
4782 // J - Constant that can be used with a SUB instruction
4783 // K - Constant that can be used with a 32-bit logical instruction
4784 // L - Constant that can be used with a 64-bit logical instruction
4785 // M - Constant that can be used as a 32-bit MOV immediate
4786 // N - Constant that can be used as a 64-bit MOV immediate
4787 // Q - A memory reference with base register and no offset
4788 // S - A symbolic address
4789 // Y - Floating point constant zero
4790 // Z - Integer constant zero
4791 //
4792 //   Note that general register operands will be output using their 64-bit x
4793 // register name, whatever the size of the variable, unless the asm operand
4794 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4795 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4796 // %q modifier.
4797 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4798   // At this point, we have to lower this constraint to something else, so we
4799   // lower it to an "r" or "w". However, by doing this we will force the result
4800   // to be in register, while the X constraint is much more permissive.
4801   //
4802   // Although we are correct (we are free to emit anything, without
4803   // constraints), we might break use cases that would expect us to be more
4804   // efficient and emit something else.
4805   if (!Subtarget->hasFPARMv8())
4806     return "r";
4807 
4808   if (ConstraintVT.isFloatingPoint())
4809     return "w";
4810 
4811   if (ConstraintVT.isVector() &&
4812      (ConstraintVT.getSizeInBits() == 64 ||
4813       ConstraintVT.getSizeInBits() == 128))
4814     return "w";
4815 
4816   return "r";
4817 }
4818 
4819 /// getConstraintType - Given a constraint letter, return the type of
4820 /// constraint it is for this target.
4821 AArch64TargetLowering::ConstraintType
4822 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4823   if (Constraint.size() == 1) {
4824     switch (Constraint[0]) {
4825     default:
4826       break;
4827     case 'z':
4828       return C_Other;
4829     case 'x':
4830     case 'w':
4831       return C_RegisterClass;
4832     // An address with a single base register. Due to the way we
4833     // currently handle addresses it is the same as 'r'.
4834     case 'Q':
4835       return C_Memory;
4836     }
4837   }
4838   return TargetLowering::getConstraintType(Constraint);
4839 }
4840 
4841 /// Examine constraint type and operand type and determine a weight value.
4842 /// This object must already have been set up with the operand type
4843 /// and the current alternative constraint selected.
4844 TargetLowering::ConstraintWeight
4845 AArch64TargetLowering::getSingleConstraintMatchWeight(
4846     AsmOperandInfo &info, const char *constraint) const {
4847   ConstraintWeight weight = CW_Invalid;
4848   Value *CallOperandVal = info.CallOperandVal;
4849   // If we don't have a value, we can't do a match,
4850   // but allow it at the lowest weight.
4851   if (!CallOperandVal)
4852     return CW_Default;
4853   Type *type = CallOperandVal->getType();
4854   // Look at the constraint type.
4855   switch (*constraint) {
4856   default:
4857     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4858     break;
4859   case 'x':
4860   case 'w':
4861     if (type->isFloatingPointTy() || type->isVectorTy())
4862       weight = CW_Register;
4863     break;
4864   case 'z':
4865     weight = CW_Constant;
4866     break;
4867   }
4868   return weight;
4869 }
4870 
4871 std::pair<unsigned, const TargetRegisterClass *>
4872 AArch64TargetLowering::getRegForInlineAsmConstraint(
4873     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4874   if (Constraint.size() == 1) {
4875     switch (Constraint[0]) {
4876     case 'r':
4877       if (VT.getSizeInBits() == 64)
4878         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4879       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4880     case 'w':
4881       if (VT.getSizeInBits() == 16)
4882         return std::make_pair(0U, &AArch64::FPR16RegClass);
4883       if (VT.getSizeInBits() == 32)
4884         return std::make_pair(0U, &AArch64::FPR32RegClass);
4885       if (VT.getSizeInBits() == 64)
4886         return std::make_pair(0U, &AArch64::FPR64RegClass);
4887       if (VT.getSizeInBits() == 128)
4888         return std::make_pair(0U, &AArch64::FPR128RegClass);
4889       break;
4890     // The instructions that this constraint is designed for can
4891     // only take 128-bit registers so just use that regclass.
4892     case 'x':
4893       if (VT.getSizeInBits() == 128)
4894         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4895       break;
4896     }
4897   }
4898   if (StringRef("{cc}").equals_lower(Constraint))
4899     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4900 
4901   // Use the default implementation in TargetLowering to convert the register
4902   // constraint into a member of a register class.
4903   std::pair<unsigned, const TargetRegisterClass *> Res;
4904   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4905 
4906   // Not found as a standard register?
4907   if (!Res.second) {
4908     unsigned Size = Constraint.size();
4909     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4910         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4911       int RegNo;
4912       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4913       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4914         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4915         // By default we'll emit v0-v31 for this unless there's a modifier where
4916         // we'll emit the correct register as well.
4917         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4918           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4919           Res.second = &AArch64::FPR64RegClass;
4920         } else {
4921           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4922           Res.second = &AArch64::FPR128RegClass;
4923         }
4924       }
4925     }
4926   }
4927 
4928   return Res;
4929 }
4930 
4931 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4932 /// vector.  If it is invalid, don't add anything to Ops.
4933 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4934     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4935     SelectionDAG &DAG) const {
4936   SDValue Result;
4937 
4938   // Currently only support length 1 constraints.
4939   if (Constraint.length() != 1)
4940     return;
4941 
4942   char ConstraintLetter = Constraint[0];
4943   switch (ConstraintLetter) {
4944   default:
4945     break;
4946 
4947   // This set of constraints deal with valid constants for various instructions.
4948   // Validate and return a target constant for them if we can.
4949   case 'z': {
4950     // 'z' maps to xzr or wzr so it needs an input of 0.
4951     if (!isNullConstant(Op))
4952       return;
4953 
4954     if (Op.getValueType() == MVT::i64)
4955       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4956     else
4957       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4958     break;
4959   }
4960 
4961   case 'I':
4962   case 'J':
4963   case 'K':
4964   case 'L':
4965   case 'M':
4966   case 'N':
4967     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4968     if (!C)
4969       return;
4970 
4971     // Grab the value and do some validation.
4972     uint64_t CVal = C->getZExtValue();
4973     switch (ConstraintLetter) {
4974     // The I constraint applies only to simple ADD or SUB immediate operands:
4975     // i.e. 0 to 4095 with optional shift by 12
4976     // The J constraint applies only to ADD or SUB immediates that would be
4977     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4978     // instruction [or vice versa], in other words -1 to -4095 with optional
4979     // left shift by 12.
4980     case 'I':
4981       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4982         break;
4983       return;
4984     case 'J': {
4985       uint64_t NVal = -C->getSExtValue();
4986       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4987         CVal = C->getSExtValue();
4988         break;
4989       }
4990       return;
4991     }
4992     // The K and L constraints apply *only* to logical immediates, including
4993     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4994     // been removed and MOV should be used). So these constraints have to
4995     // distinguish between bit patterns that are valid 32-bit or 64-bit
4996     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4997     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4998     // versa.
4999     case 'K':
5000       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5001         break;
5002       return;
5003     case 'L':
5004       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5005         break;
5006       return;
5007     // The M and N constraints are a superset of K and L respectively, for use
5008     // with the MOV (immediate) alias. As well as the logical immediates they
5009     // also match 32 or 64-bit immediates that can be loaded either using a
5010     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5011     // (M) or 64-bit 0x1234000000000000 (N) etc.
5012     // As a note some of this code is liberally stolen from the asm parser.
5013     case 'M': {
5014       if (!isUInt<32>(CVal))
5015         return;
5016       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5017         break;
5018       if ((CVal & 0xFFFF) == CVal)
5019         break;
5020       if ((CVal & 0xFFFF0000ULL) == CVal)
5021         break;
5022       uint64_t NCVal = ~(uint32_t)CVal;
5023       if ((NCVal & 0xFFFFULL) == NCVal)
5024         break;
5025       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5026         break;
5027       return;
5028     }
5029     case 'N': {
5030       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5031         break;
5032       if ((CVal & 0xFFFFULL) == CVal)
5033         break;
5034       if ((CVal & 0xFFFF0000ULL) == CVal)
5035         break;
5036       if ((CVal & 0xFFFF00000000ULL) == CVal)
5037         break;
5038       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5039         break;
5040       uint64_t NCVal = ~CVal;
5041       if ((NCVal & 0xFFFFULL) == NCVal)
5042         break;
5043       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5044         break;
5045       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5046         break;
5047       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5048         break;
5049       return;
5050     }
5051     default:
5052       return;
5053     }
5054 
5055     // All assembler immediates are 64-bit integers.
5056     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5057     break;
5058   }
5059 
5060   if (Result.getNode()) {
5061     Ops.push_back(Result);
5062     return;
5063   }
5064 
5065   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5066 }
5067 
5068 //===----------------------------------------------------------------------===//
5069 //                     AArch64 Advanced SIMD Support
5070 //===----------------------------------------------------------------------===//
5071 
5072 /// WidenVector - Given a value in the V64 register class, produce the
5073 /// equivalent value in the V128 register class.
5074 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5075   EVT VT = V64Reg.getValueType();
5076   unsigned NarrowSize = VT.getVectorNumElements();
5077   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5078   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5079   SDLoc DL(V64Reg);
5080 
5081   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5082                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5083 }
5084 
5085 /// getExtFactor - Determine the adjustment factor for the position when
5086 /// generating an "extract from vector registers" instruction.
5087 static unsigned getExtFactor(SDValue &V) {
5088   EVT EltType = V.getValueType().getVectorElementType();
5089   return EltType.getSizeInBits() / 8;
5090 }
5091 
5092 /// NarrowVector - Given a value in the V128 register class, produce the
5093 /// equivalent value in the V64 register class.
5094 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5095   EVT VT = V128Reg.getValueType();
5096   unsigned WideSize = VT.getVectorNumElements();
5097   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5098   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5099   SDLoc DL(V128Reg);
5100 
5101   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5102 }
5103 
5104 // Gather data to see if the operation can be modelled as a
5105 // shuffle in combination with VEXTs.
5106 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5107                                                   SelectionDAG &DAG) const {
5108   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5109   SDLoc dl(Op);
5110   EVT VT = Op.getValueType();
5111   unsigned NumElts = VT.getVectorNumElements();
5112 
5113   struct ShuffleSourceInfo {
5114     SDValue Vec;
5115     unsigned MinElt;
5116     unsigned MaxElt;
5117 
5118     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5119     // be compatible with the shuffle we intend to construct. As a result
5120     // ShuffleVec will be some sliding window into the original Vec.
5121     SDValue ShuffleVec;
5122 
5123     // Code should guarantee that element i in Vec starts at element "WindowBase
5124     // + i * WindowScale in ShuffleVec".
5125     int WindowBase;
5126     int WindowScale;
5127 
5128     ShuffleSourceInfo(SDValue Vec)
5129       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5130           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5131 
5132     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5133   };
5134 
5135   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5136   // node.
5137   SmallVector<ShuffleSourceInfo, 2> Sources;
5138   for (unsigned i = 0; i < NumElts; ++i) {
5139     SDValue V = Op.getOperand(i);
5140     if (V.isUndef())
5141       continue;
5142     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5143              !isa<ConstantSDNode>(V.getOperand(1))) {
5144       // A shuffle can only come from building a vector from various
5145       // elements of other vectors, provided their indices are constant.
5146       return SDValue();
5147     }
5148 
5149     // Add this element source to the list if it's not already there.
5150     SDValue SourceVec = V.getOperand(0);
5151     auto Source = find(Sources, SourceVec);
5152     if (Source == Sources.end())
5153       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5154 
5155     // Update the minimum and maximum lane number seen.
5156     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5157     Source->MinElt = std::min(Source->MinElt, EltNo);
5158     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5159   }
5160 
5161   // Currently only do something sane when at most two source vectors
5162   // are involved.
5163   if (Sources.size() > 2)
5164     return SDValue();
5165 
5166   // Find out the smallest element size among result and two sources, and use
5167   // it as element size to build the shuffle_vector.
5168   EVT SmallestEltTy = VT.getVectorElementType();
5169   for (auto &Source : Sources) {
5170     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5171     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5172       SmallestEltTy = SrcEltTy;
5173     }
5174   }
5175   unsigned ResMultiplier =
5176       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5177   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5178   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5179 
5180   // If the source vector is too wide or too narrow, we may nevertheless be able
5181   // to construct a compatible shuffle either by concatenating it with UNDEF or
5182   // extracting a suitable range of elements.
5183   for (auto &Src : Sources) {
5184     EVT SrcVT = Src.ShuffleVec.getValueType();
5185 
5186     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5187       continue;
5188 
5189     // This stage of the search produces a source with the same element type as
5190     // the original, but with a total width matching the BUILD_VECTOR output.
5191     EVT EltVT = SrcVT.getVectorElementType();
5192     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5193     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5194 
5195     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5196       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5197       // We can pad out the smaller vector for free, so if it's part of a
5198       // shuffle...
5199       Src.ShuffleVec =
5200           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5201                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5202       continue;
5203     }
5204 
5205     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5206 
5207     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5208       // Span too large for a VEXT to cope
5209       return SDValue();
5210     }
5211 
5212     if (Src.MinElt >= NumSrcElts) {
5213       // The extraction can just take the second half
5214       Src.ShuffleVec =
5215           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5216                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5217       Src.WindowBase = -NumSrcElts;
5218     } else if (Src.MaxElt < NumSrcElts) {
5219       // The extraction can just take the first half
5220       Src.ShuffleVec =
5221           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5222                       DAG.getConstant(0, dl, MVT::i64));
5223     } else {
5224       // An actual VEXT is needed
5225       SDValue VEXTSrc1 =
5226           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5227                       DAG.getConstant(0, dl, MVT::i64));
5228       SDValue VEXTSrc2 =
5229           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5230                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5231       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5232 
5233       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5234                                    VEXTSrc2,
5235                                    DAG.getConstant(Imm, dl, MVT::i32));
5236       Src.WindowBase = -Src.MinElt;
5237     }
5238   }
5239 
5240   // Another possible incompatibility occurs from the vector element types. We
5241   // can fix this by bitcasting the source vectors to the same type we intend
5242   // for the shuffle.
5243   for (auto &Src : Sources) {
5244     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5245     if (SrcEltTy == SmallestEltTy)
5246       continue;
5247     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5248     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5249     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5250     Src.WindowBase *= Src.WindowScale;
5251   }
5252 
5253   // Final sanity check before we try to actually produce a shuffle.
5254   DEBUG(
5255     for (auto Src : Sources)
5256       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5257   );
5258 
5259   // The stars all align, our next step is to produce the mask for the shuffle.
5260   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5261   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5262   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5263     SDValue Entry = Op.getOperand(i);
5264     if (Entry.isUndef())
5265       continue;
5266 
5267     auto Src = find(Sources, Entry.getOperand(0));
5268     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5269 
5270     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5271     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5272     // segment.
5273     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5274     int BitsDefined =
5275         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5276     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5277 
5278     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5279     // starting at the appropriate offset.
5280     int *LaneMask = &Mask[i * ResMultiplier];
5281 
5282     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5283     ExtractBase += NumElts * (Src - Sources.begin());
5284     for (int j = 0; j < LanesDefined; ++j)
5285       LaneMask[j] = ExtractBase + j;
5286   }
5287 
5288   // Final check before we try to produce nonsense...
5289   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5290     return SDValue();
5291 
5292   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5293   for (unsigned i = 0; i < Sources.size(); ++i)
5294     ShuffleOps[i] = Sources[i].ShuffleVec;
5295 
5296   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5297                                          ShuffleOps[1], Mask);
5298   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5299 }
5300 
5301 // check if an EXT instruction can handle the shuffle mask when the
5302 // vector sources of the shuffle are the same.
5303 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5304   unsigned NumElts = VT.getVectorNumElements();
5305 
5306   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5307   if (M[0] < 0)
5308     return false;
5309 
5310   Imm = M[0];
5311 
5312   // If this is a VEXT shuffle, the immediate value is the index of the first
5313   // element.  The other shuffle indices must be the successive elements after
5314   // the first one.
5315   unsigned ExpectedElt = Imm;
5316   for (unsigned i = 1; i < NumElts; ++i) {
5317     // Increment the expected index.  If it wraps around, just follow it
5318     // back to index zero and keep going.
5319     ++ExpectedElt;
5320     if (ExpectedElt == NumElts)
5321       ExpectedElt = 0;
5322 
5323     if (M[i] < 0)
5324       continue; // ignore UNDEF indices
5325     if (ExpectedElt != static_cast<unsigned>(M[i]))
5326       return false;
5327   }
5328 
5329   return true;
5330 }
5331 
5332 // check if an EXT instruction can handle the shuffle mask when the
5333 // vector sources of the shuffle are different.
5334 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5335                       unsigned &Imm) {
5336   // Look for the first non-undef element.
5337   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5338 
5339   // Benefit form APInt to handle overflow when calculating expected element.
5340   unsigned NumElts = VT.getVectorNumElements();
5341   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5342   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5343   // The following shuffle indices must be the successive elements after the
5344   // first real element.
5345   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5346       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5347   if (FirstWrongElt != M.end())
5348     return false;
5349 
5350   // The index of an EXT is the first element if it is not UNDEF.
5351   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5352   // value of the first element.  E.g.
5353   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5354   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5355   // ExpectedElt is the last mask index plus 1.
5356   Imm = ExpectedElt.getZExtValue();
5357 
5358   // There are two difference cases requiring to reverse input vectors.
5359   // For example, for vector <4 x i32> we have the following cases,
5360   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5361   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5362   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5363   // to reverse two input vectors.
5364   if (Imm < NumElts)
5365     ReverseEXT = true;
5366   else
5367     Imm -= NumElts;
5368 
5369   return true;
5370 }
5371 
5372 /// isREVMask - Check if a vector shuffle corresponds to a REV
5373 /// instruction with the specified blocksize.  (The order of the elements
5374 /// within each block of the vector is reversed.)
5375 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5376   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5377          "Only possible block sizes for REV are: 16, 32, 64");
5378 
5379   unsigned EltSz = VT.getScalarSizeInBits();
5380   if (EltSz == 64)
5381     return false;
5382 
5383   unsigned NumElts = VT.getVectorNumElements();
5384   unsigned BlockElts = M[0] + 1;
5385   // If the first shuffle index is UNDEF, be optimistic.
5386   if (M[0] < 0)
5387     BlockElts = BlockSize / EltSz;
5388 
5389   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5390     return false;
5391 
5392   for (unsigned i = 0; i < NumElts; ++i) {
5393     if (M[i] < 0)
5394       continue; // ignore UNDEF indices
5395     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5396       return false;
5397   }
5398 
5399   return true;
5400 }
5401 
5402 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5403   unsigned NumElts = VT.getVectorNumElements();
5404   WhichResult = (M[0] == 0 ? 0 : 1);
5405   unsigned Idx = WhichResult * NumElts / 2;
5406   for (unsigned i = 0; i != NumElts; i += 2) {
5407     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5408         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5409       return false;
5410     Idx += 1;
5411   }
5412 
5413   return true;
5414 }
5415 
5416 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5417   unsigned NumElts = VT.getVectorNumElements();
5418   WhichResult = (M[0] == 0 ? 0 : 1);
5419   for (unsigned i = 0; i != NumElts; ++i) {
5420     if (M[i] < 0)
5421       continue; // ignore UNDEF indices
5422     if ((unsigned)M[i] != 2 * i + WhichResult)
5423       return false;
5424   }
5425 
5426   return true;
5427 }
5428 
5429 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5430   unsigned NumElts = VT.getVectorNumElements();
5431   WhichResult = (M[0] == 0 ? 0 : 1);
5432   for (unsigned i = 0; i < NumElts; i += 2) {
5433     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5434         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5435       return false;
5436   }
5437   return true;
5438 }
5439 
5440 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5441 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5442 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5443 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5444   unsigned NumElts = VT.getVectorNumElements();
5445   WhichResult = (M[0] == 0 ? 0 : 1);
5446   unsigned Idx = WhichResult * NumElts / 2;
5447   for (unsigned i = 0; i != NumElts; i += 2) {
5448     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5449         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5450       return false;
5451     Idx += 1;
5452   }
5453 
5454   return true;
5455 }
5456 
5457 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5458 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5459 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5460 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5461   unsigned Half = VT.getVectorNumElements() / 2;
5462   WhichResult = (M[0] == 0 ? 0 : 1);
5463   for (unsigned j = 0; j != 2; ++j) {
5464     unsigned Idx = WhichResult;
5465     for (unsigned i = 0; i != Half; ++i) {
5466       int MIdx = M[i + j * Half];
5467       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5468         return false;
5469       Idx += 2;
5470     }
5471   }
5472 
5473   return true;
5474 }
5475 
5476 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5477 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5478 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5479 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5480   unsigned NumElts = VT.getVectorNumElements();
5481   WhichResult = (M[0] == 0 ? 0 : 1);
5482   for (unsigned i = 0; i < NumElts; i += 2) {
5483     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5484         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5485       return false;
5486   }
5487   return true;
5488 }
5489 
5490 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5491                       bool &DstIsLeft, int &Anomaly) {
5492   if (M.size() != static_cast<size_t>(NumInputElements))
5493     return false;
5494 
5495   int NumLHSMatch = 0, NumRHSMatch = 0;
5496   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5497 
5498   for (int i = 0; i < NumInputElements; ++i) {
5499     if (M[i] == -1) {
5500       ++NumLHSMatch;
5501       ++NumRHSMatch;
5502       continue;
5503     }
5504 
5505     if (M[i] == i)
5506       ++NumLHSMatch;
5507     else
5508       LastLHSMismatch = i;
5509 
5510     if (M[i] == i + NumInputElements)
5511       ++NumRHSMatch;
5512     else
5513       LastRHSMismatch = i;
5514   }
5515 
5516   if (NumLHSMatch == NumInputElements - 1) {
5517     DstIsLeft = true;
5518     Anomaly = LastLHSMismatch;
5519     return true;
5520   } else if (NumRHSMatch == NumInputElements - 1) {
5521     DstIsLeft = false;
5522     Anomaly = LastRHSMismatch;
5523     return true;
5524   }
5525 
5526   return false;
5527 }
5528 
5529 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5530   if (VT.getSizeInBits() != 128)
5531     return false;
5532 
5533   unsigned NumElts = VT.getVectorNumElements();
5534 
5535   for (int I = 0, E = NumElts / 2; I != E; I++) {
5536     if (Mask[I] != I)
5537       return false;
5538   }
5539 
5540   int Offset = NumElts / 2;
5541   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5542     if (Mask[I] != I + SplitLHS * Offset)
5543       return false;
5544   }
5545 
5546   return true;
5547 }
5548 
5549 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5550   SDLoc DL(Op);
5551   EVT VT = Op.getValueType();
5552   SDValue V0 = Op.getOperand(0);
5553   SDValue V1 = Op.getOperand(1);
5554   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5555 
5556   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5557       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5558     return SDValue();
5559 
5560   bool SplitV0 = V0.getValueSizeInBits() == 128;
5561 
5562   if (!isConcatMask(Mask, VT, SplitV0))
5563     return SDValue();
5564 
5565   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5566                                 VT.getVectorNumElements() / 2);
5567   if (SplitV0) {
5568     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5569                      DAG.getConstant(0, DL, MVT::i64));
5570   }
5571   if (V1.getValueSizeInBits() == 128) {
5572     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5573                      DAG.getConstant(0, DL, MVT::i64));
5574   }
5575   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5576 }
5577 
5578 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5579 /// the specified operations to build the shuffle.
5580 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5581                                       SDValue RHS, SelectionDAG &DAG,
5582                                       const SDLoc &dl) {
5583   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5584   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5585   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5586 
5587   enum {
5588     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5589     OP_VREV,
5590     OP_VDUP0,
5591     OP_VDUP1,
5592     OP_VDUP2,
5593     OP_VDUP3,
5594     OP_VEXT1,
5595     OP_VEXT2,
5596     OP_VEXT3,
5597     OP_VUZPL, // VUZP, left result
5598     OP_VUZPR, // VUZP, right result
5599     OP_VZIPL, // VZIP, left result
5600     OP_VZIPR, // VZIP, right result
5601     OP_VTRNL, // VTRN, left result
5602     OP_VTRNR  // VTRN, right result
5603   };
5604 
5605   if (OpNum == OP_COPY) {
5606     if (LHSID == (1 * 9 + 2) * 9 + 3)
5607       return LHS;
5608     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5609     return RHS;
5610   }
5611 
5612   SDValue OpLHS, OpRHS;
5613   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5614   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5615   EVT VT = OpLHS.getValueType();
5616 
5617   switch (OpNum) {
5618   default:
5619     llvm_unreachable("Unknown shuffle opcode!");
5620   case OP_VREV:
5621     // VREV divides the vector in half and swaps within the half.
5622     if (VT.getVectorElementType() == MVT::i32 ||
5623         VT.getVectorElementType() == MVT::f32)
5624       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5625     // vrev <4 x i16> -> REV32
5626     if (VT.getVectorElementType() == MVT::i16 ||
5627         VT.getVectorElementType() == MVT::f16)
5628       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5629     // vrev <4 x i8> -> REV16
5630     assert(VT.getVectorElementType() == MVT::i8);
5631     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5632   case OP_VDUP0:
5633   case OP_VDUP1:
5634   case OP_VDUP2:
5635   case OP_VDUP3: {
5636     EVT EltTy = VT.getVectorElementType();
5637     unsigned Opcode;
5638     if (EltTy == MVT::i8)
5639       Opcode = AArch64ISD::DUPLANE8;
5640     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5641       Opcode = AArch64ISD::DUPLANE16;
5642     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5643       Opcode = AArch64ISD::DUPLANE32;
5644     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5645       Opcode = AArch64ISD::DUPLANE64;
5646     else
5647       llvm_unreachable("Invalid vector element type?");
5648 
5649     if (VT.getSizeInBits() == 64)
5650       OpLHS = WidenVector(OpLHS, DAG);
5651     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5652     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5653   }
5654   case OP_VEXT1:
5655   case OP_VEXT2:
5656   case OP_VEXT3: {
5657     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5658     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5659                        DAG.getConstant(Imm, dl, MVT::i32));
5660   }
5661   case OP_VUZPL:
5662     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5663                        OpRHS);
5664   case OP_VUZPR:
5665     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5666                        OpRHS);
5667   case OP_VZIPL:
5668     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5669                        OpRHS);
5670   case OP_VZIPR:
5671     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5672                        OpRHS);
5673   case OP_VTRNL:
5674     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5675                        OpRHS);
5676   case OP_VTRNR:
5677     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5678                        OpRHS);
5679   }
5680 }
5681 
5682 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5683                            SelectionDAG &DAG) {
5684   // Check to see if we can use the TBL instruction.
5685   SDValue V1 = Op.getOperand(0);
5686   SDValue V2 = Op.getOperand(1);
5687   SDLoc DL(Op);
5688 
5689   EVT EltVT = Op.getValueType().getVectorElementType();
5690   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5691 
5692   SmallVector<SDValue, 8> TBLMask;
5693   for (int Val : ShuffleMask) {
5694     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5695       unsigned Offset = Byte + Val * BytesPerElt;
5696       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5697     }
5698   }
5699 
5700   MVT IndexVT = MVT::v8i8;
5701   unsigned IndexLen = 8;
5702   if (Op.getValueSizeInBits() == 128) {
5703     IndexVT = MVT::v16i8;
5704     IndexLen = 16;
5705   }
5706 
5707   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5708   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5709 
5710   SDValue Shuffle;
5711   if (V2.getNode()->isUndef()) {
5712     if (IndexLen == 8)
5713       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5714     Shuffle = DAG.getNode(
5715         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5716         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5717         DAG.getBuildVector(IndexVT, DL,
5718                            makeArrayRef(TBLMask.data(), IndexLen)));
5719   } else {
5720     if (IndexLen == 8) {
5721       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5722       Shuffle = DAG.getNode(
5723           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5724           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5725           DAG.getBuildVector(IndexVT, DL,
5726                              makeArrayRef(TBLMask.data(), IndexLen)));
5727     } else {
5728       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5729       // cannot currently represent the register constraints on the input
5730       // table registers.
5731       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5732       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5733       //                   IndexLen));
5734       Shuffle = DAG.getNode(
5735           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5736           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5737           V2Cst, DAG.getBuildVector(IndexVT, DL,
5738                                     makeArrayRef(TBLMask.data(), IndexLen)));
5739     }
5740   }
5741   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5742 }
5743 
5744 static unsigned getDUPLANEOp(EVT EltType) {
5745   if (EltType == MVT::i8)
5746     return AArch64ISD::DUPLANE8;
5747   if (EltType == MVT::i16 || EltType == MVT::f16)
5748     return AArch64ISD::DUPLANE16;
5749   if (EltType == MVT::i32 || EltType == MVT::f32)
5750     return AArch64ISD::DUPLANE32;
5751   if (EltType == MVT::i64 || EltType == MVT::f64)
5752     return AArch64ISD::DUPLANE64;
5753 
5754   llvm_unreachable("Invalid vector element type?");
5755 }
5756 
5757 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5758                                                    SelectionDAG &DAG) const {
5759   SDLoc dl(Op);
5760   EVT VT = Op.getValueType();
5761 
5762   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5763 
5764   // Convert shuffles that are directly supported on NEON to target-specific
5765   // DAG nodes, instead of keeping them as shuffles and matching them again
5766   // during code selection.  This is more efficient and avoids the possibility
5767   // of inconsistencies between legalization and selection.
5768   ArrayRef<int> ShuffleMask = SVN->getMask();
5769 
5770   SDValue V1 = Op.getOperand(0);
5771   SDValue V2 = Op.getOperand(1);
5772 
5773   if (SVN->isSplat()) {
5774     int Lane = SVN->getSplatIndex();
5775     // If this is undef splat, generate it via "just" vdup, if possible.
5776     if (Lane == -1)
5777       Lane = 0;
5778 
5779     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5780       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5781                          V1.getOperand(0));
5782     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5783     // constant. If so, we can just reference the lane's definition directly.
5784     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5785         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5786       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5787 
5788     // Otherwise, duplicate from the lane of the input vector.
5789     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5790 
5791     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5792     // to make a vector of the same size as this SHUFFLE. We can ignore the
5793     // extract entirely, and canonicalise the concat using WidenVector.
5794     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5795       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5796       V1 = V1.getOperand(0);
5797     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5798       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5799       Lane -= Idx * VT.getVectorNumElements() / 2;
5800       V1 = WidenVector(V1.getOperand(Idx), DAG);
5801     } else if (VT.getSizeInBits() == 64)
5802       V1 = WidenVector(V1, DAG);
5803 
5804     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5805   }
5806 
5807   if (isREVMask(ShuffleMask, VT, 64))
5808     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5809   if (isREVMask(ShuffleMask, VT, 32))
5810     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5811   if (isREVMask(ShuffleMask, VT, 16))
5812     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5813 
5814   bool ReverseEXT = false;
5815   unsigned Imm;
5816   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5817     if (ReverseEXT)
5818       std::swap(V1, V2);
5819     Imm *= getExtFactor(V1);
5820     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5821                        DAG.getConstant(Imm, dl, MVT::i32));
5822   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5823     Imm *= getExtFactor(V1);
5824     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5825                        DAG.getConstant(Imm, dl, MVT::i32));
5826   }
5827 
5828   unsigned WhichResult;
5829   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5830     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5831     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5832   }
5833   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5834     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5835     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5836   }
5837   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5838     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5839     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5840   }
5841 
5842   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5843     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5844     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5845   }
5846   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5847     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5848     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5849   }
5850   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5851     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5852     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5853   }
5854 
5855   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5856     return Concat;
5857 
5858   bool DstIsLeft;
5859   int Anomaly;
5860   int NumInputElements = V1.getValueType().getVectorNumElements();
5861   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5862     SDValue DstVec = DstIsLeft ? V1 : V2;
5863     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5864 
5865     SDValue SrcVec = V1;
5866     int SrcLane = ShuffleMask[Anomaly];
5867     if (SrcLane >= NumInputElements) {
5868       SrcVec = V2;
5869       SrcLane -= VT.getVectorNumElements();
5870     }
5871     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5872 
5873     EVT ScalarVT = VT.getVectorElementType();
5874 
5875     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5876       ScalarVT = MVT::i32;
5877 
5878     return DAG.getNode(
5879         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5880         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5881         DstLaneV);
5882   }
5883 
5884   // If the shuffle is not directly supported and it has 4 elements, use
5885   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5886   unsigned NumElts = VT.getVectorNumElements();
5887   if (NumElts == 4) {
5888     unsigned PFIndexes[4];
5889     for (unsigned i = 0; i != 4; ++i) {
5890       if (ShuffleMask[i] < 0)
5891         PFIndexes[i] = 8;
5892       else
5893         PFIndexes[i] = ShuffleMask[i];
5894     }
5895 
5896     // Compute the index in the perfect shuffle table.
5897     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5898                             PFIndexes[2] * 9 + PFIndexes[3];
5899     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5900     unsigned Cost = (PFEntry >> 30);
5901 
5902     if (Cost <= 4)
5903       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5904   }
5905 
5906   return GenerateTBL(Op, ShuffleMask, DAG);
5907 }
5908 
5909 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5910                                APInt &UndefBits) {
5911   EVT VT = BVN->getValueType(0);
5912   APInt SplatBits, SplatUndef;
5913   unsigned SplatBitSize;
5914   bool HasAnyUndefs;
5915   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5916     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5917 
5918     for (unsigned i = 0; i < NumSplats; ++i) {
5919       CnstBits <<= SplatBitSize;
5920       UndefBits <<= SplatBitSize;
5921       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5922       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5923     }
5924 
5925     return true;
5926   }
5927 
5928   return false;
5929 }
5930 
5931 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5932                                               SelectionDAG &DAG) const {
5933   BuildVectorSDNode *BVN =
5934       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5935   SDValue LHS = Op.getOperand(0);
5936   SDLoc dl(Op);
5937   EVT VT = Op.getValueType();
5938 
5939   if (!BVN)
5940     return Op;
5941 
5942   APInt CnstBits(VT.getSizeInBits(), 0);
5943   APInt UndefBits(VT.getSizeInBits(), 0);
5944   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5945     // We only have BIC vector immediate instruction, which is and-not.
5946     CnstBits = ~CnstBits;
5947 
5948     // We make use of a little bit of goto ickiness in order to avoid having to
5949     // duplicate the immediate matching logic for the undef toggled case.
5950     bool SecondTry = false;
5951   AttemptModImm:
5952 
5953     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5954       CnstBits = CnstBits.zextOrTrunc(64);
5955       uint64_t CnstVal = CnstBits.getZExtValue();
5956 
5957       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5958         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5959         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5960         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5961                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5962                                   DAG.getConstant(0, dl, MVT::i32));
5963         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5964       }
5965 
5966       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5967         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5968         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5969         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5970                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5971                                   DAG.getConstant(8, dl, MVT::i32));
5972         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5973       }
5974 
5975       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5976         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5977         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5978         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5979                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5980                                   DAG.getConstant(16, dl, MVT::i32));
5981         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5982       }
5983 
5984       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5985         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5986         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5987         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5988                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5989                                   DAG.getConstant(24, dl, MVT::i32));
5990         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5991       }
5992 
5993       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5994         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5995         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5996         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5997                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5998                                   DAG.getConstant(0, dl, MVT::i32));
5999         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6000       }
6001 
6002       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6003         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6004         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6005         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6006                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6007                                   DAG.getConstant(8, dl, MVT::i32));
6008         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6009       }
6010     }
6011 
6012     if (SecondTry)
6013       goto FailedModImm;
6014     SecondTry = true;
6015     CnstBits = ~UndefBits;
6016     goto AttemptModImm;
6017   }
6018 
6019 // We can always fall back to a non-immediate AND.
6020 FailedModImm:
6021   return Op;
6022 }
6023 
6024 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6025 // consists of only the same constant int value, returned in reference arg
6026 // ConstVal
6027 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6028                                      uint64_t &ConstVal) {
6029   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6030   if (!Bvec)
6031     return false;
6032   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6033   if (!FirstElt)
6034     return false;
6035   EVT VT = Bvec->getValueType(0);
6036   unsigned NumElts = VT.getVectorNumElements();
6037   for (unsigned i = 1; i < NumElts; ++i)
6038     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6039       return false;
6040   ConstVal = FirstElt->getZExtValue();
6041   return true;
6042 }
6043 
6044 static unsigned getIntrinsicID(const SDNode *N) {
6045   unsigned Opcode = N->getOpcode();
6046   switch (Opcode) {
6047   default:
6048     return Intrinsic::not_intrinsic;
6049   case ISD::INTRINSIC_WO_CHAIN: {
6050     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6051     if (IID < Intrinsic::num_intrinsics)
6052       return IID;
6053     return Intrinsic::not_intrinsic;
6054   }
6055   }
6056 }
6057 
6058 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6059 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6060 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6061 // Also, logical shift right -> sri, with the same structure.
6062 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6063   EVT VT = N->getValueType(0);
6064 
6065   if (!VT.isVector())
6066     return SDValue();
6067 
6068   SDLoc DL(N);
6069 
6070   // Is the first op an AND?
6071   const SDValue And = N->getOperand(0);
6072   if (And.getOpcode() != ISD::AND)
6073     return SDValue();
6074 
6075   // Is the second op an shl or lshr?
6076   SDValue Shift = N->getOperand(1);
6077   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6078   // or AArch64ISD::VLSHR vector, #shift
6079   unsigned ShiftOpc = Shift.getOpcode();
6080   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6081     return SDValue();
6082   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6083 
6084   // Is the shift amount constant?
6085   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6086   if (!C2node)
6087     return SDValue();
6088 
6089   // Is the and mask vector all constant?
6090   uint64_t C1;
6091   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6092     return SDValue();
6093 
6094   // Is C1 == ~C2, taking into account how much one can shift elements of a
6095   // particular size?
6096   uint64_t C2 = C2node->getZExtValue();
6097   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6098   if (C2 > ElemSizeInBits)
6099     return SDValue();
6100   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6101   if ((C1 & ElemMask) != (~C2 & ElemMask))
6102     return SDValue();
6103 
6104   SDValue X = And.getOperand(0);
6105   SDValue Y = Shift.getOperand(0);
6106 
6107   unsigned Intrin =
6108       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6109   SDValue ResultSLI =
6110       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6111                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6112                   Shift.getOperand(1));
6113 
6114   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6115   DEBUG(N->dump(&DAG));
6116   DEBUG(dbgs() << "into: \n");
6117   DEBUG(ResultSLI->dump(&DAG));
6118 
6119   ++NumShiftInserts;
6120   return ResultSLI;
6121 }
6122 
6123 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6124                                              SelectionDAG &DAG) const {
6125   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6126   if (EnableAArch64SlrGeneration) {
6127     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6128       return Res;
6129   }
6130 
6131   BuildVectorSDNode *BVN =
6132       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6133   SDValue LHS = Op.getOperand(1);
6134   SDLoc dl(Op);
6135   EVT VT = Op.getValueType();
6136 
6137   // OR commutes, so try swapping the operands.
6138   if (!BVN) {
6139     LHS = Op.getOperand(0);
6140     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6141   }
6142   if (!BVN)
6143     return Op;
6144 
6145   APInt CnstBits(VT.getSizeInBits(), 0);
6146   APInt UndefBits(VT.getSizeInBits(), 0);
6147   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6148     // We make use of a little bit of goto ickiness in order to avoid having to
6149     // duplicate the immediate matching logic for the undef toggled case.
6150     bool SecondTry = false;
6151   AttemptModImm:
6152 
6153     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6154       CnstBits = CnstBits.zextOrTrunc(64);
6155       uint64_t CnstVal = CnstBits.getZExtValue();
6156 
6157       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6158         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6159         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6160         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6161                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6162                                   DAG.getConstant(0, dl, MVT::i32));
6163         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6164       }
6165 
6166       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6167         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6168         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6169         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6170                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6171                                   DAG.getConstant(8, dl, MVT::i32));
6172         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6173       }
6174 
6175       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6176         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6177         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6178         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6179                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6180                                   DAG.getConstant(16, dl, MVT::i32));
6181         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6182       }
6183 
6184       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6185         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6186         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6187         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6188                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6189                                   DAG.getConstant(24, dl, MVT::i32));
6190         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6191       }
6192 
6193       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6194         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6195         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6196         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6197                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6198                                   DAG.getConstant(0, dl, MVT::i32));
6199         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6200       }
6201 
6202       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6203         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6204         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6205         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6206                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6207                                   DAG.getConstant(8, dl, MVT::i32));
6208         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6209       }
6210     }
6211 
6212     if (SecondTry)
6213       goto FailedModImm;
6214     SecondTry = true;
6215     CnstBits = UndefBits;
6216     goto AttemptModImm;
6217   }
6218 
6219 // We can always fall back to a non-immediate OR.
6220 FailedModImm:
6221   return Op;
6222 }
6223 
6224 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6225 // be truncated to fit element width.
6226 static SDValue NormalizeBuildVector(SDValue Op,
6227                                     SelectionDAG &DAG) {
6228   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6229   SDLoc dl(Op);
6230   EVT VT = Op.getValueType();
6231   EVT EltTy= VT.getVectorElementType();
6232 
6233   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6234     return Op;
6235 
6236   SmallVector<SDValue, 16> Ops;
6237   for (SDValue Lane : Op->ops()) {
6238     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6239       APInt LowBits(EltTy.getSizeInBits(),
6240                     CstLane->getZExtValue());
6241       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6242     }
6243     Ops.push_back(Lane);
6244   }
6245   return DAG.getBuildVector(VT, dl, Ops);
6246 }
6247 
6248 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6249                                                  SelectionDAG &DAG) const {
6250   SDLoc dl(Op);
6251   EVT VT = Op.getValueType();
6252   Op = NormalizeBuildVector(Op, DAG);
6253   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6254 
6255   APInt CnstBits(VT.getSizeInBits(), 0);
6256   APInt UndefBits(VT.getSizeInBits(), 0);
6257   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6258     // We make use of a little bit of goto ickiness in order to avoid having to
6259     // duplicate the immediate matching logic for the undef toggled case.
6260     bool SecondTry = false;
6261   AttemptModImm:
6262 
6263     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6264       CnstBits = CnstBits.zextOrTrunc(64);
6265       uint64_t CnstVal = CnstBits.getZExtValue();
6266 
6267       // Certain magic vector constants (used to express things like NOT
6268       // and NEG) are passed through unmodified.  This allows codegen patterns
6269       // for these operations to match.  Special-purpose patterns will lower
6270       // these immediates to MOVIs if it proves necessary.
6271       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6272         return Op;
6273 
6274       // The many faces of MOVI...
6275       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6276         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6277         if (VT.getSizeInBits() == 128) {
6278           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6279                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6280           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6281         }
6282 
6283         // Support the V64 version via subregister insertion.
6284         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6285                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6286         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6287       }
6288 
6289       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6290         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6291         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6292         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6293                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6294                                   DAG.getConstant(0, dl, MVT::i32));
6295         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6296       }
6297 
6298       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6299         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6300         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6301         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6302                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6303                                   DAG.getConstant(8, dl, MVT::i32));
6304         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6305       }
6306 
6307       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6308         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6309         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6310         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6311                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6312                                   DAG.getConstant(16, dl, MVT::i32));
6313         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6314       }
6315 
6316       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6317         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6318         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6319         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6320                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6321                                   DAG.getConstant(24, dl, MVT::i32));
6322         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6323       }
6324 
6325       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6326         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6327         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6328         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6329                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6330                                   DAG.getConstant(0, dl, MVT::i32));
6331         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6332       }
6333 
6334       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6335         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6336         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6337         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6338                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6339                                   DAG.getConstant(8, dl, MVT::i32));
6340         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6341       }
6342 
6343       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6344         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6345         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6346         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6347                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6348                                   DAG.getConstant(264, dl, MVT::i32));
6349         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6350       }
6351 
6352       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6353         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6354         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6355         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6356                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6357                                   DAG.getConstant(272, dl, MVT::i32));
6358         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6359       }
6360 
6361       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6362         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6363         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6364         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6365                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6366         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6367       }
6368 
6369       // The few faces of FMOV...
6370       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6371         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6372         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6373         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6374                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6375         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6376       }
6377 
6378       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6379           VT.getSizeInBits() == 128) {
6380         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6381         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6382                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6383         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6384       }
6385 
6386       // The many faces of MVNI...
6387       CnstVal = ~CnstVal;
6388       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6389         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6390         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6391         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6392                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6393                                   DAG.getConstant(0, dl, MVT::i32));
6394         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6395       }
6396 
6397       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6398         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6399         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6400         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6401                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6402                                   DAG.getConstant(8, dl, MVT::i32));
6403         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6404       }
6405 
6406       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6407         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6408         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6409         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6410                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6411                                   DAG.getConstant(16, dl, MVT::i32));
6412         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6413       }
6414 
6415       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6416         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6417         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6418         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6419                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6420                                   DAG.getConstant(24, dl, MVT::i32));
6421         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6422       }
6423 
6424       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6425         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6426         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6427         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6428                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6429                                   DAG.getConstant(0, dl, MVT::i32));
6430         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6431       }
6432 
6433       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6434         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6435         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6436         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6437                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6438                                   DAG.getConstant(8, dl, MVT::i32));
6439         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6440       }
6441 
6442       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6443         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6444         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6445         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6446                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6447                                   DAG.getConstant(264, dl, MVT::i32));
6448         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6449       }
6450 
6451       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6452         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6453         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6454         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6455                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6456                                   DAG.getConstant(272, dl, MVT::i32));
6457         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6458       }
6459     }
6460 
6461     if (SecondTry)
6462       goto FailedModImm;
6463     SecondTry = true;
6464     CnstBits = UndefBits;
6465     goto AttemptModImm;
6466   }
6467 FailedModImm:
6468 
6469   // Scan through the operands to find some interesting properties we can
6470   // exploit:
6471   //   1) If only one value is used, we can use a DUP, or
6472   //   2) if only the low element is not undef, we can just insert that, or
6473   //   3) if only one constant value is used (w/ some non-constant lanes),
6474   //      we can splat the constant value into the whole vector then fill
6475   //      in the non-constant lanes.
6476   //   4) FIXME: If different constant values are used, but we can intelligently
6477   //             select the values we'll be overwriting for the non-constant
6478   //             lanes such that we can directly materialize the vector
6479   //             some other way (MOVI, e.g.), we can be sneaky.
6480   unsigned NumElts = VT.getVectorNumElements();
6481   bool isOnlyLowElement = true;
6482   bool usesOnlyOneValue = true;
6483   bool usesOnlyOneConstantValue = true;
6484   bool isConstant = true;
6485   unsigned NumConstantLanes = 0;
6486   SDValue Value;
6487   SDValue ConstantValue;
6488   for (unsigned i = 0; i < NumElts; ++i) {
6489     SDValue V = Op.getOperand(i);
6490     if (V.isUndef())
6491       continue;
6492     if (i > 0)
6493       isOnlyLowElement = false;
6494     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6495       isConstant = false;
6496 
6497     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6498       ++NumConstantLanes;
6499       if (!ConstantValue.getNode())
6500         ConstantValue = V;
6501       else if (ConstantValue != V)
6502         usesOnlyOneConstantValue = false;
6503     }
6504 
6505     if (!Value.getNode())
6506       Value = V;
6507     else if (V != Value)
6508       usesOnlyOneValue = false;
6509   }
6510 
6511   if (!Value.getNode())
6512     return DAG.getUNDEF(VT);
6513 
6514   if (isOnlyLowElement)
6515     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6516 
6517   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6518   // i32 and try again.
6519   if (usesOnlyOneValue) {
6520     if (!isConstant) {
6521       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6522           Value.getValueType() != VT)
6523         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6524 
6525       // This is actually a DUPLANExx operation, which keeps everything vectory.
6526 
6527       // DUPLANE works on 128-bit vectors, widen it if necessary.
6528       SDValue Lane = Value.getOperand(1);
6529       Value = Value.getOperand(0);
6530       if (Value.getValueSizeInBits() == 64)
6531         Value = WidenVector(Value, DAG);
6532 
6533       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6534       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6535     }
6536 
6537     if (VT.getVectorElementType().isFloatingPoint()) {
6538       SmallVector<SDValue, 8> Ops;
6539       EVT EltTy = VT.getVectorElementType();
6540       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6541               "Unsupported floating-point vector type");
6542       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6543       for (unsigned i = 0; i < NumElts; ++i)
6544         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6545       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6546       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6547       Val = LowerBUILD_VECTOR(Val, DAG);
6548       if (Val.getNode())
6549         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6550     }
6551   }
6552 
6553   // If there was only one constant value used and for more than one lane,
6554   // start by splatting that value, then replace the non-constant lanes. This
6555   // is better than the default, which will perform a separate initialization
6556   // for each lane.
6557   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6558     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6559     // Now insert the non-constant lanes.
6560     for (unsigned i = 0; i < NumElts; ++i) {
6561       SDValue V = Op.getOperand(i);
6562       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6563       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6564         // Note that type legalization likely mucked about with the VT of the
6565         // source operand, so we may have to convert it here before inserting.
6566         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6567       }
6568     }
6569     return Val;
6570   }
6571 
6572   // If all elements are constants and the case above didn't get hit, fall back
6573   // to the default expansion, which will generate a load from the constant
6574   // pool.
6575   if (isConstant)
6576     return SDValue();
6577 
6578   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6579   if (NumElts >= 4) {
6580     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6581       return shuffle;
6582   }
6583 
6584   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6585   // know the default expansion would otherwise fall back on something even
6586   // worse. For a vector with one or two non-undef values, that's
6587   // scalar_to_vector for the elements followed by a shuffle (provided the
6588   // shuffle is valid for the target) and materialization element by element
6589   // on the stack followed by a load for everything else.
6590   if (!isConstant && !usesOnlyOneValue) {
6591     SDValue Vec = DAG.getUNDEF(VT);
6592     SDValue Op0 = Op.getOperand(0);
6593     unsigned ElemSize = VT.getScalarSizeInBits();
6594     unsigned i = 0;
6595     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6596     // a) Avoid a RMW dependency on the full vector register, and
6597     // b) Allow the register coalescer to fold away the copy if the
6598     //    value is already in an S or D register.
6599     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6600     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6601     if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6602         (ElemSize == 32 || ElemSize == 64)) {
6603       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6604       MachineSDNode *N =
6605           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6606                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6607       Vec = SDValue(N, 0);
6608       ++i;
6609     }
6610     for (; i < NumElts; ++i) {
6611       SDValue V = Op.getOperand(i);
6612       if (V.isUndef())
6613         continue;
6614       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6615       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6616     }
6617     return Vec;
6618   }
6619 
6620   // Just use the default expansion. We failed to find a better alternative.
6621   return SDValue();
6622 }
6623 
6624 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6625                                                       SelectionDAG &DAG) const {
6626   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6627 
6628   // Check for non-constant or out of range lane.
6629   EVT VT = Op.getOperand(0).getValueType();
6630   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6631   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6632     return SDValue();
6633 
6634 
6635   // Insertion/extraction are legal for V128 types.
6636   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6637       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6638       VT == MVT::v8f16)
6639     return Op;
6640 
6641   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6642       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6643     return SDValue();
6644 
6645   // For V64 types, we perform insertion by expanding the value
6646   // to a V128 type and perform the insertion on that.
6647   SDLoc DL(Op);
6648   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6649   EVT WideTy = WideVec.getValueType();
6650 
6651   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6652                              Op.getOperand(1), Op.getOperand(2));
6653   // Re-narrow the resultant vector.
6654   return NarrowVector(Node, DAG);
6655 }
6656 
6657 SDValue
6658 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6659                                                SelectionDAG &DAG) const {
6660   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6661 
6662   // Check for non-constant or out of range lane.
6663   EVT VT = Op.getOperand(0).getValueType();
6664   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6665   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6666     return SDValue();
6667 
6668 
6669   // Insertion/extraction are legal for V128 types.
6670   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6671       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6672       VT == MVT::v8f16)
6673     return Op;
6674 
6675   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6676       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6677     return SDValue();
6678 
6679   // For V64 types, we perform extraction by expanding the value
6680   // to a V128 type and perform the extraction on that.
6681   SDLoc DL(Op);
6682   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6683   EVT WideTy = WideVec.getValueType();
6684 
6685   EVT ExtrTy = WideTy.getVectorElementType();
6686   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6687     ExtrTy = MVT::i32;
6688 
6689   // For extractions, we just return the result directly.
6690   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6691                      Op.getOperand(1));
6692 }
6693 
6694 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6695                                                       SelectionDAG &DAG) const {
6696   EVT VT = Op.getOperand(0).getValueType();
6697   SDLoc dl(Op);
6698   // Just in case...
6699   if (!VT.isVector())
6700     return SDValue();
6701 
6702   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6703   if (!Cst)
6704     return SDValue();
6705   unsigned Val = Cst->getZExtValue();
6706 
6707   unsigned Size = Op.getValueSizeInBits();
6708 
6709   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6710   if (Val == 0)
6711     return Op;
6712 
6713   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6714   // that directly.
6715   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6716     return Op;
6717 
6718   return SDValue();
6719 }
6720 
6721 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6722                                                EVT VT) const {
6723   if (VT.getVectorNumElements() == 4 &&
6724       (VT.is128BitVector() || VT.is64BitVector())) {
6725     unsigned PFIndexes[4];
6726     for (unsigned i = 0; i != 4; ++i) {
6727       if (M[i] < 0)
6728         PFIndexes[i] = 8;
6729       else
6730         PFIndexes[i] = M[i];
6731     }
6732 
6733     // Compute the index in the perfect shuffle table.
6734     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6735                             PFIndexes[2] * 9 + PFIndexes[3];
6736     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6737     unsigned Cost = (PFEntry >> 30);
6738 
6739     if (Cost <= 4)
6740       return true;
6741   }
6742 
6743   bool DummyBool;
6744   int DummyInt;
6745   unsigned DummyUnsigned;
6746 
6747   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6748           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6749           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6750           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6751           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6752           isZIPMask(M, VT, DummyUnsigned) ||
6753           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6754           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6755           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6756           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6757           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6758 }
6759 
6760 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6761 /// operand of a vector shift operation, where all the elements of the
6762 /// build_vector must have the same constant integer value.
6763 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6764   // Ignore bit_converts.
6765   while (Op.getOpcode() == ISD::BITCAST)
6766     Op = Op.getOperand(0);
6767   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6768   APInt SplatBits, SplatUndef;
6769   unsigned SplatBitSize;
6770   bool HasAnyUndefs;
6771   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6772                                     HasAnyUndefs, ElementBits) ||
6773       SplatBitSize > ElementBits)
6774     return false;
6775   Cnt = SplatBits.getSExtValue();
6776   return true;
6777 }
6778 
6779 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6780 /// operand of a vector shift left operation.  That value must be in the range:
6781 ///   0 <= Value < ElementBits for a left shift; or
6782 ///   0 <= Value <= ElementBits for a long left shift.
6783 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6784   assert(VT.isVector() && "vector shift count is not a vector type");
6785   int64_t ElementBits = VT.getScalarSizeInBits();
6786   if (!getVShiftImm(Op, ElementBits, Cnt))
6787     return false;
6788   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6789 }
6790 
6791 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6792 /// operand of a vector shift right operation. The value must be in the range:
6793 ///   1 <= Value <= ElementBits for a right shift; or
6794 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6795   assert(VT.isVector() && "vector shift count is not a vector type");
6796   int64_t ElementBits = VT.getScalarSizeInBits();
6797   if (!getVShiftImm(Op, ElementBits, Cnt))
6798     return false;
6799   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6800 }
6801 
6802 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6803                                                       SelectionDAG &DAG) const {
6804   EVT VT = Op.getValueType();
6805   SDLoc DL(Op);
6806   int64_t Cnt;
6807 
6808   if (!Op.getOperand(1).getValueType().isVector())
6809     return Op;
6810   unsigned EltSize = VT.getScalarSizeInBits();
6811 
6812   switch (Op.getOpcode()) {
6813   default:
6814     llvm_unreachable("unexpected shift opcode");
6815 
6816   case ISD::SHL:
6817     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6818       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6819                          DAG.getConstant(Cnt, DL, MVT::i32));
6820     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6821                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6822                                        MVT::i32),
6823                        Op.getOperand(0), Op.getOperand(1));
6824   case ISD::SRA:
6825   case ISD::SRL:
6826     // Right shift immediate
6827     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6828       unsigned Opc =
6829           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6830       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6831                          DAG.getConstant(Cnt, DL, MVT::i32));
6832     }
6833 
6834     // Right shift register.  Note, there is not a shift right register
6835     // instruction, but the shift left register instruction takes a signed
6836     // value, where negative numbers specify a right shift.
6837     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6838                                                 : Intrinsic::aarch64_neon_ushl;
6839     // negate the shift amount
6840     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6841     SDValue NegShiftLeft =
6842         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6843                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6844                     NegShift);
6845     return NegShiftLeft;
6846   }
6847 
6848   return SDValue();
6849 }
6850 
6851 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6852                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6853                                     const SDLoc &dl, SelectionDAG &DAG) {
6854   EVT SrcVT = LHS.getValueType();
6855   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6856          "function only supposed to emit natural comparisons");
6857 
6858   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6859   APInt CnstBits(VT.getSizeInBits(), 0);
6860   APInt UndefBits(VT.getSizeInBits(), 0);
6861   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6862   bool IsZero = IsCnst && (CnstBits == 0);
6863 
6864   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6865     switch (CC) {
6866     default:
6867       return SDValue();
6868     case AArch64CC::NE: {
6869       SDValue Fcmeq;
6870       if (IsZero)
6871         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6872       else
6873         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6874       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6875     }
6876     case AArch64CC::EQ:
6877       if (IsZero)
6878         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6879       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6880     case AArch64CC::GE:
6881       if (IsZero)
6882         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6883       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6884     case AArch64CC::GT:
6885       if (IsZero)
6886         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6887       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6888     case AArch64CC::LS:
6889       if (IsZero)
6890         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6891       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6892     case AArch64CC::LT:
6893       if (!NoNans)
6894         return SDValue();
6895       // If we ignore NaNs then we can use to the MI implementation.
6896       LLVM_FALLTHROUGH;
6897     case AArch64CC::MI:
6898       if (IsZero)
6899         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6900       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6901     }
6902   }
6903 
6904   switch (CC) {
6905   default:
6906     return SDValue();
6907   case AArch64CC::NE: {
6908     SDValue Cmeq;
6909     if (IsZero)
6910       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6911     else
6912       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6913     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6914   }
6915   case AArch64CC::EQ:
6916     if (IsZero)
6917       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6918     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6919   case AArch64CC::GE:
6920     if (IsZero)
6921       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6922     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6923   case AArch64CC::GT:
6924     if (IsZero)
6925       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6926     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6927   case AArch64CC::LE:
6928     if (IsZero)
6929       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6930     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6931   case AArch64CC::LS:
6932     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6933   case AArch64CC::LO:
6934     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6935   case AArch64CC::LT:
6936     if (IsZero)
6937       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6938     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6939   case AArch64CC::HI:
6940     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6941   case AArch64CC::HS:
6942     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6943   }
6944 }
6945 
6946 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6947                                            SelectionDAG &DAG) const {
6948   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6949   SDValue LHS = Op.getOperand(0);
6950   SDValue RHS = Op.getOperand(1);
6951   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6952   SDLoc dl(Op);
6953 
6954   if (LHS.getValueType().getVectorElementType().isInteger()) {
6955     assert(LHS.getValueType() == RHS.getValueType());
6956     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6957     SDValue Cmp =
6958         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6959     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6960   }
6961 
6962   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6963     return SDValue();
6964 
6965   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6966          LHS.getValueType().getVectorElementType() == MVT::f64);
6967 
6968   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6969   // clean.  Some of them require two branches to implement.
6970   AArch64CC::CondCode CC1, CC2;
6971   bool ShouldInvert;
6972   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6973 
6974   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6975   SDValue Cmp =
6976       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6977   if (!Cmp.getNode())
6978     return SDValue();
6979 
6980   if (CC2 != AArch64CC::AL) {
6981     SDValue Cmp2 =
6982         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6983     if (!Cmp2.getNode())
6984       return SDValue();
6985 
6986     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6987   }
6988 
6989   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6990 
6991   if (ShouldInvert)
6992     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6993 
6994   return Cmp;
6995 }
6996 
6997 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6998 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6999 /// specified in the intrinsic calls.
7000 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7001                                                const CallInst &I,
7002                                                unsigned Intrinsic) const {
7003   auto &DL = I.getModule()->getDataLayout();
7004   switch (Intrinsic) {
7005   case Intrinsic::aarch64_neon_ld2:
7006   case Intrinsic::aarch64_neon_ld3:
7007   case Intrinsic::aarch64_neon_ld4:
7008   case Intrinsic::aarch64_neon_ld1x2:
7009   case Intrinsic::aarch64_neon_ld1x3:
7010   case Intrinsic::aarch64_neon_ld1x4:
7011   case Intrinsic::aarch64_neon_ld2lane:
7012   case Intrinsic::aarch64_neon_ld3lane:
7013   case Intrinsic::aarch64_neon_ld4lane:
7014   case Intrinsic::aarch64_neon_ld2r:
7015   case Intrinsic::aarch64_neon_ld3r:
7016   case Intrinsic::aarch64_neon_ld4r: {
7017     Info.opc = ISD::INTRINSIC_W_CHAIN;
7018     // Conservatively set memVT to the entire set of vectors loaded.
7019     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7020     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7021     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7022     Info.offset = 0;
7023     Info.align = 0;
7024     Info.vol = false; // volatile loads with NEON intrinsics not supported
7025     Info.readMem = true;
7026     Info.writeMem = false;
7027     return true;
7028   }
7029   case Intrinsic::aarch64_neon_st2:
7030   case Intrinsic::aarch64_neon_st3:
7031   case Intrinsic::aarch64_neon_st4:
7032   case Intrinsic::aarch64_neon_st1x2:
7033   case Intrinsic::aarch64_neon_st1x3:
7034   case Intrinsic::aarch64_neon_st1x4:
7035   case Intrinsic::aarch64_neon_st2lane:
7036   case Intrinsic::aarch64_neon_st3lane:
7037   case Intrinsic::aarch64_neon_st4lane: {
7038     Info.opc = ISD::INTRINSIC_VOID;
7039     // Conservatively set memVT to the entire set of vectors stored.
7040     unsigned NumElts = 0;
7041     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7042       Type *ArgTy = I.getArgOperand(ArgI)->getType();
7043       if (!ArgTy->isVectorTy())
7044         break;
7045       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7046     }
7047     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7048     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7049     Info.offset = 0;
7050     Info.align = 0;
7051     Info.vol = false; // volatile stores with NEON intrinsics not supported
7052     Info.readMem = false;
7053     Info.writeMem = true;
7054     return true;
7055   }
7056   case Intrinsic::aarch64_ldaxr:
7057   case Intrinsic::aarch64_ldxr: {
7058     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7059     Info.opc = ISD::INTRINSIC_W_CHAIN;
7060     Info.memVT = MVT::getVT(PtrTy->getElementType());
7061     Info.ptrVal = I.getArgOperand(0);
7062     Info.offset = 0;
7063     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7064     Info.vol = true;
7065     Info.readMem = true;
7066     Info.writeMem = false;
7067     return true;
7068   }
7069   case Intrinsic::aarch64_stlxr:
7070   case Intrinsic::aarch64_stxr: {
7071     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7072     Info.opc = ISD::INTRINSIC_W_CHAIN;
7073     Info.memVT = MVT::getVT(PtrTy->getElementType());
7074     Info.ptrVal = I.getArgOperand(1);
7075     Info.offset = 0;
7076     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7077     Info.vol = true;
7078     Info.readMem = false;
7079     Info.writeMem = true;
7080     return true;
7081   }
7082   case Intrinsic::aarch64_ldaxp:
7083   case Intrinsic::aarch64_ldxp:
7084     Info.opc = ISD::INTRINSIC_W_CHAIN;
7085     Info.memVT = MVT::i128;
7086     Info.ptrVal = I.getArgOperand(0);
7087     Info.offset = 0;
7088     Info.align = 16;
7089     Info.vol = true;
7090     Info.readMem = true;
7091     Info.writeMem = false;
7092     return true;
7093   case Intrinsic::aarch64_stlxp:
7094   case Intrinsic::aarch64_stxp:
7095     Info.opc = ISD::INTRINSIC_W_CHAIN;
7096     Info.memVT = MVT::i128;
7097     Info.ptrVal = I.getArgOperand(2);
7098     Info.offset = 0;
7099     Info.align = 16;
7100     Info.vol = true;
7101     Info.readMem = false;
7102     Info.writeMem = true;
7103     return true;
7104   default:
7105     break;
7106   }
7107 
7108   return false;
7109 }
7110 
7111 // Truncations from 64-bit GPR to 32-bit GPR is free.
7112 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7113   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7114     return false;
7115   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7116   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7117   return NumBits1 > NumBits2;
7118 }
7119 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7120   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7121     return false;
7122   unsigned NumBits1 = VT1.getSizeInBits();
7123   unsigned NumBits2 = VT2.getSizeInBits();
7124   return NumBits1 > NumBits2;
7125 }
7126 
7127 /// Check if it is profitable to hoist instruction in then/else to if.
7128 /// Not profitable if I and it's user can form a FMA instruction
7129 /// because we prefer FMSUB/FMADD.
7130 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7131   if (I->getOpcode() != Instruction::FMul)
7132     return true;
7133 
7134   if (I->getNumUses() != 1)
7135     return true;
7136 
7137   Instruction *User = I->user_back();
7138 
7139   if (User &&
7140       !(User->getOpcode() == Instruction::FSub ||
7141         User->getOpcode() == Instruction::FAdd))
7142     return true;
7143 
7144   const TargetOptions &Options = getTargetMachine().Options;
7145   const DataLayout &DL = I->getModule()->getDataLayout();
7146   EVT VT = getValueType(DL, User->getOperand(0)->getType());
7147 
7148   return !(isFMAFasterThanFMulAndFAdd(VT) &&
7149            isOperationLegalOrCustom(ISD::FMA, VT) &&
7150            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7151             Options.UnsafeFPMath));
7152 }
7153 
7154 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7155 // 64-bit GPR.
7156 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7157   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7158     return false;
7159   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7160   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7161   return NumBits1 == 32 && NumBits2 == 64;
7162 }
7163 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7164   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7165     return false;
7166   unsigned NumBits1 = VT1.getSizeInBits();
7167   unsigned NumBits2 = VT2.getSizeInBits();
7168   return NumBits1 == 32 && NumBits2 == 64;
7169 }
7170 
7171 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7172   EVT VT1 = Val.getValueType();
7173   if (isZExtFree(VT1, VT2)) {
7174     return true;
7175   }
7176 
7177   if (Val.getOpcode() != ISD::LOAD)
7178     return false;
7179 
7180   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7181   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7182           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7183           VT1.getSizeInBits() <= 32);
7184 }
7185 
7186 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7187   if (isa<FPExtInst>(Ext))
7188     return false;
7189 
7190   // Vector types are next free.
7191   if (Ext->getType()->isVectorTy())
7192     return false;
7193 
7194   for (const Use &U : Ext->uses()) {
7195     // The extension is free if we can fold it with a left shift in an
7196     // addressing mode or an arithmetic operation: add, sub, and cmp.
7197 
7198     // Is there a shift?
7199     const Instruction *Instr = cast<Instruction>(U.getUser());
7200 
7201     // Is this a constant shift?
7202     switch (Instr->getOpcode()) {
7203     case Instruction::Shl:
7204       if (!isa<ConstantInt>(Instr->getOperand(1)))
7205         return false;
7206       break;
7207     case Instruction::GetElementPtr: {
7208       gep_type_iterator GTI = gep_type_begin(Instr);
7209       auto &DL = Ext->getModule()->getDataLayout();
7210       std::advance(GTI, U.getOperandNo()-1);
7211       Type *IdxTy = GTI.getIndexedType();
7212       // This extension will end up with a shift because of the scaling factor.
7213       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7214       // Get the shift amount based on the scaling factor:
7215       // log2(sizeof(IdxTy)) - log2(8).
7216       uint64_t ShiftAmt =
7217           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7218       // Is the constant foldable in the shift of the addressing mode?
7219       // I.e., shift amount is between 1 and 4 inclusive.
7220       if (ShiftAmt == 0 || ShiftAmt > 4)
7221         return false;
7222       break;
7223     }
7224     case Instruction::Trunc:
7225       // Check if this is a noop.
7226       // trunc(sext ty1 to ty2) to ty1.
7227       if (Instr->getType() == Ext->getOperand(0)->getType())
7228         continue;
7229       LLVM_FALLTHROUGH;
7230     default:
7231       return false;
7232     }
7233 
7234     // At this point we can use the bfm family, so this extension is free
7235     // for that use.
7236   }
7237   return true;
7238 }
7239 
7240 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7241                                           unsigned &RequiredAligment) const {
7242   if (!LoadedType.isSimple() ||
7243       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7244     return false;
7245   // Cyclone supports unaligned accesses.
7246   RequiredAligment = 0;
7247   unsigned NumBits = LoadedType.getSizeInBits();
7248   return NumBits == 32 || NumBits == 64;
7249 }
7250 
7251 /// \brief Lower an interleaved load into a ldN intrinsic.
7252 ///
7253 /// E.g. Lower an interleaved load (Factor = 2):
7254 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7255 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7256 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7257 ///
7258 ///      Into:
7259 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7260 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7261 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7262 bool AArch64TargetLowering::lowerInterleavedLoad(
7263     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7264     ArrayRef<unsigned> Indices, unsigned Factor) const {
7265   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7266          "Invalid interleave factor");
7267   assert(!Shuffles.empty() && "Empty shufflevector input");
7268   assert(Shuffles.size() == Indices.size() &&
7269          "Unmatched number of shufflevectors and indices");
7270 
7271   const DataLayout &DL = LI->getModule()->getDataLayout();
7272 
7273   VectorType *VecTy = Shuffles[0]->getType();
7274   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7275 
7276   // Skip if we do not have NEON and skip illegal vector types.
7277   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7278     return false;
7279 
7280   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7281   // load integer vectors first and then convert to pointer vectors.
7282   Type *EltTy = VecTy->getVectorElementType();
7283   if (EltTy->isPointerTy())
7284     VecTy =
7285         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7286 
7287   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7288   Type *Tys[2] = {VecTy, PtrTy};
7289   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7290                                             Intrinsic::aarch64_neon_ld3,
7291                                             Intrinsic::aarch64_neon_ld4};
7292   Function *LdNFunc =
7293       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7294 
7295   IRBuilder<> Builder(LI);
7296   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7297 
7298   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7299 
7300   // Replace uses of each shufflevector with the corresponding vector loaded
7301   // by ldN.
7302   for (unsigned i = 0; i < Shuffles.size(); i++) {
7303     ShuffleVectorInst *SVI = Shuffles[i];
7304     unsigned Index = Indices[i];
7305 
7306     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7307 
7308     // Convert the integer vector to pointer vector if the element is pointer.
7309     if (EltTy->isPointerTy())
7310       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7311 
7312     SVI->replaceAllUsesWith(SubVec);
7313   }
7314 
7315   return true;
7316 }
7317 
7318 /// \brief Lower an interleaved store into a stN intrinsic.
7319 ///
7320 /// E.g. Lower an interleaved store (Factor = 3):
7321 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7322 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7323 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7324 ///
7325 ///      Into:
7326 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7327 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7328 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7329 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7330 ///
7331 /// Note that the new shufflevectors will be removed and we'll only generate one
7332 /// st3 instruction in CodeGen.
7333 ///
7334 /// Example for a more general valid mask (Factor 3). Lower:
7335 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7336 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7337 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7338 ///
7339 ///      Into:
7340 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7341 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7342 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7343 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7344 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7345                                                   ShuffleVectorInst *SVI,
7346                                                   unsigned Factor) const {
7347   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7348          "Invalid interleave factor");
7349 
7350   VectorType *VecTy = SVI->getType();
7351   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7352          "Invalid interleaved store");
7353 
7354   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7355   Type *EltTy = VecTy->getVectorElementType();
7356   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7357 
7358   const DataLayout &DL = SI->getModule()->getDataLayout();
7359   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7360 
7361   // Skip if we do not have NEON and skip illegal vector types.
7362   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7363     return false;
7364 
7365   Value *Op0 = SVI->getOperand(0);
7366   Value *Op1 = SVI->getOperand(1);
7367   IRBuilder<> Builder(SI);
7368 
7369   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7370   // vectors to integer vectors.
7371   if (EltTy->isPointerTy()) {
7372     Type *IntTy = DL.getIntPtrType(EltTy);
7373     unsigned NumOpElts =
7374         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7375 
7376     // Convert to the corresponding integer vector.
7377     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7378     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7379     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7380 
7381     SubVecTy = VectorType::get(IntTy, LaneLen);
7382   }
7383 
7384   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7385   Type *Tys[2] = {SubVecTy, PtrTy};
7386   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7387                                              Intrinsic::aarch64_neon_st3,
7388                                              Intrinsic::aarch64_neon_st4};
7389   Function *StNFunc =
7390       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7391 
7392   SmallVector<Value *, 5> Ops;
7393 
7394   // Split the shufflevector operands into sub vectors for the new stN call.
7395   auto Mask = SVI->getShuffleMask();
7396   for (unsigned i = 0; i < Factor; i++) {
7397     if (Mask[i] >= 0) {
7398       Ops.push_back(Builder.CreateShuffleVector(
7399           Op0, Op1, createSequentialMask(Builder, Mask[i], LaneLen, 0)));
7400     } else {
7401       unsigned StartMask = 0;
7402       for (unsigned j = 1; j < LaneLen; j++) {
7403         if (Mask[j*Factor + i] >= 0) {
7404           StartMask = Mask[j*Factor + i] - j;
7405           break;
7406         }
7407       }
7408       // Note: If all elements in a chunk are undefs, StartMask=0!
7409       // Note: Filling undef gaps with random elements is ok, since
7410       // those elements were being written anyway (with undefs).
7411       // In the case of all undefs we're defaulting to using elems from 0
7412       // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
7413       Ops.push_back(Builder.CreateShuffleVector(
7414           Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7415     }
7416   }
7417 
7418   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7419   Builder.CreateCall(StNFunc, Ops);
7420   return true;
7421 }
7422 
7423 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7424                        unsigned AlignCheck) {
7425   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7426           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7427 }
7428 
7429 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7430                                                unsigned SrcAlign, bool IsMemset,
7431                                                bool ZeroMemset,
7432                                                bool MemcpyStrSrc,
7433                                                MachineFunction &MF) const {
7434   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7435   // instruction to materialize the v2i64 zero and one store (with restrictive
7436   // addressing mode). Just do two i64 store of zero-registers.
7437   bool Fast;
7438   const Function *F = MF.getFunction();
7439   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7440       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7441       (memOpAlign(SrcAlign, DstAlign, 16) ||
7442        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7443     return MVT::f128;
7444 
7445   if (Size >= 8 &&
7446       (memOpAlign(SrcAlign, DstAlign, 8) ||
7447        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7448     return MVT::i64;
7449 
7450   if (Size >= 4 &&
7451       (memOpAlign(SrcAlign, DstAlign, 4) ||
7452        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7453     return MVT::i32;
7454 
7455   return MVT::Other;
7456 }
7457 
7458 // 12-bit optionally shifted immediates are legal for adds.
7459 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7460   // Avoid UB for INT64_MIN.
7461   if (Immed == std::numeric_limits<int64_t>::min())
7462     return false;
7463   // Same encoding for add/sub, just flip the sign.
7464   Immed = std::abs(Immed);
7465   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7466 }
7467 
7468 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7469 // immediates is the same as for an add or a sub.
7470 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7471   return isLegalAddImmediate(Immed);
7472 }
7473 
7474 /// isLegalAddressingMode - Return true if the addressing mode represented
7475 /// by AM is legal for this target, for a load/store of the specified type.
7476 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7477                                                   const AddrMode &AM, Type *Ty,
7478                                                   unsigned AS) const {
7479   // AArch64 has five basic addressing modes:
7480   //  reg
7481   //  reg + 9-bit signed offset
7482   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7483   //  reg1 + reg2
7484   //  reg + SIZE_IN_BYTES * reg
7485 
7486   // No global is ever allowed as a base.
7487   if (AM.BaseGV)
7488     return false;
7489 
7490   // No reg+reg+imm addressing.
7491   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7492     return false;
7493 
7494   // check reg + imm case:
7495   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7496   uint64_t NumBytes = 0;
7497   if (Ty->isSized()) {
7498     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7499     NumBytes = NumBits / 8;
7500     if (!isPowerOf2_64(NumBits))
7501       NumBytes = 0;
7502   }
7503 
7504   if (!AM.Scale) {
7505     int64_t Offset = AM.BaseOffs;
7506 
7507     // 9-bit signed offset
7508     if (isInt<9>(Offset))
7509       return true;
7510 
7511     // 12-bit unsigned offset
7512     unsigned shift = Log2_64(NumBytes);
7513     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7514         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7515         (Offset >> shift) << shift == Offset)
7516       return true;
7517     return false;
7518   }
7519 
7520   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7521 
7522   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7523 }
7524 
7525 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7526                                                 const AddrMode &AM, Type *Ty,
7527                                                 unsigned AS) const {
7528   // Scaling factors are not free at all.
7529   // Operands                     | Rt Latency
7530   // -------------------------------------------
7531   // Rt, [Xn, Xm]                 | 4
7532   // -------------------------------------------
7533   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7534   // Rt, [Xn, Wm, <extend> #imm]  |
7535   if (isLegalAddressingMode(DL, AM, Ty, AS))
7536     // Scale represents reg2 * scale, thus account for 1 if
7537     // it is not equal to 0 or 1.
7538     return AM.Scale != 0 && AM.Scale != 1;
7539   return -1;
7540 }
7541 
7542 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7543   VT = VT.getScalarType();
7544 
7545   if (!VT.isSimple())
7546     return false;
7547 
7548   switch (VT.getSimpleVT().SimpleTy) {
7549   case MVT::f32:
7550   case MVT::f64:
7551     return true;
7552   default:
7553     break;
7554   }
7555 
7556   return false;
7557 }
7558 
7559 const MCPhysReg *
7560 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7561   // LR is a callee-save register, but we must treat it as clobbered by any call
7562   // site. Hence we include LR in the scratch registers, which are in turn added
7563   // as implicit-defs for stackmaps and patchpoints.
7564   static const MCPhysReg ScratchRegs[] = {
7565     AArch64::X16, AArch64::X17, AArch64::LR, 0
7566   };
7567   return ScratchRegs;
7568 }
7569 
7570 bool
7571 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7572   EVT VT = N->getValueType(0);
7573     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7574     // it with shift to let it be lowered to UBFX.
7575   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7576       isa<ConstantSDNode>(N->getOperand(1))) {
7577     uint64_t TruncMask = N->getConstantOperandVal(1);
7578     if (isMask_64(TruncMask) &&
7579       N->getOperand(0).getOpcode() == ISD::SRL &&
7580       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7581       return false;
7582   }
7583   return true;
7584 }
7585 
7586 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7587                                                               Type *Ty) const {
7588   assert(Ty->isIntegerTy());
7589 
7590   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7591   if (BitSize == 0)
7592     return false;
7593 
7594   int64_t Val = Imm.getSExtValue();
7595   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7596     return true;
7597 
7598   if ((int64_t)Val < 0)
7599     Val = ~Val;
7600   if (BitSize == 32)
7601     Val &= (1LL << 32) - 1;
7602 
7603   unsigned LZ = countLeadingZeros((uint64_t)Val);
7604   unsigned Shift = (63 - LZ) / 16;
7605   // MOVZ is free so return true for one or fewer MOVK.
7606   return Shift < 3;
7607 }
7608 
7609 /// Turn vector tests of the signbit in the form of:
7610 ///   xor (sra X, elt_size(X)-1), -1
7611 /// into:
7612 ///   cmge X, X, #0
7613 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7614                                          const AArch64Subtarget *Subtarget) {
7615   EVT VT = N->getValueType(0);
7616   if (!Subtarget->hasNEON() || !VT.isVector())
7617     return SDValue();
7618 
7619   // There must be a shift right algebraic before the xor, and the xor must be a
7620   // 'not' operation.
7621   SDValue Shift = N->getOperand(0);
7622   SDValue Ones = N->getOperand(1);
7623   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7624       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7625     return SDValue();
7626 
7627   // The shift should be smearing the sign bit across each vector element.
7628   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7629   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7630   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7631     return SDValue();
7632 
7633   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7634 }
7635 
7636 // Generate SUBS and CSEL for integer abs.
7637 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7638   EVT VT = N->getValueType(0);
7639 
7640   SDValue N0 = N->getOperand(0);
7641   SDValue N1 = N->getOperand(1);
7642   SDLoc DL(N);
7643 
7644   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7645   // and change it to SUB and CSEL.
7646   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7647       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7648       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7649     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7650       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7651         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7652                                   N0.getOperand(0));
7653         // Generate SUBS & CSEL.
7654         SDValue Cmp =
7655             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7656                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7657         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7658                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7659                            SDValue(Cmp.getNode(), 1));
7660       }
7661   return SDValue();
7662 }
7663 
7664 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7665                                  TargetLowering::DAGCombinerInfo &DCI,
7666                                  const AArch64Subtarget *Subtarget) {
7667   if (DCI.isBeforeLegalizeOps())
7668     return SDValue();
7669 
7670   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7671     return Cmp;
7672 
7673   return performIntegerAbsCombine(N, DAG);
7674 }
7675 
7676 SDValue
7677 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7678                                      SelectionDAG &DAG,
7679                                      std::vector<SDNode *> *Created) const {
7680   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7681   if (isIntDivCheap(N->getValueType(0), Attr))
7682     return SDValue(N,0); // Lower SDIV as SDIV
7683 
7684   // fold (sdiv X, pow2)
7685   EVT VT = N->getValueType(0);
7686   if ((VT != MVT::i32 && VT != MVT::i64) ||
7687       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7688     return SDValue();
7689 
7690   SDLoc DL(N);
7691   SDValue N0 = N->getOperand(0);
7692   unsigned Lg2 = Divisor.countTrailingZeros();
7693   SDValue Zero = DAG.getConstant(0, DL, VT);
7694   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7695 
7696   // Add (N0 < 0) ? Pow2 - 1 : 0;
7697   SDValue CCVal;
7698   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7699   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7700   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7701 
7702   if (Created) {
7703     Created->push_back(Cmp.getNode());
7704     Created->push_back(Add.getNode());
7705     Created->push_back(CSel.getNode());
7706   }
7707 
7708   // Divide by pow2.
7709   SDValue SRA =
7710       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7711 
7712   // If we're dividing by a positive value, we're done.  Otherwise, we must
7713   // negate the result.
7714   if (Divisor.isNonNegative())
7715     return SRA;
7716 
7717   if (Created)
7718     Created->push_back(SRA.getNode());
7719   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7720 }
7721 
7722 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7723                                  TargetLowering::DAGCombinerInfo &DCI,
7724                                  const AArch64Subtarget *Subtarget) {
7725   if (DCI.isBeforeLegalizeOps())
7726     return SDValue();
7727 
7728   // The below optimizations require a constant RHS.
7729   if (!isa<ConstantSDNode>(N->getOperand(1)))
7730     return SDValue();
7731 
7732   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7733   const APInt &ConstValue = C->getAPIntValue();
7734 
7735   // Multiplication of a power of two plus/minus one can be done more
7736   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7737   // future CPUs have a cheaper MADD instruction, this may need to be
7738   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7739   // 64-bit is 5 cycles, so this is always a win.
7740   // More aggressively, some multiplications N0 * C can be lowered to
7741   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7742   // e.g. 6=3*2=(2+1)*2.
7743   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7744   // which equals to (1+2)*16-(1+2).
7745   SDValue N0 = N->getOperand(0);
7746   // TrailingZeroes is used to test if the mul can be lowered to
7747   // shift+add+shift.
7748   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7749   if (TrailingZeroes) {
7750     // Conservatively do not lower to shift+add+shift if the mul might be
7751     // folded into smul or umul.
7752     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7753                             isZeroExtended(N0.getNode(), DAG)))
7754       return SDValue();
7755     // Conservatively do not lower to shift+add+shift if the mul might be
7756     // folded into madd or msub.
7757     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7758                            N->use_begin()->getOpcode() == ISD::SUB))
7759       return SDValue();
7760   }
7761   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7762   // and shift+add+shift.
7763   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7764 
7765   unsigned ShiftAmt, AddSubOpc;
7766   // Is the shifted value the LHS operand of the add/sub?
7767   bool ShiftValUseIsN0 = true;
7768   // Do we need to negate the result?
7769   bool NegateResult = false;
7770 
7771   if (ConstValue.isNonNegative()) {
7772     // (mul x, 2^N + 1) => (add (shl x, N), x)
7773     // (mul x, 2^N - 1) => (sub (shl x, N), x)
7774     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7775     APInt SCVMinus1 = ShiftedConstValue - 1;
7776     APInt CVPlus1 = ConstValue + 1;
7777     if (SCVMinus1.isPowerOf2()) {
7778       ShiftAmt = SCVMinus1.logBase2();
7779       AddSubOpc = ISD::ADD;
7780     } else if (CVPlus1.isPowerOf2()) {
7781       ShiftAmt = CVPlus1.logBase2();
7782       AddSubOpc = ISD::SUB;
7783     } else
7784       return SDValue();
7785   } else {
7786     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7787     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7788     APInt CVNegPlus1 = -ConstValue + 1;
7789     APInt CVNegMinus1 = -ConstValue - 1;
7790     if (CVNegPlus1.isPowerOf2()) {
7791       ShiftAmt = CVNegPlus1.logBase2();
7792       AddSubOpc = ISD::SUB;
7793       ShiftValUseIsN0 = false;
7794     } else if (CVNegMinus1.isPowerOf2()) {
7795       ShiftAmt = CVNegMinus1.logBase2();
7796       AddSubOpc = ISD::ADD;
7797       NegateResult = true;
7798     } else
7799       return SDValue();
7800   }
7801 
7802   SDLoc DL(N);
7803   EVT VT = N->getValueType(0);
7804   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
7805                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
7806 
7807   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7808   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7809   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
7810   assert(!(NegateResult && TrailingZeroes) &&
7811          "NegateResult and TrailingZeroes cannot both be true for now.");
7812   // Negate the result.
7813   if (NegateResult)
7814     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7815   // Shift the result.
7816   if (TrailingZeroes)
7817     return DAG.getNode(ISD::SHL, DL, VT, Res,
7818                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7819   return Res;
7820 }
7821 
7822 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7823                                                          SelectionDAG &DAG) {
7824   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7825   // optimize away operation when it's from a constant.
7826   //
7827   // The general transformation is:
7828   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7829   //       AND(VECTOR_CMP(x,y), constant2)
7830   //    constant2 = UNARYOP(constant)
7831 
7832   // Early exit if this isn't a vector operation, the operand of the
7833   // unary operation isn't a bitwise AND, or if the sizes of the operations
7834   // aren't the same.
7835   EVT VT = N->getValueType(0);
7836   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7837       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7838       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7839     return SDValue();
7840 
7841   // Now check that the other operand of the AND is a constant. We could
7842   // make the transformation for non-constant splats as well, but it's unclear
7843   // that would be a benefit as it would not eliminate any operations, just
7844   // perform one more step in scalar code before moving to the vector unit.
7845   if (BuildVectorSDNode *BV =
7846           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7847     // Bail out if the vector isn't a constant.
7848     if (!BV->isConstant())
7849       return SDValue();
7850 
7851     // Everything checks out. Build up the new and improved node.
7852     SDLoc DL(N);
7853     EVT IntVT = BV->getValueType(0);
7854     // Create a new constant of the appropriate type for the transformed
7855     // DAG.
7856     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7857     // The AND node needs bitcasts to/from an integer vector type around it.
7858     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7859     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7860                                  N->getOperand(0)->getOperand(0), MaskConst);
7861     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7862     return Res;
7863   }
7864 
7865   return SDValue();
7866 }
7867 
7868 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7869                                      const AArch64Subtarget *Subtarget) {
7870   // First try to optimize away the conversion when it's conditionally from
7871   // a constant. Vectors only.
7872   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7873     return Res;
7874 
7875   EVT VT = N->getValueType(0);
7876   if (VT != MVT::f32 && VT != MVT::f64)
7877     return SDValue();
7878 
7879   // Only optimize when the source and destination types have the same width.
7880   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
7881     return SDValue();
7882 
7883   // If the result of an integer load is only used by an integer-to-float
7884   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7885   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7886   SDValue N0 = N->getOperand(0);
7887   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7888       // Do not change the width of a volatile load.
7889       !cast<LoadSDNode>(N0)->isVolatile()) {
7890     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7891     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7892                                LN0->getPointerInfo(), LN0->getAlignment(),
7893                                LN0->getMemOperand()->getFlags());
7894 
7895     // Make sure successors of the original load stay after it by updating them
7896     // to use the new Chain.
7897     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7898 
7899     unsigned Opcode =
7900         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7901     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7902   }
7903 
7904   return SDValue();
7905 }
7906 
7907 /// Fold a floating-point multiply by power of two into floating-point to
7908 /// fixed-point conversion.
7909 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7910                                      TargetLowering::DAGCombinerInfo &DCI,
7911                                      const AArch64Subtarget *Subtarget) {
7912   if (!Subtarget->hasNEON())
7913     return SDValue();
7914 
7915   SDValue Op = N->getOperand(0);
7916   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7917       Op.getOpcode() != ISD::FMUL)
7918     return SDValue();
7919 
7920   SDValue ConstVec = Op->getOperand(1);
7921   if (!isa<BuildVectorSDNode>(ConstVec))
7922     return SDValue();
7923 
7924   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7925   uint32_t FloatBits = FloatTy.getSizeInBits();
7926   if (FloatBits != 32 && FloatBits != 64)
7927     return SDValue();
7928 
7929   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7930   uint32_t IntBits = IntTy.getSizeInBits();
7931   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7932     return SDValue();
7933 
7934   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7935   if (IntBits > FloatBits)
7936     return SDValue();
7937 
7938   BitVector UndefElements;
7939   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7940   int32_t Bits = IntBits == 64 ? 64 : 32;
7941   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7942   if (C == -1 || C == 0 || C > Bits)
7943     return SDValue();
7944 
7945   MVT ResTy;
7946   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7947   switch (NumLanes) {
7948   default:
7949     return SDValue();
7950   case 2:
7951     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7952     break;
7953   case 4:
7954     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7955     break;
7956   }
7957 
7958   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7959     return SDValue();
7960 
7961   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7962          "Illegal vector type after legalization");
7963 
7964   SDLoc DL(N);
7965   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7966   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7967                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7968   SDValue FixConv =
7969       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7970                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7971                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7972   // We can handle smaller integers by generating an extra trunc.
7973   if (IntBits < FloatBits)
7974     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7975 
7976   return FixConv;
7977 }
7978 
7979 /// Fold a floating-point divide by power of two into fixed-point to
7980 /// floating-point conversion.
7981 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7982                                   TargetLowering::DAGCombinerInfo &DCI,
7983                                   const AArch64Subtarget *Subtarget) {
7984   if (!Subtarget->hasNEON())
7985     return SDValue();
7986 
7987   SDValue Op = N->getOperand(0);
7988   unsigned Opc = Op->getOpcode();
7989   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7990       !Op.getOperand(0).getValueType().isSimple() ||
7991       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7992     return SDValue();
7993 
7994   SDValue ConstVec = N->getOperand(1);
7995   if (!isa<BuildVectorSDNode>(ConstVec))
7996     return SDValue();
7997 
7998   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7999   int32_t IntBits = IntTy.getSizeInBits();
8000   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8001     return SDValue();
8002 
8003   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8004   int32_t FloatBits = FloatTy.getSizeInBits();
8005   if (FloatBits != 32 && FloatBits != 64)
8006     return SDValue();
8007 
8008   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8009   if (IntBits > FloatBits)
8010     return SDValue();
8011 
8012   BitVector UndefElements;
8013   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8014   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8015   if (C == -1 || C == 0 || C > FloatBits)
8016     return SDValue();
8017 
8018   MVT ResTy;
8019   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8020   switch (NumLanes) {
8021   default:
8022     return SDValue();
8023   case 2:
8024     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8025     break;
8026   case 4:
8027     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8028     break;
8029   }
8030 
8031   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8032     return SDValue();
8033 
8034   SDLoc DL(N);
8035   SDValue ConvInput = Op.getOperand(0);
8036   bool IsSigned = Opc == ISD::SINT_TO_FP;
8037   if (IntBits < FloatBits)
8038     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8039                             ResTy, ConvInput);
8040 
8041   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8042                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
8043   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8044                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8045                      DAG.getConstant(C, DL, MVT::i32));
8046 }
8047 
8048 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8049 /// searches for and classifies those shifts.
8050 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8051                          bool &FromHi) {
8052   if (N.getOpcode() == ISD::SHL)
8053     FromHi = false;
8054   else if (N.getOpcode() == ISD::SRL)
8055     FromHi = true;
8056   else
8057     return false;
8058 
8059   if (!isa<ConstantSDNode>(N.getOperand(1)))
8060     return false;
8061 
8062   ShiftAmount = N->getConstantOperandVal(1);
8063   Src = N->getOperand(0);
8064   return true;
8065 }
8066 
8067 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8068 /// registers viewed as a high/low pair. This function looks for the pattern:
8069 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8070 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8071 /// independent.
8072 static SDValue tryCombineToEXTR(SDNode *N,
8073                                 TargetLowering::DAGCombinerInfo &DCI) {
8074   SelectionDAG &DAG = DCI.DAG;
8075   SDLoc DL(N);
8076   EVT VT = N->getValueType(0);
8077 
8078   assert(N->getOpcode() == ISD::OR && "Unexpected root");
8079 
8080   if (VT != MVT::i32 && VT != MVT::i64)
8081     return SDValue();
8082 
8083   SDValue LHS;
8084   uint32_t ShiftLHS = 0;
8085   bool LHSFromHi = false;
8086   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8087     return SDValue();
8088 
8089   SDValue RHS;
8090   uint32_t ShiftRHS = 0;
8091   bool RHSFromHi = false;
8092   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8093     return SDValue();
8094 
8095   // If they're both trying to come from the high part of the register, they're
8096   // not really an EXTR.
8097   if (LHSFromHi == RHSFromHi)
8098     return SDValue();
8099 
8100   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8101     return SDValue();
8102 
8103   if (LHSFromHi) {
8104     std::swap(LHS, RHS);
8105     std::swap(ShiftLHS, ShiftRHS);
8106   }
8107 
8108   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8109                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
8110 }
8111 
8112 static SDValue tryCombineToBSL(SDNode *N,
8113                                 TargetLowering::DAGCombinerInfo &DCI) {
8114   EVT VT = N->getValueType(0);
8115   SelectionDAG &DAG = DCI.DAG;
8116   SDLoc DL(N);
8117 
8118   if (!VT.isVector())
8119     return SDValue();
8120 
8121   SDValue N0 = N->getOperand(0);
8122   if (N0.getOpcode() != ISD::AND)
8123     return SDValue();
8124 
8125   SDValue N1 = N->getOperand(1);
8126   if (N1.getOpcode() != ISD::AND)
8127     return SDValue();
8128 
8129   // We only have to look for constant vectors here since the general, variable
8130   // case can be handled in TableGen.
8131   unsigned Bits = VT.getScalarSizeInBits();
8132   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8133   for (int i = 1; i >= 0; --i)
8134     for (int j = 1; j >= 0; --j) {
8135       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8136       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8137       if (!BVN0 || !BVN1)
8138         continue;
8139 
8140       bool FoundMatch = true;
8141       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8142         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8143         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8144         if (!CN0 || !CN1 ||
8145             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8146           FoundMatch = false;
8147           break;
8148         }
8149       }
8150 
8151       if (FoundMatch)
8152         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8153                            N0->getOperand(1 - i), N1->getOperand(1 - j));
8154     }
8155 
8156   return SDValue();
8157 }
8158 
8159 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8160                                 const AArch64Subtarget *Subtarget) {
8161   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8162   SelectionDAG &DAG = DCI.DAG;
8163   EVT VT = N->getValueType(0);
8164 
8165   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8166     return SDValue();
8167 
8168   if (SDValue Res = tryCombineToEXTR(N, DCI))
8169     return Res;
8170 
8171   if (SDValue Res = tryCombineToBSL(N, DCI))
8172     return Res;
8173 
8174   return SDValue();
8175 }
8176 
8177 static SDValue performSRLCombine(SDNode *N,
8178                                  TargetLowering::DAGCombinerInfo &DCI) {
8179   SelectionDAG &DAG = DCI.DAG;
8180   EVT VT = N->getValueType(0);
8181   if (VT != MVT::i32 && VT != MVT::i64)
8182     return SDValue();
8183 
8184   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8185   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8186   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8187   SDValue N0 = N->getOperand(0);
8188   if (N0.getOpcode() == ISD::BSWAP) {
8189     SDLoc DL(N);
8190     SDValue N1 = N->getOperand(1);
8191     SDValue N00 = N0.getOperand(0);
8192     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8193       uint64_t ShiftAmt = C->getZExtValue();
8194       if (VT == MVT::i32 && ShiftAmt == 16 &&
8195           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8196         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8197       if (VT == MVT::i64 && ShiftAmt == 32 &&
8198           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8199         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8200     }
8201   }
8202   return SDValue();
8203 }
8204 
8205 static SDValue performBitcastCombine(SDNode *N,
8206                                      TargetLowering::DAGCombinerInfo &DCI,
8207                                      SelectionDAG &DAG) {
8208   // Wait 'til after everything is legalized to try this. That way we have
8209   // legal vector types and such.
8210   if (DCI.isBeforeLegalizeOps())
8211     return SDValue();
8212 
8213   // Remove extraneous bitcasts around an extract_subvector.
8214   // For example,
8215   //    (v4i16 (bitconvert
8216   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8217   //  becomes
8218   //    (extract_subvector ((v8i16 ...), (i64 4)))
8219 
8220   // Only interested in 64-bit vectors as the ultimate result.
8221   EVT VT = N->getValueType(0);
8222   if (!VT.isVector())
8223     return SDValue();
8224   if (VT.getSimpleVT().getSizeInBits() != 64)
8225     return SDValue();
8226   // Is the operand an extract_subvector starting at the beginning or halfway
8227   // point of the vector? A low half may also come through as an
8228   // EXTRACT_SUBREG, so look for that, too.
8229   SDValue Op0 = N->getOperand(0);
8230   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8231       !(Op0->isMachineOpcode() &&
8232         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8233     return SDValue();
8234   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8235   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8236     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8237       return SDValue();
8238   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8239     if (idx != AArch64::dsub)
8240       return SDValue();
8241     // The dsub reference is equivalent to a lane zero subvector reference.
8242     idx = 0;
8243   }
8244   // Look through the bitcast of the input to the extract.
8245   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8246     return SDValue();
8247   SDValue Source = Op0->getOperand(0)->getOperand(0);
8248   // If the source type has twice the number of elements as our destination
8249   // type, we know this is an extract of the high or low half of the vector.
8250   EVT SVT = Source->getValueType(0);
8251   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8252     return SDValue();
8253 
8254   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8255 
8256   // Create the simplified form to just extract the low or high half of the
8257   // vector directly rather than bothering with the bitcasts.
8258   SDLoc dl(N);
8259   unsigned NumElements = VT.getVectorNumElements();
8260   if (idx) {
8261     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8262     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8263   } else {
8264     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8265     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8266                                       Source, SubReg),
8267                    0);
8268   }
8269 }
8270 
8271 static SDValue performConcatVectorsCombine(SDNode *N,
8272                                            TargetLowering::DAGCombinerInfo &DCI,
8273                                            SelectionDAG &DAG) {
8274   SDLoc dl(N);
8275   EVT VT = N->getValueType(0);
8276   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8277 
8278   // Optimize concat_vectors of truncated vectors, where the intermediate
8279   // type is illegal, to avoid said illegality,  e.g.,
8280   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8281   //                          (v2i16 (truncate (v2i64)))))
8282   // ->
8283   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8284   //                                    (v4i32 (bitcast (v2i64))),
8285   //                                    <0, 2, 4, 6>)))
8286   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8287   // on both input and result type, so we might generate worse code.
8288   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8289   if (N->getNumOperands() == 2 &&
8290       N0->getOpcode() == ISD::TRUNCATE &&
8291       N1->getOpcode() == ISD::TRUNCATE) {
8292     SDValue N00 = N0->getOperand(0);
8293     SDValue N10 = N1->getOperand(0);
8294     EVT N00VT = N00.getValueType();
8295 
8296     if (N00VT == N10.getValueType() &&
8297         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8298         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8299       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8300       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8301       for (size_t i = 0; i < Mask.size(); ++i)
8302         Mask[i] = i * 2;
8303       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8304                          DAG.getVectorShuffle(
8305                              MidVT, dl,
8306                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8307                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8308     }
8309   }
8310 
8311   // Wait 'til after everything is legalized to try this. That way we have
8312   // legal vector types and such.
8313   if (DCI.isBeforeLegalizeOps())
8314     return SDValue();
8315 
8316   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8317   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8318   // canonicalise to that.
8319   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8320     assert(VT.getScalarSizeInBits() == 64);
8321     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8322                        DAG.getConstant(0, dl, MVT::i64));
8323   }
8324 
8325   // Canonicalise concat_vectors so that the right-hand vector has as few
8326   // bit-casts as possible before its real operation. The primary matching
8327   // destination for these operations will be the narrowing "2" instructions,
8328   // which depend on the operation being performed on this right-hand vector.
8329   // For example,
8330   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8331   // becomes
8332   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8333 
8334   if (N1->getOpcode() != ISD::BITCAST)
8335     return SDValue();
8336   SDValue RHS = N1->getOperand(0);
8337   MVT RHSTy = RHS.getValueType().getSimpleVT();
8338   // If the RHS is not a vector, this is not the pattern we're looking for.
8339   if (!RHSTy.isVector())
8340     return SDValue();
8341 
8342   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8343 
8344   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8345                                   RHSTy.getVectorNumElements() * 2);
8346   return DAG.getNode(ISD::BITCAST, dl, VT,
8347                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8348                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8349                                  RHS));
8350 }
8351 
8352 static SDValue tryCombineFixedPointConvert(SDNode *N,
8353                                            TargetLowering::DAGCombinerInfo &DCI,
8354                                            SelectionDAG &DAG) {
8355   // Wait 'til after everything is legalized to try this. That way we have
8356   // legal vector types and such.
8357   if (DCI.isBeforeLegalizeOps())
8358     return SDValue();
8359   // Transform a scalar conversion of a value from a lane extract into a
8360   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8361   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8362   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8363   //
8364   // The second form interacts better with instruction selection and the
8365   // register allocator to avoid cross-class register copies that aren't
8366   // coalescable due to a lane reference.
8367 
8368   // Check the operand and see if it originates from a lane extract.
8369   SDValue Op1 = N->getOperand(1);
8370   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8371     // Yep, no additional predication needed. Perform the transform.
8372     SDValue IID = N->getOperand(0);
8373     SDValue Shift = N->getOperand(2);
8374     SDValue Vec = Op1.getOperand(0);
8375     SDValue Lane = Op1.getOperand(1);
8376     EVT ResTy = N->getValueType(0);
8377     EVT VecResTy;
8378     SDLoc DL(N);
8379 
8380     // The vector width should be 128 bits by the time we get here, even
8381     // if it started as 64 bits (the extract_vector handling will have
8382     // done so).
8383     assert(Vec.getValueSizeInBits() == 128 &&
8384            "unexpected vector size on extract_vector_elt!");
8385     if (Vec.getValueType() == MVT::v4i32)
8386       VecResTy = MVT::v4f32;
8387     else if (Vec.getValueType() == MVT::v2i64)
8388       VecResTy = MVT::v2f64;
8389     else
8390       llvm_unreachable("unexpected vector type!");
8391 
8392     SDValue Convert =
8393         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8394     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8395   }
8396   return SDValue();
8397 }
8398 
8399 // AArch64 high-vector "long" operations are formed by performing the non-high
8400 // version on an extract_subvector of each operand which gets the high half:
8401 //
8402 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8403 //
8404 // However, there are cases which don't have an extract_high explicitly, but
8405 // have another operation that can be made compatible with one for free. For
8406 // example:
8407 //
8408 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8409 //
8410 // This routine does the actual conversion of such DUPs, once outer routines
8411 // have determined that everything else is in order.
8412 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8413 // similarly here.
8414 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8415   switch (N.getOpcode()) {
8416   case AArch64ISD::DUP:
8417   case AArch64ISD::DUPLANE8:
8418   case AArch64ISD::DUPLANE16:
8419   case AArch64ISD::DUPLANE32:
8420   case AArch64ISD::DUPLANE64:
8421   case AArch64ISD::MOVI:
8422   case AArch64ISD::MOVIshift:
8423   case AArch64ISD::MOVIedit:
8424   case AArch64ISD::MOVImsl:
8425   case AArch64ISD::MVNIshift:
8426   case AArch64ISD::MVNImsl:
8427     break;
8428   default:
8429     // FMOV could be supported, but isn't very useful, as it would only occur
8430     // if you passed a bitcast' floating point immediate to an eligible long
8431     // integer op (addl, smull, ...).
8432     return SDValue();
8433   }
8434 
8435   MVT NarrowTy = N.getSimpleValueType();
8436   if (!NarrowTy.is64BitVector())
8437     return SDValue();
8438 
8439   MVT ElementTy = NarrowTy.getVectorElementType();
8440   unsigned NumElems = NarrowTy.getVectorNumElements();
8441   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8442 
8443   SDLoc dl(N);
8444   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8445                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8446                      DAG.getConstant(NumElems, dl, MVT::i64));
8447 }
8448 
8449 static bool isEssentiallyExtractSubvector(SDValue N) {
8450   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8451     return true;
8452 
8453   return N.getOpcode() == ISD::BITCAST &&
8454          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8455 }
8456 
8457 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8458 struct GenericSetCCInfo {
8459   const SDValue *Opnd0;
8460   const SDValue *Opnd1;
8461   ISD::CondCode CC;
8462 };
8463 
8464 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8465 struct AArch64SetCCInfo {
8466   const SDValue *Cmp;
8467   AArch64CC::CondCode CC;
8468 };
8469 
8470 /// \brief Helper structure to keep track of SetCC information.
8471 union SetCCInfo {
8472   GenericSetCCInfo Generic;
8473   AArch64SetCCInfo AArch64;
8474 };
8475 
8476 /// \brief Helper structure to be able to read SetCC information.  If set to
8477 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8478 /// GenericSetCCInfo.
8479 struct SetCCInfoAndKind {
8480   SetCCInfo Info;
8481   bool IsAArch64;
8482 };
8483 
8484 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8485 /// an
8486 /// AArch64 lowered one.
8487 /// \p SetCCInfo is filled accordingly.
8488 /// \post SetCCInfo is meanginfull only when this function returns true.
8489 /// \return True when Op is a kind of SET_CC operation.
8490 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8491   // If this is a setcc, this is straight forward.
8492   if (Op.getOpcode() == ISD::SETCC) {
8493     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8494     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8495     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8496     SetCCInfo.IsAArch64 = false;
8497     return true;
8498   }
8499   // Otherwise, check if this is a matching csel instruction.
8500   // In other words:
8501   // - csel 1, 0, cc
8502   // - csel 0, 1, !cc
8503   if (Op.getOpcode() != AArch64ISD::CSEL)
8504     return false;
8505   // Set the information about the operands.
8506   // TODO: we want the operands of the Cmp not the csel
8507   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8508   SetCCInfo.IsAArch64 = true;
8509   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8510       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8511 
8512   // Check that the operands matches the constraints:
8513   // (1) Both operands must be constants.
8514   // (2) One must be 1 and the other must be 0.
8515   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8516   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8517 
8518   // Check (1).
8519   if (!TValue || !FValue)
8520     return false;
8521 
8522   // Check (2).
8523   if (!TValue->isOne()) {
8524     // Update the comparison when we are interested in !cc.
8525     std::swap(TValue, FValue);
8526     SetCCInfo.Info.AArch64.CC =
8527         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8528   }
8529   return TValue->isOne() && FValue->isNullValue();
8530 }
8531 
8532 // Returns true if Op is setcc or zext of setcc.
8533 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8534   if (isSetCC(Op, Info))
8535     return true;
8536   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8537     isSetCC(Op->getOperand(0), Info));
8538 }
8539 
8540 // The folding we want to perform is:
8541 // (add x, [zext] (setcc cc ...) )
8542 //   -->
8543 // (csel x, (add x, 1), !cc ...)
8544 //
8545 // The latter will get matched to a CSINC instruction.
8546 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8547   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8548   SDValue LHS = Op->getOperand(0);
8549   SDValue RHS = Op->getOperand(1);
8550   SetCCInfoAndKind InfoAndKind;
8551 
8552   // If neither operand is a SET_CC, give up.
8553   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8554     std::swap(LHS, RHS);
8555     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8556       return SDValue();
8557   }
8558 
8559   // FIXME: This could be generatized to work for FP comparisons.
8560   EVT CmpVT = InfoAndKind.IsAArch64
8561                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8562                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8563   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8564     return SDValue();
8565 
8566   SDValue CCVal;
8567   SDValue Cmp;
8568   SDLoc dl(Op);
8569   if (InfoAndKind.IsAArch64) {
8570     CCVal = DAG.getConstant(
8571         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8572         MVT::i32);
8573     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8574   } else
8575     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8576                       *InfoAndKind.Info.Generic.Opnd1,
8577                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8578                       CCVal, DAG, dl);
8579 
8580   EVT VT = Op->getValueType(0);
8581   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8582   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8583 }
8584 
8585 // The basic add/sub long vector instructions have variants with "2" on the end
8586 // which act on the high-half of their inputs. They are normally matched by
8587 // patterns like:
8588 //
8589 // (add (zeroext (extract_high LHS)),
8590 //      (zeroext (extract_high RHS)))
8591 // -> uaddl2 vD, vN, vM
8592 //
8593 // However, if one of the extracts is something like a duplicate, this
8594 // instruction can still be used profitably. This function puts the DAG into a
8595 // more appropriate form for those patterns to trigger.
8596 static SDValue performAddSubLongCombine(SDNode *N,
8597                                         TargetLowering::DAGCombinerInfo &DCI,
8598                                         SelectionDAG &DAG) {
8599   if (DCI.isBeforeLegalizeOps())
8600     return SDValue();
8601 
8602   MVT VT = N->getSimpleValueType(0);
8603   if (!VT.is128BitVector()) {
8604     if (N->getOpcode() == ISD::ADD)
8605       return performSetccAddFolding(N, DAG);
8606     return SDValue();
8607   }
8608 
8609   // Make sure both branches are extended in the same way.
8610   SDValue LHS = N->getOperand(0);
8611   SDValue RHS = N->getOperand(1);
8612   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8613        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8614       LHS.getOpcode() != RHS.getOpcode())
8615     return SDValue();
8616 
8617   unsigned ExtType = LHS.getOpcode();
8618 
8619   // It's not worth doing if at least one of the inputs isn't already an
8620   // extract, but we don't know which it'll be so we have to try both.
8621   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8622     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8623     if (!RHS.getNode())
8624       return SDValue();
8625 
8626     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8627   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8628     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8629     if (!LHS.getNode())
8630       return SDValue();
8631 
8632     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8633   }
8634 
8635   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8636 }
8637 
8638 // Massage DAGs which we can use the high-half "long" operations on into
8639 // something isel will recognize better. E.g.
8640 //
8641 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8642 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8643 //                     (extract_high (v2i64 (dup128 scalar)))))
8644 //
8645 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8646                                        TargetLowering::DAGCombinerInfo &DCI,
8647                                        SelectionDAG &DAG) {
8648   if (DCI.isBeforeLegalizeOps())
8649     return SDValue();
8650 
8651   SDValue LHS = N->getOperand(1);
8652   SDValue RHS = N->getOperand(2);
8653   assert(LHS.getValueType().is64BitVector() &&
8654          RHS.getValueType().is64BitVector() &&
8655          "unexpected shape for long operation");
8656 
8657   // Either node could be a DUP, but it's not worth doing both of them (you'd
8658   // just as well use the non-high version) so look for a corresponding extract
8659   // operation on the other "wing".
8660   if (isEssentiallyExtractSubvector(LHS)) {
8661     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8662     if (!RHS.getNode())
8663       return SDValue();
8664   } else if (isEssentiallyExtractSubvector(RHS)) {
8665     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8666     if (!LHS.getNode())
8667       return SDValue();
8668   }
8669 
8670   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8671                      N->getOperand(0), LHS, RHS);
8672 }
8673 
8674 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8675   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8676   unsigned ElemBits = ElemTy.getSizeInBits();
8677 
8678   int64_t ShiftAmount;
8679   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8680     APInt SplatValue, SplatUndef;
8681     unsigned SplatBitSize;
8682     bool HasAnyUndefs;
8683     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8684                               HasAnyUndefs, ElemBits) ||
8685         SplatBitSize != ElemBits)
8686       return SDValue();
8687 
8688     ShiftAmount = SplatValue.getSExtValue();
8689   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8690     ShiftAmount = CVN->getSExtValue();
8691   } else
8692     return SDValue();
8693 
8694   unsigned Opcode;
8695   bool IsRightShift;
8696   switch (IID) {
8697   default:
8698     llvm_unreachable("Unknown shift intrinsic");
8699   case Intrinsic::aarch64_neon_sqshl:
8700     Opcode = AArch64ISD::SQSHL_I;
8701     IsRightShift = false;
8702     break;
8703   case Intrinsic::aarch64_neon_uqshl:
8704     Opcode = AArch64ISD::UQSHL_I;
8705     IsRightShift = false;
8706     break;
8707   case Intrinsic::aarch64_neon_srshl:
8708     Opcode = AArch64ISD::SRSHR_I;
8709     IsRightShift = true;
8710     break;
8711   case Intrinsic::aarch64_neon_urshl:
8712     Opcode = AArch64ISD::URSHR_I;
8713     IsRightShift = true;
8714     break;
8715   case Intrinsic::aarch64_neon_sqshlu:
8716     Opcode = AArch64ISD::SQSHLU_I;
8717     IsRightShift = false;
8718     break;
8719   }
8720 
8721   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8722     SDLoc dl(N);
8723     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8724                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8725   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8726     SDLoc dl(N);
8727     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8728                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8729   }
8730 
8731   return SDValue();
8732 }
8733 
8734 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8735 // the intrinsics must be legal and take an i32, this means there's almost
8736 // certainly going to be a zext in the DAG which we can eliminate.
8737 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8738   SDValue AndN = N->getOperand(2);
8739   if (AndN.getOpcode() != ISD::AND)
8740     return SDValue();
8741 
8742   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8743   if (!CMask || CMask->getZExtValue() != Mask)
8744     return SDValue();
8745 
8746   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8747                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8748 }
8749 
8750 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8751                                            SelectionDAG &DAG) {
8752   SDLoc dl(N);
8753   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8754                      DAG.getNode(Opc, dl,
8755                                  N->getOperand(1).getSimpleValueType(),
8756                                  N->getOperand(1)),
8757                      DAG.getConstant(0, dl, MVT::i64));
8758 }
8759 
8760 static SDValue performIntrinsicCombine(SDNode *N,
8761                                        TargetLowering::DAGCombinerInfo &DCI,
8762                                        const AArch64Subtarget *Subtarget) {
8763   SelectionDAG &DAG = DCI.DAG;
8764   unsigned IID = getIntrinsicID(N);
8765   switch (IID) {
8766   default:
8767     break;
8768   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8769   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8770     return tryCombineFixedPointConvert(N, DCI, DAG);
8771   case Intrinsic::aarch64_neon_saddv:
8772     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8773   case Intrinsic::aarch64_neon_uaddv:
8774     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8775   case Intrinsic::aarch64_neon_sminv:
8776     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8777   case Intrinsic::aarch64_neon_uminv:
8778     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8779   case Intrinsic::aarch64_neon_smaxv:
8780     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8781   case Intrinsic::aarch64_neon_umaxv:
8782     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8783   case Intrinsic::aarch64_neon_fmax:
8784     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8785                        N->getOperand(1), N->getOperand(2));
8786   case Intrinsic::aarch64_neon_fmin:
8787     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8788                        N->getOperand(1), N->getOperand(2));
8789   case Intrinsic::aarch64_neon_fmaxnm:
8790     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8791                        N->getOperand(1), N->getOperand(2));
8792   case Intrinsic::aarch64_neon_fminnm:
8793     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8794                        N->getOperand(1), N->getOperand(2));
8795   case Intrinsic::aarch64_neon_smull:
8796   case Intrinsic::aarch64_neon_umull:
8797   case Intrinsic::aarch64_neon_pmull:
8798   case Intrinsic::aarch64_neon_sqdmull:
8799     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8800   case Intrinsic::aarch64_neon_sqshl:
8801   case Intrinsic::aarch64_neon_uqshl:
8802   case Intrinsic::aarch64_neon_sqshlu:
8803   case Intrinsic::aarch64_neon_srshl:
8804   case Intrinsic::aarch64_neon_urshl:
8805     return tryCombineShiftImm(IID, N, DAG);
8806   case Intrinsic::aarch64_crc32b:
8807   case Intrinsic::aarch64_crc32cb:
8808     return tryCombineCRC32(0xff, N, DAG);
8809   case Intrinsic::aarch64_crc32h:
8810   case Intrinsic::aarch64_crc32ch:
8811     return tryCombineCRC32(0xffff, N, DAG);
8812   }
8813   return SDValue();
8814 }
8815 
8816 static SDValue performExtendCombine(SDNode *N,
8817                                     TargetLowering::DAGCombinerInfo &DCI,
8818                                     SelectionDAG &DAG) {
8819   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8820   // we can convert that DUP into another extract_high (of a bigger DUP), which
8821   // helps the backend to decide that an sabdl2 would be useful, saving a real
8822   // extract_high operation.
8823   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8824       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8825     SDNode *ABDNode = N->getOperand(0).getNode();
8826     unsigned IID = getIntrinsicID(ABDNode);
8827     if (IID == Intrinsic::aarch64_neon_sabd ||
8828         IID == Intrinsic::aarch64_neon_uabd) {
8829       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8830       if (!NewABD.getNode())
8831         return SDValue();
8832 
8833       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8834                          NewABD);
8835     }
8836   }
8837 
8838   // This is effectively a custom type legalization for AArch64.
8839   //
8840   // Type legalization will split an extend of a small, legal, type to a larger
8841   // illegal type by first splitting the destination type, often creating
8842   // illegal source types, which then get legalized in isel-confusing ways,
8843   // leading to really terrible codegen. E.g.,
8844   //   %result = v8i32 sext v8i8 %value
8845   // becomes
8846   //   %losrc = extract_subreg %value, ...
8847   //   %hisrc = extract_subreg %value, ...
8848   //   %lo = v4i32 sext v4i8 %losrc
8849   //   %hi = v4i32 sext v4i8 %hisrc
8850   // Things go rapidly downhill from there.
8851   //
8852   // For AArch64, the [sz]ext vector instructions can only go up one element
8853   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8854   // take two instructions.
8855   //
8856   // This implies that the most efficient way to do the extend from v8i8
8857   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8858   // the normal splitting to happen for the v8i16->v8i32.
8859 
8860   // This is pre-legalization to catch some cases where the default
8861   // type legalization will create ill-tempered code.
8862   if (!DCI.isBeforeLegalizeOps())
8863     return SDValue();
8864 
8865   // We're only interested in cleaning things up for non-legal vector types
8866   // here. If both the source and destination are legal, things will just
8867   // work naturally without any fiddling.
8868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8869   EVT ResVT = N->getValueType(0);
8870   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8871     return SDValue();
8872   // If the vector type isn't a simple VT, it's beyond the scope of what
8873   // we're  worried about here. Let legalization do its thing and hope for
8874   // the best.
8875   SDValue Src = N->getOperand(0);
8876   EVT SrcVT = Src->getValueType(0);
8877   if (!ResVT.isSimple() || !SrcVT.isSimple())
8878     return SDValue();
8879 
8880   // If the source VT is a 64-bit vector, we can play games and get the
8881   // better results we want.
8882   if (SrcVT.getSizeInBits() != 64)
8883     return SDValue();
8884 
8885   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
8886   unsigned ElementCount = SrcVT.getVectorNumElements();
8887   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8888   SDLoc DL(N);
8889   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8890 
8891   // Now split the rest of the operation into two halves, each with a 64
8892   // bit source.
8893   EVT LoVT, HiVT;
8894   SDValue Lo, Hi;
8895   unsigned NumElements = ResVT.getVectorNumElements();
8896   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8897   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8898                                  ResVT.getVectorElementType(), NumElements / 2);
8899 
8900   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8901                                LoVT.getVectorNumElements());
8902   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8903                    DAG.getConstant(0, DL, MVT::i64));
8904   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8905                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8906   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8907   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8908 
8909   // Now combine the parts back together so we still have a single result
8910   // like the combiner expects.
8911   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8912 }
8913 
8914 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
8915                                SDValue SplatVal, unsigned NumVecElts) {
8916   unsigned OrigAlignment = St.getAlignment();
8917   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
8918 
8919   // Create scalar stores. This is at least as good as the code sequence for a
8920   // split unaligned store which is a dup.s, ext.b, and two stores.
8921   // Most of the time the three stores should be replaced by store pair
8922   // instructions (stp).
8923   SDLoc DL(&St);
8924   SDValue BasePtr = St.getBasePtr();
8925   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
8926   SDValue NewST1 =
8927       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
8928                    OrigAlignment, St.getMemOperand()->getFlags());
8929 
8930   unsigned Offset = EltOffset;
8931   while (--NumVecElts) {
8932     unsigned Alignment = MinAlign(OrigAlignment, Offset);
8933     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8934                                     DAG.getConstant(Offset, DL, MVT::i64));
8935     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8936                           PtrInfo.getWithOffset(Offset), Alignment,
8937                           St.getMemOperand()->getFlags());
8938     Offset += EltOffset;
8939   }
8940   return NewST1;
8941 }
8942 
8943 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
8944 /// load store optimizer pass will merge them to store pair stores.  This should
8945 /// be better than a movi to create the vector zero followed by a vector store
8946 /// if the zero constant is not re-used, since one instructions and one register
8947 /// live range will be removed.
8948 ///
8949 /// For example, the final generated code should be:
8950 ///
8951 ///   stp xzr, xzr, [x0]
8952 ///
8953 /// instead of:
8954 ///
8955 ///   movi v0.2d, #0
8956 ///   str q0, [x0]
8957 ///
8958 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8959   SDValue StVal = St.getValue();
8960   EVT VT = StVal.getValueType();
8961 
8962   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
8963   // 2, 3 or 4 i32 elements.
8964   int NumVecElts = VT.getVectorNumElements();
8965   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
8966          VT.getVectorElementType().getSizeInBits() == 64) ||
8967         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
8968          VT.getVectorElementType().getSizeInBits() == 32)))
8969     return SDValue();
8970 
8971   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
8972     return SDValue();
8973 
8974   // If the zero constant has more than one use then the vector store could be
8975   // better since the constant mov will be amortized and stp q instructions
8976   // should be able to be formed.
8977   if (!StVal.hasOneUse())
8978     return SDValue();
8979 
8980   // If the immediate offset of the address operand is too large for the stp
8981   // instruction, then bail out.
8982   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
8983     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
8984     if (Offset < -512 || Offset > 504)
8985       return SDValue();
8986   }
8987 
8988   for (int I = 0; I < NumVecElts; ++I) {
8989     SDValue EltVal = StVal.getOperand(I);
8990     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
8991       return SDValue();
8992   }
8993 
8994   // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
8995   // undoing this transformation.
8996   SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
8997                          ? DAG.getRegister(AArch64::WZR, MVT::i32)
8998                          : DAG.getRegister(AArch64::XZR, MVT::i64);
8999   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9000 }
9001 
9002 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9003 /// value. The load store optimizer pass will merge them to store pair stores.
9004 /// This has better performance than a splat of the scalar followed by a split
9005 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9006 /// followed by an ext.b and two stores.
9007 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9008   SDValue StVal = St.getValue();
9009   EVT VT = StVal.getValueType();
9010 
9011   // Don't replace floating point stores, they possibly won't be transformed to
9012   // stp because of the store pair suppress pass.
9013   if (VT.isFloatingPoint())
9014     return SDValue();
9015 
9016   // We can express a splat as store pair(s) for 2 or 4 elements.
9017   unsigned NumVecElts = VT.getVectorNumElements();
9018   if (NumVecElts != 4 && NumVecElts != 2)
9019     return SDValue();
9020 
9021   // Check that this is a splat.
9022   // Make sure that each of the relevant vector element locations are inserted
9023   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9024   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9025   SDValue SplatVal;
9026   for (unsigned I = 0; I < NumVecElts; ++I) {
9027     // Check for insert vector elements.
9028     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9029       return SDValue();
9030 
9031     // Check that same value is inserted at each vector element.
9032     if (I == 0)
9033       SplatVal = StVal.getOperand(1);
9034     else if (StVal.getOperand(1) != SplatVal)
9035       return SDValue();
9036 
9037     // Check insert element index.
9038     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9039     if (!CIndex)
9040       return SDValue();
9041     uint64_t IndexVal = CIndex->getZExtValue();
9042     if (IndexVal >= NumVecElts)
9043       return SDValue();
9044     IndexNotInserted.reset(IndexVal);
9045 
9046     StVal = StVal.getOperand(0);
9047   }
9048   // Check that all vector element locations were inserted to.
9049   if (IndexNotInserted.any())
9050       return SDValue();
9051 
9052   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9053 }
9054 
9055 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9056                            SelectionDAG &DAG,
9057                            const AArch64Subtarget *Subtarget) {
9058   if (!DCI.isBeforeLegalize())
9059     return SDValue();
9060 
9061   StoreSDNode *S = cast<StoreSDNode>(N);
9062   if (S->isVolatile())
9063     return SDValue();
9064 
9065   SDValue StVal = S->getValue();
9066   EVT VT = StVal.getValueType();
9067   if (!VT.isVector())
9068     return SDValue();
9069 
9070   // If we get a splat of zeros, convert this vector store to a store of
9071   // scalars. They will be merged into store pairs of xzr thereby removing one
9072   // instruction and one register.
9073   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9074     return ReplacedZeroSplat;
9075 
9076   // FIXME: The logic for deciding if an unaligned store should be split should
9077   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9078   // a call to that function here.
9079 
9080   if (!Subtarget->isMisaligned128StoreSlow())
9081     return SDValue();
9082 
9083   // Don't split at -Oz.
9084   if (DAG.getMachineFunction().getFunction()->optForMinSize())
9085     return SDValue();
9086 
9087   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9088   // those up regresses performance on micro-benchmarks and olden/bh.
9089   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9090     return SDValue();
9091 
9092   // Split unaligned 16B stores. They are terrible for performance.
9093   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9094   // extensions can use this to mark that it does not want splitting to happen
9095   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9096   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9097   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9098       S->getAlignment() <= 2)
9099     return SDValue();
9100 
9101   // If we get a splat of a scalar convert this vector store to a store of
9102   // scalars. They will be merged into store pairs thereby removing two
9103   // instructions.
9104   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9105     return ReplacedSplat;
9106 
9107   SDLoc DL(S);
9108   unsigned NumElts = VT.getVectorNumElements() / 2;
9109   // Split VT into two.
9110   EVT HalfVT =
9111       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9112   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9113                                    DAG.getConstant(0, DL, MVT::i64));
9114   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9115                                    DAG.getConstant(NumElts, DL, MVT::i64));
9116   SDValue BasePtr = S->getBasePtr();
9117   SDValue NewST1 =
9118       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9119                    S->getAlignment(), S->getMemOperand()->getFlags());
9120   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9121                                   DAG.getConstant(8, DL, MVT::i64));
9122   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9123                       S->getPointerInfo(), S->getAlignment(),
9124                       S->getMemOperand()->getFlags());
9125 }
9126 
9127 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9128 /// post-increment LD1R.
9129 static SDValue performPostLD1Combine(SDNode *N,
9130                                      TargetLowering::DAGCombinerInfo &DCI,
9131                                      bool IsLaneOp) {
9132   if (DCI.isBeforeLegalizeOps())
9133     return SDValue();
9134 
9135   SelectionDAG &DAG = DCI.DAG;
9136   EVT VT = N->getValueType(0);
9137 
9138   unsigned LoadIdx = IsLaneOp ? 1 : 0;
9139   SDNode *LD = N->getOperand(LoadIdx).getNode();
9140   // If it is not LOAD, can not do such combine.
9141   if (LD->getOpcode() != ISD::LOAD)
9142     return SDValue();
9143 
9144   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9145   EVT MemVT = LoadSDN->getMemoryVT();
9146   // Check if memory operand is the same type as the vector element.
9147   if (MemVT != VT.getVectorElementType())
9148     return SDValue();
9149 
9150   // Check if there are other uses. If so, do not combine as it will introduce
9151   // an extra load.
9152   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9153        ++UI) {
9154     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9155       continue;
9156     if (*UI != N)
9157       return SDValue();
9158   }
9159 
9160   SDValue Addr = LD->getOperand(1);
9161   SDValue Vector = N->getOperand(0);
9162   // Search for a use of the address operand that is an increment.
9163   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9164        Addr.getNode()->use_end(); UI != UE; ++UI) {
9165     SDNode *User = *UI;
9166     if (User->getOpcode() != ISD::ADD
9167         || UI.getUse().getResNo() != Addr.getResNo())
9168       continue;
9169 
9170     // Check that the add is independent of the load.  Otherwise, folding it
9171     // would create a cycle.
9172     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9173       continue;
9174     // Also check that add is not used in the vector operand.  This would also
9175     // create a cycle.
9176     if (User->isPredecessorOf(Vector.getNode()))
9177       continue;
9178 
9179     // If the increment is a constant, it must match the memory ref size.
9180     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9181     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9182       uint32_t IncVal = CInc->getZExtValue();
9183       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9184       if (IncVal != NumBytes)
9185         continue;
9186       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9187     }
9188 
9189     // Finally, check that the vector doesn't depend on the load.
9190     // Again, this would create a cycle.
9191     // The load depending on the vector is fine, as that's the case for the
9192     // LD1*post we'll eventually generate anyway.
9193     if (LoadSDN->isPredecessorOf(Vector.getNode()))
9194       continue;
9195 
9196     SmallVector<SDValue, 8> Ops;
9197     Ops.push_back(LD->getOperand(0));  // Chain
9198     if (IsLaneOp) {
9199       Ops.push_back(Vector);           // The vector to be inserted
9200       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9201     }
9202     Ops.push_back(Addr);
9203     Ops.push_back(Inc);
9204 
9205     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9206     SDVTList SDTys = DAG.getVTList(Tys);
9207     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9208     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9209                                            MemVT,
9210                                            LoadSDN->getMemOperand());
9211 
9212     // Update the uses.
9213     SDValue NewResults[] = {
9214         SDValue(LD, 0),            // The result of load
9215         SDValue(UpdN.getNode(), 2) // Chain
9216     };
9217     DCI.CombineTo(LD, NewResults);
9218     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
9219     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
9220 
9221     break;
9222   }
9223   return SDValue();
9224 }
9225 
9226 /// Simplify \Addr given that the top byte of it is ignored by HW during
9227 /// address translation.
9228 static bool performTBISimplification(SDValue Addr,
9229                                      TargetLowering::DAGCombinerInfo &DCI,
9230                                      SelectionDAG &DAG) {
9231   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9232   APInt KnownZero, KnownOne;
9233   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9234                                         DCI.isBeforeLegalizeOps());
9235   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9236   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9237     DCI.CommitTargetLoweringOpt(TLO);
9238     return true;
9239   }
9240   return false;
9241 }
9242 
9243 static SDValue performSTORECombine(SDNode *N,
9244                                    TargetLowering::DAGCombinerInfo &DCI,
9245                                    SelectionDAG &DAG,
9246                                    const AArch64Subtarget *Subtarget) {
9247   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9248     return Split;
9249 
9250   if (Subtarget->supportsAddressTopByteIgnored() &&
9251       performTBISimplification(N->getOperand(2), DCI, DAG))
9252     return SDValue(N, 0);
9253 
9254   return SDValue();
9255 }
9256 
9257   /// This function handles the log2-shuffle pattern produced by the
9258 /// LoopVectorizer for the across vector reduction. It consists of
9259 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9260 /// are reduced, where s is an induction variable from 0 to
9261 /// log2(NumVectorElements).
9262 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9263                                                      unsigned Op,
9264                                                      SelectionDAG &DAG) {
9265   EVT VTy = OpV->getOperand(0).getValueType();
9266   if (!VTy.isVector())
9267     return SDValue();
9268 
9269   int NumVecElts = VTy.getVectorNumElements();
9270   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9271     if (NumVecElts != 4)
9272       return SDValue();
9273   } else {
9274     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9275       return SDValue();
9276   }
9277 
9278   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
9279   SDValue PreOp = OpV;
9280   // Iterate over each step of the across vector reduction.
9281   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9282     SDValue CurOp = PreOp.getOperand(0);
9283     SDValue Shuffle = PreOp.getOperand(1);
9284     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9285       // Try to swap the 1st and 2nd operand as add and min/max instructions
9286       // are commutative.
9287       CurOp = PreOp.getOperand(1);
9288       Shuffle = PreOp.getOperand(0);
9289       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9290         return SDValue();
9291     }
9292 
9293     // Check if the input vector is fed by the operator we want to handle,
9294     // except the last step; the very first input vector is not necessarily
9295     // the same operator we are handling.
9296     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9297       return SDValue();
9298 
9299     // Check if it forms one step of the across vector reduction.
9300     // E.g.,
9301     //   %cur = add %1, %0
9302     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
9303     //   %pre = add %cur, %shuffle
9304     if (Shuffle.getOperand(0) != CurOp)
9305       return SDValue();
9306 
9307     int NumMaskElts = 1 << CurStep;
9308     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9309     // Check mask values in each step.
9310     // We expect the shuffle mask in each step follows a specific pattern
9311     // denoted here by the <M, U> form, where M is a sequence of integers
9312     // starting from NumMaskElts, increasing by 1, and the number integers
9313     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9314     // of undef in U should be NumVecElts - NumMaskElts.
9315     // E.g., for <8 x i16>, mask values in each step should be :
9316     //   step 0 : <1,u,u,u,u,u,u,u>
9317     //   step 1 : <2,3,u,u,u,u,u,u>
9318     //   step 2 : <4,5,6,7,u,u,u,u>
9319     for (int i = 0; i < NumVecElts; ++i)
9320       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9321           (i >= NumMaskElts && !(Mask[i] < 0)))
9322         return SDValue();
9323 
9324     PreOp = CurOp;
9325   }
9326   unsigned Opcode;
9327   bool IsIntrinsic = false;
9328 
9329   switch (Op) {
9330   default:
9331     llvm_unreachable("Unexpected operator for across vector reduction");
9332   case ISD::ADD:
9333     Opcode = AArch64ISD::UADDV;
9334     break;
9335   case ISD::SMAX:
9336     Opcode = AArch64ISD::SMAXV;
9337     break;
9338   case ISD::UMAX:
9339     Opcode = AArch64ISD::UMAXV;
9340     break;
9341   case ISD::SMIN:
9342     Opcode = AArch64ISD::SMINV;
9343     break;
9344   case ISD::UMIN:
9345     Opcode = AArch64ISD::UMINV;
9346     break;
9347   case ISD::FMAXNUM:
9348     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9349     IsIntrinsic = true;
9350     break;
9351   case ISD::FMINNUM:
9352     Opcode = Intrinsic::aarch64_neon_fminnmv;
9353     IsIntrinsic = true;
9354     break;
9355   }
9356   SDLoc DL(N);
9357 
9358   return IsIntrinsic
9359              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9360                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9361              : DAG.getNode(
9362                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9363                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9364                    DAG.getConstant(0, DL, MVT::i64));
9365 }
9366 
9367 /// Target-specific DAG combine for the across vector min/max reductions.
9368 /// This function specifically handles the final clean-up step of the vector
9369 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9370 /// pattern, which narrows down and finds the final min/max value from all
9371 /// elements of the vector.
9372 /// For example, for a <16 x i8> vector :
9373 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9374 ///   %smax0 = smax %arr, svn0
9375 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9376 ///   %smax1 = smax %smax0, %svn1
9377 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9378 ///   %smax2 = smax %smax1, svn2
9379 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9380 ///   %sc = setcc %smax2, %svn3, gt
9381 ///   %n0 = extract_vector_elt %sc, #0
9382 ///   %n1 = extract_vector_elt %smax2, #0
9383 ///   %n2 = extract_vector_elt $smax2, #1
9384 ///   %result = select %n0, %n1, n2
9385 ///     becomes :
9386 ///   %1 = smaxv %0
9387 ///   %result = extract_vector_elt %1, 0
9388 static SDValue
9389 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9390                                         const AArch64Subtarget *Subtarget) {
9391   if (!Subtarget->hasNEON())
9392     return SDValue();
9393 
9394   SDValue N0 = N->getOperand(0);
9395   SDValue IfTrue = N->getOperand(1);
9396   SDValue IfFalse = N->getOperand(2);
9397 
9398   // Check if the SELECT merges up the final result of the min/max
9399   // from a vector.
9400   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9401       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9402       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9403     return SDValue();
9404 
9405   // Expect N0 is fed by SETCC.
9406   SDValue SetCC = N0.getOperand(0);
9407   EVT SetCCVT = SetCC.getValueType();
9408   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9409       SetCCVT.getVectorElementType() != MVT::i1)
9410     return SDValue();
9411 
9412   SDValue VectorOp = SetCC.getOperand(0);
9413   unsigned Op = VectorOp->getOpcode();
9414   // Check if the input vector is fed by the operator we want to handle.
9415   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9416       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9417     return SDValue();
9418 
9419   EVT VTy = VectorOp.getValueType();
9420   if (!VTy.isVector())
9421     return SDValue();
9422 
9423   if (VTy.getSizeInBits() < 64)
9424     return SDValue();
9425 
9426   EVT EltTy = VTy.getVectorElementType();
9427   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9428     if (EltTy != MVT::f32)
9429       return SDValue();
9430   } else {
9431     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9432       return SDValue();
9433   }
9434 
9435   // Check if extracting from the same vector.
9436   // For example,
9437   //   %sc = setcc %vector, %svn1, gt
9438   //   %n0 = extract_vector_elt %sc, #0
9439   //   %n1 = extract_vector_elt %vector, #0
9440   //   %n2 = extract_vector_elt $vector, #1
9441   if (!(VectorOp == IfTrue->getOperand(0) &&
9442         VectorOp == IfFalse->getOperand(0)))
9443     return SDValue();
9444 
9445   // Check if the condition code is matched with the operator type.
9446   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9447   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9448       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9449       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9450       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9451       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9452        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9453        CC != ISD::SETGE) ||
9454       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9455        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9456        CC != ISD::SETLE))
9457     return SDValue();
9458 
9459   // Expect to check only lane 0 from the vector SETCC.
9460   if (!isNullConstant(N0.getOperand(1)))
9461     return SDValue();
9462 
9463   // Expect to extract the true value from lane 0.
9464   if (!isNullConstant(IfTrue.getOperand(1)))
9465     return SDValue();
9466 
9467   // Expect to extract the false value from lane 1.
9468   if (!isOneConstant(IfFalse.getOperand(1)))
9469     return SDValue();
9470 
9471   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9472 }
9473 
9474 /// Target-specific DAG combine for the across vector add reduction.
9475 /// This function specifically handles the final clean-up step of the vector
9476 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9477 /// pattern, which adds all elements of a vector together.
9478 /// For example, for a <4 x i32> vector :
9479 ///   %1 = vector_shuffle %0, <2,3,u,u>
9480 ///   %2 = add %0, %1
9481 ///   %3 = vector_shuffle %2, <1,u,u,u>
9482 ///   %4 = add %2, %3
9483 ///   %result = extract_vector_elt %4, 0
9484 /// becomes :
9485 ///   %0 = uaddv %0
9486 ///   %result = extract_vector_elt %0, 0
9487 static SDValue
9488 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9489                                      const AArch64Subtarget *Subtarget) {
9490   if (!Subtarget->hasNEON())
9491     return SDValue();
9492   SDValue N0 = N->getOperand(0);
9493   SDValue N1 = N->getOperand(1);
9494 
9495   // Check if the input vector is fed by the ADD.
9496   if (N0->getOpcode() != ISD::ADD)
9497     return SDValue();
9498 
9499   // The vector extract idx must constant zero because we only expect the final
9500   // result of the reduction is placed in lane 0.
9501   if (!isNullConstant(N1))
9502     return SDValue();
9503 
9504   EVT VTy = N0.getValueType();
9505   if (!VTy.isVector())
9506     return SDValue();
9507 
9508   EVT EltTy = VTy.getVectorElementType();
9509   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9510     return SDValue();
9511 
9512   if (VTy.getSizeInBits() < 64)
9513     return SDValue();
9514 
9515   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9516 }
9517 
9518 /// Target-specific DAG combine function for NEON load/store intrinsics
9519 /// to merge base address updates.
9520 static SDValue performNEONPostLDSTCombine(SDNode *N,
9521                                           TargetLowering::DAGCombinerInfo &DCI,
9522                                           SelectionDAG &DAG) {
9523   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9524     return SDValue();
9525 
9526   unsigned AddrOpIdx = N->getNumOperands() - 1;
9527   SDValue Addr = N->getOperand(AddrOpIdx);
9528 
9529   // Search for a use of the address operand that is an increment.
9530   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9531        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9532     SDNode *User = *UI;
9533     if (User->getOpcode() != ISD::ADD ||
9534         UI.getUse().getResNo() != Addr.getResNo())
9535       continue;
9536 
9537     // Check that the add is independent of the load/store.  Otherwise, folding
9538     // it would create a cycle.
9539     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9540       continue;
9541 
9542     // Find the new opcode for the updating load/store.
9543     bool IsStore = false;
9544     bool IsLaneOp = false;
9545     bool IsDupOp = false;
9546     unsigned NewOpc = 0;
9547     unsigned NumVecs = 0;
9548     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9549     switch (IntNo) {
9550     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9551     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9552       NumVecs = 2; break;
9553     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9554       NumVecs = 3; break;
9555     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9556       NumVecs = 4; break;
9557     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9558       NumVecs = 2; IsStore = true; break;
9559     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9560       NumVecs = 3; IsStore = true; break;
9561     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9562       NumVecs = 4; IsStore = true; break;
9563     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9564       NumVecs = 2; break;
9565     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9566       NumVecs = 3; break;
9567     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9568       NumVecs = 4; break;
9569     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9570       NumVecs = 2; IsStore = true; break;
9571     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9572       NumVecs = 3; IsStore = true; break;
9573     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9574       NumVecs = 4; IsStore = true; break;
9575     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9576       NumVecs = 2; IsDupOp = true; break;
9577     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9578       NumVecs = 3; IsDupOp = true; break;
9579     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9580       NumVecs = 4; IsDupOp = true; break;
9581     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9582       NumVecs = 2; IsLaneOp = true; break;
9583     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9584       NumVecs = 3; IsLaneOp = true; break;
9585     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9586       NumVecs = 4; IsLaneOp = true; break;
9587     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9588       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9589     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9590       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9591     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9592       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9593     }
9594 
9595     EVT VecTy;
9596     if (IsStore)
9597       VecTy = N->getOperand(2).getValueType();
9598     else
9599       VecTy = N->getValueType(0);
9600 
9601     // If the increment is a constant, it must match the memory ref size.
9602     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9603     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9604       uint32_t IncVal = CInc->getZExtValue();
9605       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9606       if (IsLaneOp || IsDupOp)
9607         NumBytes /= VecTy.getVectorNumElements();
9608       if (IncVal != NumBytes)
9609         continue;
9610       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9611     }
9612     SmallVector<SDValue, 8> Ops;
9613     Ops.push_back(N->getOperand(0)); // Incoming chain
9614     // Load lane and store have vector list as input.
9615     if (IsLaneOp || IsStore)
9616       for (unsigned i = 2; i < AddrOpIdx; ++i)
9617         Ops.push_back(N->getOperand(i));
9618     Ops.push_back(Addr); // Base register
9619     Ops.push_back(Inc);
9620 
9621     // Return Types.
9622     EVT Tys[6];
9623     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9624     unsigned n;
9625     for (n = 0; n < NumResultVecs; ++n)
9626       Tys[n] = VecTy;
9627     Tys[n++] = MVT::i64;  // Type of write back register
9628     Tys[n] = MVT::Other;  // Type of the chain
9629     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9630 
9631     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9632     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9633                                            MemInt->getMemoryVT(),
9634                                            MemInt->getMemOperand());
9635 
9636     // Update the uses.
9637     std::vector<SDValue> NewResults;
9638     for (unsigned i = 0; i < NumResultVecs; ++i) {
9639       NewResults.push_back(SDValue(UpdN.getNode(), i));
9640     }
9641     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9642     DCI.CombineTo(N, NewResults);
9643     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9644 
9645     break;
9646   }
9647   return SDValue();
9648 }
9649 
9650 // Checks to see if the value is the prescribed width and returns information
9651 // about its extension mode.
9652 static
9653 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9654   ExtType = ISD::NON_EXTLOAD;
9655   switch(V.getNode()->getOpcode()) {
9656   default:
9657     return false;
9658   case ISD::LOAD: {
9659     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9660     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9661        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9662       ExtType = LoadNode->getExtensionType();
9663       return true;
9664     }
9665     return false;
9666   }
9667   case ISD::AssertSext: {
9668     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9669     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9670        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9671       ExtType = ISD::SEXTLOAD;
9672       return true;
9673     }
9674     return false;
9675   }
9676   case ISD::AssertZext: {
9677     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9678     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9679        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9680       ExtType = ISD::ZEXTLOAD;
9681       return true;
9682     }
9683     return false;
9684   }
9685   case ISD::Constant:
9686   case ISD::TargetConstant: {
9687     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9688            1LL << (width - 1);
9689   }
9690   }
9691 
9692   return true;
9693 }
9694 
9695 // This function does a whole lot of voodoo to determine if the tests are
9696 // equivalent without and with a mask. Essentially what happens is that given a
9697 // DAG resembling:
9698 //
9699 //  +-------------+ +-------------+ +-------------+ +-------------+
9700 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9701 //  +-------------+ +-------------+ +-------------+ +-------------+
9702 //           |           |           |               |
9703 //           V           V           |    +----------+
9704 //          +-------------+  +----+  |    |
9705 //          |     ADD     |  |0xff|  |    |
9706 //          +-------------+  +----+  |    |
9707 //                  |           |    |    |
9708 //                  V           V    |    |
9709 //                 +-------------+   |    |
9710 //                 |     AND     |   |    |
9711 //                 +-------------+   |    |
9712 //                      |            |    |
9713 //                      +-----+      |    |
9714 //                            |      |    |
9715 //                            V      V    V
9716 //                           +-------------+
9717 //                           |     CMP     |
9718 //                           +-------------+
9719 //
9720 // The AND node may be safely removed for some combinations of inputs. In
9721 // particular we need to take into account the extension type of the Input,
9722 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9723 // width of the input (this can work for any width inputs, the above graph is
9724 // specific to 8 bits.
9725 //
9726 // The specific equations were worked out by generating output tables for each
9727 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9728 // problem was simplified by working with 4 bit inputs, which means we only
9729 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9730 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9731 // patterns present in both extensions (0,7). For every distinct set of
9732 // AddConstant and CompConstants bit patterns we can consider the masked and
9733 // unmasked versions to be equivalent if the result of this function is true for
9734 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9735 //
9736 //   sub      w8, w0, w1
9737 //   and      w10, w8, #0x0f
9738 //   cmp      w8, w2
9739 //   cset     w9, AArch64CC
9740 //   cmp      w10, w2
9741 //   cset     w11, AArch64CC
9742 //   cmp      w9, w11
9743 //   cset     w0, eq
9744 //   ret
9745 //
9746 // Since the above function shows when the outputs are equivalent it defines
9747 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9748 // would be expensive to run during compiles. The equations below were written
9749 // in a test harness that confirmed they gave equivalent outputs to the above
9750 // for all inputs function, so they can be used determine if the removal is
9751 // legal instead.
9752 //
9753 // isEquivalentMaskless() is the code for testing if the AND can be removed
9754 // factored out of the DAG recognition as the DAG can take several forms.
9755 
9756 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9757                                  ISD::LoadExtType ExtType, int AddConstant,
9758                                  int CompConstant) {
9759   // By being careful about our equations and only writing the in term
9760   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9761   // make them generally applicable to all bit widths.
9762   int MaxUInt = (1 << width);
9763 
9764   // For the purposes of these comparisons sign extending the type is
9765   // equivalent to zero extending the add and displacing it by half the integer
9766   // width. Provided we are careful and make sure our equations are valid over
9767   // the whole range we can just adjust the input and avoid writing equations
9768   // for sign extended inputs.
9769   if (ExtType == ISD::SEXTLOAD)
9770     AddConstant -= (1 << (width-1));
9771 
9772   switch(CC) {
9773   case AArch64CC::LE:
9774   case AArch64CC::GT:
9775     if ((AddConstant == 0) ||
9776         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9777         (AddConstant >= 0 && CompConstant < 0) ||
9778         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9779       return true;
9780     break;
9781   case AArch64CC::LT:
9782   case AArch64CC::GE:
9783     if ((AddConstant == 0) ||
9784         (AddConstant >= 0 && CompConstant <= 0) ||
9785         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9786       return true;
9787     break;
9788   case AArch64CC::HI:
9789   case AArch64CC::LS:
9790     if ((AddConstant >= 0 && CompConstant < 0) ||
9791        (AddConstant <= 0 && CompConstant >= -1 &&
9792         CompConstant < AddConstant + MaxUInt))
9793       return true;
9794    break;
9795   case AArch64CC::PL:
9796   case AArch64CC::MI:
9797     if ((AddConstant == 0) ||
9798         (AddConstant > 0 && CompConstant <= 0) ||
9799         (AddConstant < 0 && CompConstant <= AddConstant))
9800       return true;
9801     break;
9802   case AArch64CC::LO:
9803   case AArch64CC::HS:
9804     if ((AddConstant >= 0 && CompConstant <= 0) ||
9805         (AddConstant <= 0 && CompConstant >= 0 &&
9806          CompConstant <= AddConstant + MaxUInt))
9807       return true;
9808     break;
9809   case AArch64CC::EQ:
9810   case AArch64CC::NE:
9811     if ((AddConstant > 0 && CompConstant < 0) ||
9812         (AddConstant < 0 && CompConstant >= 0 &&
9813          CompConstant < AddConstant + MaxUInt) ||
9814         (AddConstant >= 0 && CompConstant >= 0 &&
9815          CompConstant >= AddConstant) ||
9816         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9817       return true;
9818     break;
9819   case AArch64CC::VS:
9820   case AArch64CC::VC:
9821   case AArch64CC::AL:
9822   case AArch64CC::NV:
9823     return true;
9824   case AArch64CC::Invalid:
9825     break;
9826   }
9827 
9828   return false;
9829 }
9830 
9831 static
9832 SDValue performCONDCombine(SDNode *N,
9833                            TargetLowering::DAGCombinerInfo &DCI,
9834                            SelectionDAG &DAG, unsigned CCIndex,
9835                            unsigned CmpIndex) {
9836   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9837   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9838   unsigned CondOpcode = SubsNode->getOpcode();
9839 
9840   if (CondOpcode != AArch64ISD::SUBS)
9841     return SDValue();
9842 
9843   // There is a SUBS feeding this condition. Is it fed by a mask we can
9844   // use?
9845 
9846   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9847   unsigned MaskBits = 0;
9848 
9849   if (AndNode->getOpcode() != ISD::AND)
9850     return SDValue();
9851 
9852   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9853     uint32_t CNV = CN->getZExtValue();
9854     if (CNV == 255)
9855       MaskBits = 8;
9856     else if (CNV == 65535)
9857       MaskBits = 16;
9858   }
9859 
9860   if (!MaskBits)
9861     return SDValue();
9862 
9863   SDValue AddValue = AndNode->getOperand(0);
9864 
9865   if (AddValue.getOpcode() != ISD::ADD)
9866     return SDValue();
9867 
9868   // The basic dag structure is correct, grab the inputs and validate them.
9869 
9870   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9871   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9872   SDValue SubsInputValue = SubsNode->getOperand(1);
9873 
9874   // The mask is present and the provenance of all the values is a smaller type,
9875   // lets see if the mask is superfluous.
9876 
9877   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9878       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9879     return SDValue();
9880 
9881   ISD::LoadExtType ExtType;
9882 
9883   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9884       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9885       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9886     return SDValue();
9887 
9888   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9889                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9890                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9891     return SDValue();
9892 
9893   // The AND is not necessary, remove it.
9894 
9895   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9896                                SubsNode->getValueType(1));
9897   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9898 
9899   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9900   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9901 
9902   return SDValue(N, 0);
9903 }
9904 
9905 // Optimize compare with zero and branch.
9906 static SDValue performBRCONDCombine(SDNode *N,
9907                                     TargetLowering::DAGCombinerInfo &DCI,
9908                                     SelectionDAG &DAG) {
9909   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9910     N = NV.getNode();
9911   SDValue Chain = N->getOperand(0);
9912   SDValue Dest = N->getOperand(1);
9913   SDValue CCVal = N->getOperand(2);
9914   SDValue Cmp = N->getOperand(3);
9915 
9916   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9917   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9918   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9919     return SDValue();
9920 
9921   unsigned CmpOpc = Cmp.getOpcode();
9922   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9923     return SDValue();
9924 
9925   // Only attempt folding if there is only one use of the flag and no use of the
9926   // value.
9927   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9928     return SDValue();
9929 
9930   SDValue LHS = Cmp.getOperand(0);
9931   SDValue RHS = Cmp.getOperand(1);
9932 
9933   assert(LHS.getValueType() == RHS.getValueType() &&
9934          "Expected the value type to be the same for both operands!");
9935   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9936     return SDValue();
9937 
9938   if (isNullConstant(LHS))
9939     std::swap(LHS, RHS);
9940 
9941   if (!isNullConstant(RHS))
9942     return SDValue();
9943 
9944   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9945       LHS.getOpcode() == ISD::SRL)
9946     return SDValue();
9947 
9948   // Fold the compare into the branch instruction.
9949   SDValue BR;
9950   if (CC == AArch64CC::EQ)
9951     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9952   else
9953     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9954 
9955   // Do not add new nodes to DAG combiner worklist.
9956   DCI.CombineTo(N, BR, false);
9957 
9958   return SDValue();
9959 }
9960 
9961 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9962 // as well as whether the test should be inverted.  This code is required to
9963 // catch these cases (as opposed to standard dag combines) because
9964 // AArch64ISD::TBZ is matched during legalization.
9965 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9966                                  SelectionDAG &DAG) {
9967 
9968   if (!Op->hasOneUse())
9969     return Op;
9970 
9971   // We don't handle undef/constant-fold cases below, as they should have
9972   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9973   // etc.)
9974 
9975   // (tbz (trunc x), b) -> (tbz x, b)
9976   // This case is just here to enable more of the below cases to be caught.
9977   if (Op->getOpcode() == ISD::TRUNCATE &&
9978       Bit < Op->getValueType(0).getSizeInBits()) {
9979     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9980   }
9981 
9982   if (Op->getNumOperands() != 2)
9983     return Op;
9984 
9985   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9986   if (!C)
9987     return Op;
9988 
9989   switch (Op->getOpcode()) {
9990   default:
9991     return Op;
9992 
9993   // (tbz (and x, m), b) -> (tbz x, b)
9994   case ISD::AND:
9995     if ((C->getZExtValue() >> Bit) & 1)
9996       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9997     return Op;
9998 
9999   // (tbz (shl x, c), b) -> (tbz x, b-c)
10000   case ISD::SHL:
10001     if (C->getZExtValue() <= Bit &&
10002         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10003       Bit = Bit - C->getZExtValue();
10004       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10005     }
10006     return Op;
10007 
10008   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10009   case ISD::SRA:
10010     Bit = Bit + C->getZExtValue();
10011     if (Bit >= Op->getValueType(0).getSizeInBits())
10012       Bit = Op->getValueType(0).getSizeInBits() - 1;
10013     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10014 
10015   // (tbz (srl x, c), b) -> (tbz x, b+c)
10016   case ISD::SRL:
10017     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10018       Bit = Bit + C->getZExtValue();
10019       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10020     }
10021     return Op;
10022 
10023   // (tbz (xor x, -1), b) -> (tbnz x, b)
10024   case ISD::XOR:
10025     if ((C->getZExtValue() >> Bit) & 1)
10026       Invert = !Invert;
10027     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10028   }
10029 }
10030 
10031 // Optimize test single bit zero/non-zero and branch.
10032 static SDValue performTBZCombine(SDNode *N,
10033                                  TargetLowering::DAGCombinerInfo &DCI,
10034                                  SelectionDAG &DAG) {
10035   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10036   bool Invert = false;
10037   SDValue TestSrc = N->getOperand(1);
10038   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10039 
10040   if (TestSrc == NewTestSrc)
10041     return SDValue();
10042 
10043   unsigned NewOpc = N->getOpcode();
10044   if (Invert) {
10045     if (NewOpc == AArch64ISD::TBZ)
10046       NewOpc = AArch64ISD::TBNZ;
10047     else {
10048       assert(NewOpc == AArch64ISD::TBNZ);
10049       NewOpc = AArch64ISD::TBZ;
10050     }
10051   }
10052 
10053   SDLoc DL(N);
10054   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10055                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10056 }
10057 
10058 // vselect (v1i1 setcc) ->
10059 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10060 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10061 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10062 // such VSELECT.
10063 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10064   SDValue N0 = N->getOperand(0);
10065   EVT CCVT = N0.getValueType();
10066 
10067   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10068       CCVT.getVectorElementType() != MVT::i1)
10069     return SDValue();
10070 
10071   EVT ResVT = N->getValueType(0);
10072   EVT CmpVT = N0.getOperand(0).getValueType();
10073   // Only combine when the result type is of the same size as the compared
10074   // operands.
10075   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10076     return SDValue();
10077 
10078   SDValue IfTrue = N->getOperand(1);
10079   SDValue IfFalse = N->getOperand(2);
10080   SDValue SetCC =
10081       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10082                    N0.getOperand(0), N0.getOperand(1),
10083                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10084   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10085                      IfTrue, IfFalse);
10086 }
10087 
10088 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10089 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10090 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10091 /// with a vector one followed by a DUP shuffle on the result.
10092 static SDValue performSelectCombine(SDNode *N,
10093                                     TargetLowering::DAGCombinerInfo &DCI) {
10094   SelectionDAG &DAG = DCI.DAG;
10095   SDValue N0 = N->getOperand(0);
10096   EVT ResVT = N->getValueType(0);
10097 
10098   if (N0.getOpcode() != ISD::SETCC)
10099     return SDValue();
10100 
10101   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10102   // scalar SetCCResultType. We also don't expect vectors, because we assume
10103   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10104   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10105          "Scalar-SETCC feeding SELECT has unexpected result type!");
10106 
10107   // If NumMaskElts == 0, the comparison is larger than select result. The
10108   // largest real NEON comparison is 64-bits per lane, which means the result is
10109   // at most 32-bits and an illegal vector. Just bail out for now.
10110   EVT SrcVT = N0.getOperand(0).getValueType();
10111 
10112   // Don't try to do this optimization when the setcc itself has i1 operands.
10113   // There are no legal vectors of i1, so this would be pointless.
10114   if (SrcVT == MVT::i1)
10115     return SDValue();
10116 
10117   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10118   if (!ResVT.isVector() || NumMaskElts == 0)
10119     return SDValue();
10120 
10121   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10122   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10123 
10124   // Also bail out if the vector CCVT isn't the same size as ResVT.
10125   // This can happen if the SETCC operand size doesn't divide the ResVT size
10126   // (e.g., f64 vs v3f32).
10127   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10128     return SDValue();
10129 
10130   // Make sure we didn't create illegal types, if we're not supposed to.
10131   assert(DCI.isBeforeLegalize() ||
10132          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10133 
10134   // First perform a vector comparison, where lane 0 is the one we're interested
10135   // in.
10136   SDLoc DL(N0);
10137   SDValue LHS =
10138       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10139   SDValue RHS =
10140       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10141   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10142 
10143   // Now duplicate the comparison mask we want across all other lanes.
10144   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10145   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10146   Mask = DAG.getNode(ISD::BITCAST, DL,
10147                      ResVT.changeVectorElementTypeToInteger(), Mask);
10148 
10149   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10150 }
10151 
10152 /// Get rid of unnecessary NVCASTs (that don't change the type).
10153 static SDValue performNVCASTCombine(SDNode *N) {
10154   if (N->getValueType(0) == N->getOperand(0).getValueType())
10155     return N->getOperand(0);
10156 
10157   return SDValue();
10158 }
10159 
10160 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10161                                                  DAGCombinerInfo &DCI) const {
10162   SelectionDAG &DAG = DCI.DAG;
10163   switch (N->getOpcode()) {
10164   default:
10165     break;
10166   case ISD::ADD:
10167   case ISD::SUB:
10168     return performAddSubLongCombine(N, DCI, DAG);
10169   case ISD::XOR:
10170     return performXorCombine(N, DAG, DCI, Subtarget);
10171   case ISD::MUL:
10172     return performMulCombine(N, DAG, DCI, Subtarget);
10173   case ISD::SINT_TO_FP:
10174   case ISD::UINT_TO_FP:
10175     return performIntToFpCombine(N, DAG, Subtarget);
10176   case ISD::FP_TO_SINT:
10177   case ISD::FP_TO_UINT:
10178     return performFpToIntCombine(N, DAG, DCI, Subtarget);
10179   case ISD::FDIV:
10180     return performFDivCombine(N, DAG, DCI, Subtarget);
10181   case ISD::OR:
10182     return performORCombine(N, DCI, Subtarget);
10183   case ISD::SRL:
10184     return performSRLCombine(N, DCI);
10185   case ISD::INTRINSIC_WO_CHAIN:
10186     return performIntrinsicCombine(N, DCI, Subtarget);
10187   case ISD::ANY_EXTEND:
10188   case ISD::ZERO_EXTEND:
10189   case ISD::SIGN_EXTEND:
10190     return performExtendCombine(N, DCI, DAG);
10191   case ISD::BITCAST:
10192     return performBitcastCombine(N, DCI, DAG);
10193   case ISD::CONCAT_VECTORS:
10194     return performConcatVectorsCombine(N, DCI, DAG);
10195   case ISD::SELECT: {
10196     SDValue RV = performSelectCombine(N, DCI);
10197     if (!RV.getNode())
10198       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10199     return RV;
10200   }
10201   case ISD::VSELECT:
10202     return performVSelectCombine(N, DCI.DAG);
10203   case ISD::LOAD:
10204     if (performTBISimplification(N->getOperand(1), DCI, DAG))
10205       return SDValue(N, 0);
10206     break;
10207   case ISD::STORE:
10208     return performSTORECombine(N, DCI, DAG, Subtarget);
10209   case AArch64ISD::BRCOND:
10210     return performBRCONDCombine(N, DCI, DAG);
10211   case AArch64ISD::TBNZ:
10212   case AArch64ISD::TBZ:
10213     return performTBZCombine(N, DCI, DAG);
10214   case AArch64ISD::CSEL:
10215     return performCONDCombine(N, DCI, DAG, 2, 3);
10216   case AArch64ISD::DUP:
10217     return performPostLD1Combine(N, DCI, false);
10218   case AArch64ISD::NVCAST:
10219     return performNVCASTCombine(N);
10220   case ISD::INSERT_VECTOR_ELT:
10221     return performPostLD1Combine(N, DCI, true);
10222   case ISD::EXTRACT_VECTOR_ELT:
10223     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
10224   case ISD::INTRINSIC_VOID:
10225   case ISD::INTRINSIC_W_CHAIN:
10226     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10227     case Intrinsic::aarch64_neon_ld2:
10228     case Intrinsic::aarch64_neon_ld3:
10229     case Intrinsic::aarch64_neon_ld4:
10230     case Intrinsic::aarch64_neon_ld1x2:
10231     case Intrinsic::aarch64_neon_ld1x3:
10232     case Intrinsic::aarch64_neon_ld1x4:
10233     case Intrinsic::aarch64_neon_ld2lane:
10234     case Intrinsic::aarch64_neon_ld3lane:
10235     case Intrinsic::aarch64_neon_ld4lane:
10236     case Intrinsic::aarch64_neon_ld2r:
10237     case Intrinsic::aarch64_neon_ld3r:
10238     case Intrinsic::aarch64_neon_ld4r:
10239     case Intrinsic::aarch64_neon_st2:
10240     case Intrinsic::aarch64_neon_st3:
10241     case Intrinsic::aarch64_neon_st4:
10242     case Intrinsic::aarch64_neon_st1x2:
10243     case Intrinsic::aarch64_neon_st1x3:
10244     case Intrinsic::aarch64_neon_st1x4:
10245     case Intrinsic::aarch64_neon_st2lane:
10246     case Intrinsic::aarch64_neon_st3lane:
10247     case Intrinsic::aarch64_neon_st4lane:
10248       return performNEONPostLDSTCombine(N, DCI, DAG);
10249     default:
10250       break;
10251     }
10252   }
10253   return SDValue();
10254 }
10255 
10256 // Check if the return value is used as only a return value, as otherwise
10257 // we can't perform a tail-call. In particular, we need to check for
10258 // target ISD nodes that are returns and any other "odd" constructs
10259 // that the generic analysis code won't necessarily catch.
10260 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10261                                                SDValue &Chain) const {
10262   if (N->getNumValues() != 1)
10263     return false;
10264   if (!N->hasNUsesOfValue(1, 0))
10265     return false;
10266 
10267   SDValue TCChain = Chain;
10268   SDNode *Copy = *N->use_begin();
10269   if (Copy->getOpcode() == ISD::CopyToReg) {
10270     // If the copy has a glue operand, we conservatively assume it isn't safe to
10271     // perform a tail call.
10272     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10273         MVT::Glue)
10274       return false;
10275     TCChain = Copy->getOperand(0);
10276   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10277     return false;
10278 
10279   bool HasRet = false;
10280   for (SDNode *Node : Copy->uses()) {
10281     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10282       return false;
10283     HasRet = true;
10284   }
10285 
10286   if (!HasRet)
10287     return false;
10288 
10289   Chain = TCChain;
10290   return true;
10291 }
10292 
10293 // Return whether the an instruction can potentially be optimized to a tail
10294 // call. This will cause the optimizers to attempt to move, or duplicate,
10295 // return instructions to help enable tail call optimizations for this
10296 // instruction.
10297 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
10298   return CI->isTailCall();
10299 }
10300 
10301 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10302                                                    SDValue &Offset,
10303                                                    ISD::MemIndexedMode &AM,
10304                                                    bool &IsInc,
10305                                                    SelectionDAG &DAG) const {
10306   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10307     return false;
10308 
10309   Base = Op->getOperand(0);
10310   // All of the indexed addressing mode instructions take a signed
10311   // 9 bit immediate offset.
10312   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10313     int64_t RHSC = RHS->getSExtValue();
10314     if (Op->getOpcode() == ISD::SUB)
10315       RHSC = -(uint64_t)RHSC;
10316     if (!isInt<9>(RHSC))
10317       return false;
10318     IsInc = (Op->getOpcode() == ISD::ADD);
10319     Offset = Op->getOperand(1);
10320     return true;
10321   }
10322   return false;
10323 }
10324 
10325 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10326                                                       SDValue &Offset,
10327                                                       ISD::MemIndexedMode &AM,
10328                                                       SelectionDAG &DAG) const {
10329   EVT VT;
10330   SDValue Ptr;
10331   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10332     VT = LD->getMemoryVT();
10333     Ptr = LD->getBasePtr();
10334   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10335     VT = ST->getMemoryVT();
10336     Ptr = ST->getBasePtr();
10337   } else
10338     return false;
10339 
10340   bool IsInc;
10341   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10342     return false;
10343   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10344   return true;
10345 }
10346 
10347 bool AArch64TargetLowering::getPostIndexedAddressParts(
10348     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10349     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10350   EVT VT;
10351   SDValue Ptr;
10352   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10353     VT = LD->getMemoryVT();
10354     Ptr = LD->getBasePtr();
10355   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10356     VT = ST->getMemoryVT();
10357     Ptr = ST->getBasePtr();
10358   } else
10359     return false;
10360 
10361   bool IsInc;
10362   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10363     return false;
10364   // Post-indexing updates the base, so it's not a valid transform
10365   // if that's not the same as the load's pointer.
10366   if (Ptr != Base)
10367     return false;
10368   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10369   return true;
10370 }
10371 
10372 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10373                                   SelectionDAG &DAG) {
10374   SDLoc DL(N);
10375   SDValue Op = N->getOperand(0);
10376 
10377   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10378     return;
10379 
10380   Op = SDValue(
10381       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10382                          DAG.getUNDEF(MVT::i32), Op,
10383                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10384       0);
10385   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10386   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10387 }
10388 
10389 static void ReplaceReductionResults(SDNode *N,
10390                                     SmallVectorImpl<SDValue> &Results,
10391                                     SelectionDAG &DAG, unsigned InterOp,
10392                                     unsigned AcrossOp) {
10393   EVT LoVT, HiVT;
10394   SDValue Lo, Hi;
10395   SDLoc dl(N);
10396   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10397   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10398   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10399   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10400   Results.push_back(SplitVal);
10401 }
10402 
10403 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10404   SDLoc DL(N);
10405   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10406   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10407                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10408                                        DAG.getConstant(64, DL, MVT::i64)));
10409   return std::make_pair(Lo, Hi);
10410 }
10411 
10412 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10413                                        SmallVectorImpl<SDValue> & Results,
10414                                        SelectionDAG &DAG) {
10415   assert(N->getValueType(0) == MVT::i128 &&
10416          "AtomicCmpSwap on types less than 128 should be legal");
10417   auto Desired = splitInt128(N->getOperand(2), DAG);
10418   auto New = splitInt128(N->getOperand(3), DAG);
10419   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10420                    New.first,        New.second,    N->getOperand(0)};
10421   SDNode *CmpSwap = DAG.getMachineNode(
10422       AArch64::CMP_SWAP_128, SDLoc(N),
10423       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10424 
10425   MachineFunction &MF = DAG.getMachineFunction();
10426   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10427   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10428   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10429 
10430   Results.push_back(SDValue(CmpSwap, 0));
10431   Results.push_back(SDValue(CmpSwap, 1));
10432   Results.push_back(SDValue(CmpSwap, 3));
10433 }
10434 
10435 void AArch64TargetLowering::ReplaceNodeResults(
10436     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10437   switch (N->getOpcode()) {
10438   default:
10439     llvm_unreachable("Don't know how to custom expand this");
10440   case ISD::BITCAST:
10441     ReplaceBITCASTResults(N, Results, DAG);
10442     return;
10443   case AArch64ISD::SADDV:
10444     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10445     return;
10446   case AArch64ISD::UADDV:
10447     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10448     return;
10449   case AArch64ISD::SMINV:
10450     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10451     return;
10452   case AArch64ISD::UMINV:
10453     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10454     return;
10455   case AArch64ISD::SMAXV:
10456     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10457     return;
10458   case AArch64ISD::UMAXV:
10459     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10460     return;
10461   case ISD::FP_TO_UINT:
10462   case ISD::FP_TO_SINT:
10463     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10464     // Let normal code take care of it by not adding anything to Results.
10465     return;
10466   case ISD::ATOMIC_CMP_SWAP:
10467     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10468     return;
10469   }
10470 }
10471 
10472 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10473   if (!Subtarget->isTargetAndroid())
10474     return true;
10475   return TargetLowering::useLoadStackGuardNode();
10476 }
10477 
10478 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10479   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10480   // reciprocal if there are three or more FDIVs.
10481   return 3;
10482 }
10483 
10484 TargetLoweringBase::LegalizeTypeAction
10485 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10486   MVT SVT = VT.getSimpleVT();
10487   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10488   // v4i16, v2i32 instead of to promote.
10489   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10490       || SVT == MVT::v1f32)
10491     return TypeWidenVector;
10492 
10493   return TargetLoweringBase::getPreferredVectorAction(VT);
10494 }
10495 
10496 // Loads and stores less than 128-bits are already atomic; ones above that
10497 // are doomed anyway, so defer to the default libcall and blame the OS when
10498 // things go wrong.
10499 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10500   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10501   return Size == 128;
10502 }
10503 
10504 // Loads and stores less than 128-bits are already atomic; ones above that
10505 // are doomed anyway, so defer to the default libcall and blame the OS when
10506 // things go wrong.
10507 TargetLowering::AtomicExpansionKind
10508 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10509   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10510   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10511 }
10512 
10513 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10514 TargetLowering::AtomicExpansionKind
10515 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10516   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10517   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10518 }
10519 
10520 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10521     AtomicCmpXchgInst *AI) const {
10522   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10523   // implement cmpxchg without spilling. If the address being exchanged is also
10524   // on the stack and close enough to the spill slot, this can lead to a
10525   // situation where the monitor always gets cleared and the atomic operation
10526   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10527   return getTargetMachine().getOptLevel() != 0;
10528 }
10529 
10530 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10531                                              AtomicOrdering Ord) const {
10532   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10533   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10534   bool IsAcquire = isAcquireOrStronger(Ord);
10535 
10536   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10537   // intrinsic must return {i64, i64} and we have to recombine them into a
10538   // single i128 here.
10539   if (ValTy->getPrimitiveSizeInBits() == 128) {
10540     Intrinsic::ID Int =
10541         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10542     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10543 
10544     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10545     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10546 
10547     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10548     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10549     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10550     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10551     return Builder.CreateOr(
10552         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10553   }
10554 
10555   Type *Tys[] = { Addr->getType() };
10556   Intrinsic::ID Int =
10557       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10558   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10559 
10560   return Builder.CreateTruncOrBitCast(
10561       Builder.CreateCall(Ldxr, Addr),
10562       cast<PointerType>(Addr->getType())->getElementType());
10563 }
10564 
10565 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10566     IRBuilder<> &Builder) const {
10567   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10568   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10569 }
10570 
10571 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10572                                                    Value *Val, Value *Addr,
10573                                                    AtomicOrdering Ord) const {
10574   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10575   bool IsRelease = isReleaseOrStronger(Ord);
10576 
10577   // Since the intrinsics must have legal type, the i128 intrinsics take two
10578   // parameters: "i64, i64". We must marshal Val into the appropriate form
10579   // before the call.
10580   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10581     Intrinsic::ID Int =
10582         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10583     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10584     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10585 
10586     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10587     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10588     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10589     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10590   }
10591 
10592   Intrinsic::ID Int =
10593       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10594   Type *Tys[] = { Addr->getType() };
10595   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10596 
10597   return Builder.CreateCall(Stxr,
10598                             {Builder.CreateZExtOrBitCast(
10599                                  Val, Stxr->getFunctionType()->getParamType(0)),
10600                              Addr});
10601 }
10602 
10603 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10604     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10605   return Ty->isArrayTy();
10606 }
10607 
10608 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10609                                                             EVT) const {
10610   return false;
10611 }
10612 
10613 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10614   if (!Subtarget->isTargetAndroid())
10615     return TargetLowering::getIRStackGuard(IRB);
10616 
10617   // Android provides a fixed TLS slot for the stack cookie. See the definition
10618   // of TLS_SLOT_STACK_GUARD in
10619   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10620   const unsigned TlsOffset = 0x28;
10621   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10622   Function *ThreadPointerFunc =
10623       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10624   return IRB.CreatePointerCast(
10625       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10626       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10627 }
10628 
10629 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10630   if (!Subtarget->isTargetAndroid())
10631     return TargetLowering::getSafeStackPointerLocation(IRB);
10632 
10633   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10634   // definition of TLS_SLOT_SAFESTACK in
10635   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10636   const unsigned TlsOffset = 0x48;
10637   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10638   Function *ThreadPointerFunc =
10639       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10640   return IRB.CreatePointerCast(
10641       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10642       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10643 }
10644 
10645 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10646     const Instruction &AndI) const {
10647   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10648   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
10649   // may be beneficial to sink in other cases, but we would have to check that
10650   // the cmp would not get folded into the br to form a cbz for these to be
10651   // beneficial.
10652   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10653   if (!Mask)
10654     return false;
10655   return Mask->getUniqueInteger().isPowerOf2();
10656 }
10657 
10658 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10659   // Update IsSplitCSR in AArch64unctionInfo.
10660   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10661   AFI->setIsSplitCSR(true);
10662 }
10663 
10664 void AArch64TargetLowering::insertCopiesSplitCSR(
10665     MachineBasicBlock *Entry,
10666     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10667   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10668   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10669   if (!IStart)
10670     return;
10671 
10672   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10673   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10674   MachineBasicBlock::iterator MBBI = Entry->begin();
10675   for (const MCPhysReg *I = IStart; *I; ++I) {
10676     const TargetRegisterClass *RC = nullptr;
10677     if (AArch64::GPR64RegClass.contains(*I))
10678       RC = &AArch64::GPR64RegClass;
10679     else if (AArch64::FPR64RegClass.contains(*I))
10680       RC = &AArch64::FPR64RegClass;
10681     else
10682       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10683 
10684     unsigned NewVR = MRI->createVirtualRegister(RC);
10685     // Create copy from CSR to a virtual register.
10686     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10687     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10688     // nounwind. If we want to generalize this later, we may need to emit
10689     // CFI pseudo-instructions.
10690     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10691                Attribute::NoUnwind) &&
10692            "Function should be nounwind in insertCopiesSplitCSR!");
10693     Entry->addLiveIn(*I);
10694     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10695         .addReg(*I);
10696 
10697     // Insert the copy-back instructions right before the terminator.
10698     for (auto *Exit : Exits)
10699       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10700               TII->get(TargetOpcode::COPY), *I)
10701           .addReg(NewVR);
10702   }
10703 }
10704 
10705 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10706   // Integer division on AArch64 is expensive. However, when aggressively
10707   // optimizing for code size, we prefer to use a div instruction, as it is
10708   // usually smaller than the alternative sequence.
10709   // The exception to this is vector division. Since AArch64 doesn't have vector
10710   // integer division, leaving the division as-is is a loss even in terms of
10711   // size, because it will have to be scalarized, while the alternative code
10712   // sequence can be performed in vector form.
10713   bool OptSize =
10714       Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10715   return OptSize && !VT.isVector();
10716 }
10717 
10718 unsigned
10719 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10720   if (Subtarget->isTargetDarwin())
10721     return getPointerTy(DL).getSizeInBits();
10722 
10723   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
10724 }
10725