1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64ExpandImm.h"
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/TargetCallingConv.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/IR/OperandTraits.h"
63 #include "llvm/IR/PatternMatch.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/IR/Use.h"
66 #include "llvm/IR/Value.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/CodeGen.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/KnownBits.h"
75 #include "llvm/Support/MachineValueType.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Target/TargetMachine.h"
79 #include "llvm/Target/TargetOptions.h"
80 #include <algorithm>
81 #include <bitset>
82 #include <cassert>
83 #include <cctype>
84 #include <cstdint>
85 #include <cstdlib>
86 #include <iterator>
87 #include <limits>
88 #include <tuple>
89 #include <utility>
90 #include <vector>
91 
92 using namespace llvm;
93 using namespace llvm::PatternMatch;
94 
95 #define DEBUG_TYPE "aarch64-lower"
96 
97 STATISTIC(NumTailCalls, "Number of tail calls");
98 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
99 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
100 
101 static cl::opt<bool>
102 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
103                            cl::desc("Allow AArch64 SLI/SRI formation"),
104                            cl::init(false));
105 
106 // FIXME: The necessary dtprel relocations don't seem to be supported
107 // well in the GNU bfd and gold linkers at the moment. Therefore, by
108 // default, for now, fall back to GeneralDynamic code generation.
109 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
110     "aarch64-elf-ldtls-generation", cl::Hidden,
111     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
112     cl::init(false));
113 
114 static cl::opt<bool>
115 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
116                          cl::desc("Enable AArch64 logical imm instruction "
117                                   "optimization"),
118                          cl::init(true));
119 
120 /// Value type used for condition codes.
121 static const MVT MVT_CC = MVT::i32;
122 
123 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
124                                              const AArch64Subtarget &STI)
125     : TargetLowering(TM), Subtarget(&STI) {
126   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
127   // we have to make something up. Arbitrarily, choose ZeroOrOne.
128   setBooleanContents(ZeroOrOneBooleanContent);
129   // When comparing vectors the result sets the different elements in the
130   // vector to all-one or all-zero.
131   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
132 
133   // Set up the register classes.
134   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
135   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
136 
137   if (Subtarget->hasFPARMv8()) {
138     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
139     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
140     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
141     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
142   }
143 
144   if (Subtarget->hasNEON()) {
145     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
146     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
147     // Someone set us up the NEON.
148     addDRTypeForNEON(MVT::v2f32);
149     addDRTypeForNEON(MVT::v8i8);
150     addDRTypeForNEON(MVT::v4i16);
151     addDRTypeForNEON(MVT::v2i32);
152     addDRTypeForNEON(MVT::v1i64);
153     addDRTypeForNEON(MVT::v1f64);
154     addDRTypeForNEON(MVT::v4f16);
155 
156     addQRTypeForNEON(MVT::v4f32);
157     addQRTypeForNEON(MVT::v2f64);
158     addQRTypeForNEON(MVT::v16i8);
159     addQRTypeForNEON(MVT::v8i16);
160     addQRTypeForNEON(MVT::v4i32);
161     addQRTypeForNEON(MVT::v2i64);
162     addQRTypeForNEON(MVT::v8f16);
163   }
164 
165   if (Subtarget->hasSVE()) {
166     // Add legal sve predicate types
167     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
168     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
169     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
170     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
171 
172     // Add legal sve data types
173     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
174     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
175     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
176     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
177 
178     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
179     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
180     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
181     addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass);
182     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184     addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass);
185     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
186 
187     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
188       setOperationAction(ISD::SADDSAT, VT, Legal);
189       setOperationAction(ISD::UADDSAT, VT, Legal);
190       setOperationAction(ISD::SSUBSAT, VT, Legal);
191       setOperationAction(ISD::USUBSAT, VT, Legal);
192     }
193   }
194 
195   // Compute derived properties from the register classes
196   computeRegisterProperties(Subtarget->getRegisterInfo());
197 
198   // Provide all sorts of operation actions
199   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
200   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
201   setOperationAction(ISD::SETCC, MVT::i32, Custom);
202   setOperationAction(ISD::SETCC, MVT::i64, Custom);
203   setOperationAction(ISD::SETCC, MVT::f16, Custom);
204   setOperationAction(ISD::SETCC, MVT::f32, Custom);
205   setOperationAction(ISD::SETCC, MVT::f64, Custom);
206   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
207   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
208   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
209   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
210   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
211   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
212   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
213   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
214   setOperationAction(ISD::SELECT, MVT::i32, Custom);
215   setOperationAction(ISD::SELECT, MVT::i64, Custom);
216   setOperationAction(ISD::SELECT, MVT::f16, Custom);
217   setOperationAction(ISD::SELECT, MVT::f32, Custom);
218   setOperationAction(ISD::SELECT, MVT::f64, Custom);
219   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
220   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
221   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
222   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
223   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
224   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
225   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
226 
227   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
228   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
229   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
230 
231   setOperationAction(ISD::FREM, MVT::f32, Expand);
232   setOperationAction(ISD::FREM, MVT::f64, Expand);
233   setOperationAction(ISD::FREM, MVT::f80, Expand);
234 
235   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
236 
237   // Custom lowering hooks are needed for XOR
238   // to fold it into CSINC/CSINV.
239   setOperationAction(ISD::XOR, MVT::i32, Custom);
240   setOperationAction(ISD::XOR, MVT::i64, Custom);
241 
242   // Virtually no operation on f128 is legal, but LLVM can't expand them when
243   // there's a valid register class, so we need custom operations in most cases.
244   setOperationAction(ISD::FABS, MVT::f128, Expand);
245   setOperationAction(ISD::FADD, MVT::f128, Custom);
246   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
247   setOperationAction(ISD::FCOS, MVT::f128, Expand);
248   setOperationAction(ISD::FDIV, MVT::f128, Custom);
249   setOperationAction(ISD::FMA, MVT::f128, Expand);
250   setOperationAction(ISD::FMUL, MVT::f128, Custom);
251   setOperationAction(ISD::FNEG, MVT::f128, Expand);
252   setOperationAction(ISD::FPOW, MVT::f128, Expand);
253   setOperationAction(ISD::FREM, MVT::f128, Expand);
254   setOperationAction(ISD::FRINT, MVT::f128, Expand);
255   setOperationAction(ISD::FSIN, MVT::f128, Expand);
256   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
257   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
258   setOperationAction(ISD::FSUB, MVT::f128, Custom);
259   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
260   setOperationAction(ISD::SETCC, MVT::f128, Custom);
261   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
262   setOperationAction(ISD::SELECT, MVT::f128, Custom);
263   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
264   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
265 
266   // Lowering for many of the conversions is actually specified by the non-f128
267   // type. The LowerXXX function will be trivial when f128 isn't involved.
268   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
269   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
270   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
271   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
272   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
273   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
274   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
275   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
276   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
277   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
278   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
279   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
280   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
281   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
282 
283   // Variable arguments.
284   setOperationAction(ISD::VASTART, MVT::Other, Custom);
285   setOperationAction(ISD::VAARG, MVT::Other, Custom);
286   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
287   setOperationAction(ISD::VAEND, MVT::Other, Expand);
288 
289   // Variable-sized objects.
290   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
291   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
292 
293   if (Subtarget->isTargetWindows())
294     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
295   else
296     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
297 
298   // Constant pool entries
299   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
300 
301   // BlockAddress
302   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
303 
304   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
305   setOperationAction(ISD::ADDC, MVT::i32, Custom);
306   setOperationAction(ISD::ADDE, MVT::i32, Custom);
307   setOperationAction(ISD::SUBC, MVT::i32, Custom);
308   setOperationAction(ISD::SUBE, MVT::i32, Custom);
309   setOperationAction(ISD::ADDC, MVT::i64, Custom);
310   setOperationAction(ISD::ADDE, MVT::i64, Custom);
311   setOperationAction(ISD::SUBC, MVT::i64, Custom);
312   setOperationAction(ISD::SUBE, MVT::i64, Custom);
313 
314   // AArch64 lacks both left-rotate and popcount instructions.
315   setOperationAction(ISD::ROTL, MVT::i32, Expand);
316   setOperationAction(ISD::ROTL, MVT::i64, Expand);
317   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
318     setOperationAction(ISD::ROTL, VT, Expand);
319     setOperationAction(ISD::ROTR, VT, Expand);
320   }
321 
322   // AArch64 doesn't have {U|S}MUL_LOHI.
323   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
324   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
325 
326   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
327   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
328 
329   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
330   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
331   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
332     setOperationAction(ISD::SDIVREM, VT, Expand);
333     setOperationAction(ISD::UDIVREM, VT, Expand);
334   }
335   setOperationAction(ISD::SREM, MVT::i32, Expand);
336   setOperationAction(ISD::SREM, MVT::i64, Expand);
337   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
338   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
339   setOperationAction(ISD::UREM, MVT::i32, Expand);
340   setOperationAction(ISD::UREM, MVT::i64, Expand);
341 
342   // Custom lower Add/Sub/Mul with overflow.
343   setOperationAction(ISD::SADDO, MVT::i32, Custom);
344   setOperationAction(ISD::SADDO, MVT::i64, Custom);
345   setOperationAction(ISD::UADDO, MVT::i32, Custom);
346   setOperationAction(ISD::UADDO, MVT::i64, Custom);
347   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
348   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
349   setOperationAction(ISD::USUBO, MVT::i32, Custom);
350   setOperationAction(ISD::USUBO, MVT::i64, Custom);
351   setOperationAction(ISD::SMULO, MVT::i32, Custom);
352   setOperationAction(ISD::SMULO, MVT::i64, Custom);
353   setOperationAction(ISD::UMULO, MVT::i32, Custom);
354   setOperationAction(ISD::UMULO, MVT::i64, Custom);
355 
356   setOperationAction(ISD::FSIN, MVT::f32, Expand);
357   setOperationAction(ISD::FSIN, MVT::f64, Expand);
358   setOperationAction(ISD::FCOS, MVT::f32, Expand);
359   setOperationAction(ISD::FCOS, MVT::f64, Expand);
360   setOperationAction(ISD::FPOW, MVT::f32, Expand);
361   setOperationAction(ISD::FPOW, MVT::f64, Expand);
362   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
363   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
364   if (Subtarget->hasFullFP16())
365     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
366   else
367     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
368 
369   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
370   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
371   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
372   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
373   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
374   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
375   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
376   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
377   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
378   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
379   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
380   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
381   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
382   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
383   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
384   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
385   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
386   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
387   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
388   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
389   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
390   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
391   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
392   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
393   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
394   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
395   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
396   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
397   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
398   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
399   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
400   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
401   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
402 
403   if (!Subtarget->hasFullFP16()) {
404     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
405     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
406     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
407     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
408     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
409     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
410     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
411     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
412     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
413     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
414     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
415     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
416     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
417     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
418     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
419     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
420     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
421     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
422     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
423     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
424     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
425     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
426 
427     // promote v4f16 to v4f32 when that is known to be safe.
428     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
429     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
430     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
431     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
432     setOperationAction(ISD::FP_EXTEND,   MVT::v4f16, Promote);
433     setOperationAction(ISD::FP_ROUND,    MVT::v4f16, Promote);
434     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
435     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
436     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
437     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
438     AddPromotedToType(ISD::FP_EXTEND,    MVT::v4f16, MVT::v4f32);
439     AddPromotedToType(ISD::FP_ROUND,     MVT::v4f16, MVT::v4f32);
440 
441     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
442     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
443     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
444     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
445     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
446     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
447     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
448     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
449     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
450     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
451     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
452     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
453     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
454     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
455     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
456 
457     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
458     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
459     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
460     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
461     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
462     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
463     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
464     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
465     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
466     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
467     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
468     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
469     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
470     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
471     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
472     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
473     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
474     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
475     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
476     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
477   }
478 
479   // AArch64 has implementations of a lot of rounding-like FP operations.
480   for (MVT Ty : {MVT::f32, MVT::f64}) {
481     setOperationAction(ISD::FFLOOR, Ty, Legal);
482     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
483     setOperationAction(ISD::FCEIL, Ty, Legal);
484     setOperationAction(ISD::FRINT, Ty, Legal);
485     setOperationAction(ISD::FTRUNC, Ty, Legal);
486     setOperationAction(ISD::FROUND, Ty, Legal);
487     setOperationAction(ISD::FMINNUM, Ty, Legal);
488     setOperationAction(ISD::FMAXNUM, Ty, Legal);
489     setOperationAction(ISD::FMINIMUM, Ty, Legal);
490     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
491     setOperationAction(ISD::LROUND, Ty, Legal);
492     setOperationAction(ISD::LLROUND, Ty, Legal);
493     setOperationAction(ISD::LRINT, Ty, Legal);
494     setOperationAction(ISD::LLRINT, Ty, Legal);
495   }
496 
497   if (Subtarget->hasFullFP16()) {
498     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
499     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
500     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
501     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
502     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
503     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
504     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
505     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
506     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
507     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
508   }
509 
510   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
511 
512   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
513 
514   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
515   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
516   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
517   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
518   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
519 
520   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
521   // This requires the Performance Monitors extension.
522   if (Subtarget->hasPerfMon())
523     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
524 
525   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
526       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
527     // Issue __sincos_stret if available.
528     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
529     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
530   } else {
531     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
532     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
533   }
534 
535   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
536     // MSVCRT doesn't have powi; fall back to pow
537     setLibcallName(RTLIB::POWI_F32, nullptr);
538     setLibcallName(RTLIB::POWI_F64, nullptr);
539   }
540 
541   // Make floating-point constants legal for the large code model, so they don't
542   // become loads from the constant pool.
543   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
544     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
545     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
546   }
547 
548   // AArch64 does not have floating-point extending loads, i1 sign-extending
549   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
550   for (MVT VT : MVT::fp_valuetypes()) {
551     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
552     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
553     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
554     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
555   }
556   for (MVT VT : MVT::integer_valuetypes())
557     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
558 
559   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
560   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
561   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
562   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
563   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
564   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
565   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
566 
567   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
568   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
569 
570   // Indexed loads and stores are supported.
571   for (unsigned im = (unsigned)ISD::PRE_INC;
572        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
573     setIndexedLoadAction(im, MVT::i8, Legal);
574     setIndexedLoadAction(im, MVT::i16, Legal);
575     setIndexedLoadAction(im, MVT::i32, Legal);
576     setIndexedLoadAction(im, MVT::i64, Legal);
577     setIndexedLoadAction(im, MVT::f64, Legal);
578     setIndexedLoadAction(im, MVT::f32, Legal);
579     setIndexedLoadAction(im, MVT::f16, Legal);
580     setIndexedStoreAction(im, MVT::i8, Legal);
581     setIndexedStoreAction(im, MVT::i16, Legal);
582     setIndexedStoreAction(im, MVT::i32, Legal);
583     setIndexedStoreAction(im, MVT::i64, Legal);
584     setIndexedStoreAction(im, MVT::f64, Legal);
585     setIndexedStoreAction(im, MVT::f32, Legal);
586     setIndexedStoreAction(im, MVT::f16, Legal);
587   }
588 
589   // Trap.
590   setOperationAction(ISD::TRAP, MVT::Other, Legal);
591   if (Subtarget->isTargetWindows())
592     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
593 
594   // We combine OR nodes for bitfield operations.
595   setTargetDAGCombine(ISD::OR);
596   // Try to create BICs for vector ANDs.
597   setTargetDAGCombine(ISD::AND);
598 
599   // Vector add and sub nodes may conceal a high-half opportunity.
600   // Also, try to fold ADD into CSINC/CSINV..
601   setTargetDAGCombine(ISD::ADD);
602   setTargetDAGCombine(ISD::SUB);
603   setTargetDAGCombine(ISD::SRL);
604   setTargetDAGCombine(ISD::XOR);
605   setTargetDAGCombine(ISD::SINT_TO_FP);
606   setTargetDAGCombine(ISD::UINT_TO_FP);
607 
608   setTargetDAGCombine(ISD::FP_TO_SINT);
609   setTargetDAGCombine(ISD::FP_TO_UINT);
610   setTargetDAGCombine(ISD::FDIV);
611 
612   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
613 
614   setTargetDAGCombine(ISD::ANY_EXTEND);
615   setTargetDAGCombine(ISD::ZERO_EXTEND);
616   setTargetDAGCombine(ISD::SIGN_EXTEND);
617   setTargetDAGCombine(ISD::BITCAST);
618   setTargetDAGCombine(ISD::CONCAT_VECTORS);
619   setTargetDAGCombine(ISD::STORE);
620   if (Subtarget->supportsAddressTopByteIgnored())
621     setTargetDAGCombine(ISD::LOAD);
622 
623   setTargetDAGCombine(ISD::MUL);
624 
625   setTargetDAGCombine(ISD::SELECT);
626   setTargetDAGCombine(ISD::VSELECT);
627 
628   setTargetDAGCombine(ISD::INTRINSIC_VOID);
629   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
630   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
631 
632   setTargetDAGCombine(ISD::GlobalAddress);
633 
634   // In case of strict alignment, avoid an excessive number of byte wide stores.
635   MaxStoresPerMemsetOptSize = 8;
636   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
637                        ? MaxStoresPerMemsetOptSize : 32;
638 
639   MaxGluedStoresPerMemcpy = 4;
640   MaxStoresPerMemcpyOptSize = 4;
641   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
642                        ? MaxStoresPerMemcpyOptSize : 16;
643 
644   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
645 
646   MaxLoadsPerMemcmpOptSize = 4;
647   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
648                       ? MaxLoadsPerMemcmpOptSize : 8;
649 
650   setStackPointerRegisterToSaveRestore(AArch64::SP);
651 
652   setSchedulingPreference(Sched::Hybrid);
653 
654   EnableExtLdPromotion = true;
655 
656   // Set required alignment.
657   setMinFunctionAlignment(Align(4));
658   // Set preferred alignments.
659   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
660   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
661 
662   // Only change the limit for entries in a jump table if specified by
663   // the sub target, but not at the command line.
664   unsigned MaxJT = STI.getMaximumJumpTableSize();
665   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
666     setMaximumJumpTableSize(MaxJT);
667 
668   setHasExtractBitsInsn(true);
669 
670   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
671 
672   if (Subtarget->hasNEON()) {
673     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
674     // silliness like this:
675     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
676     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
677     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
678     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
679     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
680     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
681     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
682     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
683     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
684     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
685     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
686     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
687     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
688     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
689     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
690     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
691     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
692     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
693     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
694     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
695     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
696     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
697     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
698     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
699     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
700 
701     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
702     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
703     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
704     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
705     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
706 
707     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
708 
709     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
710     // elements smaller than i32, so promote the input to i32 first.
711     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
712     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
713     // i8 vector elements also need promotion to i32 for v8i8
714     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
715     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
716     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
717     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
718     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
719     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
720     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
721     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
722     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
723     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
724     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
725 
726     if (Subtarget->hasFullFP16()) {
727       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
728       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
729       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
730       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
731     } else {
732       // when AArch64 doesn't have fullfp16 support, promote the input
733       // to i32 first.
734       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
735       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
736       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
737       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
738     }
739 
740     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
741     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
742 
743     // AArch64 doesn't have MUL.2d:
744     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
745     // Custom handling for some quad-vector types to detect MULL.
746     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
748     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
749 
750     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
751                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
752       // Vector reductions
753       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
754       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
755       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
756       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
757       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
758 
759       // Saturates
760       setOperationAction(ISD::SADDSAT, VT, Legal);
761       setOperationAction(ISD::UADDSAT, VT, Legal);
762       setOperationAction(ISD::SSUBSAT, VT, Legal);
763       setOperationAction(ISD::USUBSAT, VT, Legal);
764     }
765     for (MVT VT : { MVT::v4f16, MVT::v2f32,
766                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
767       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
768       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
769     }
770 
771     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
772     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
773     // Likewise, narrowing and extending vector loads/stores aren't handled
774     // directly.
775     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
776       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
777 
778       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
779         setOperationAction(ISD::MULHS, VT, Legal);
780         setOperationAction(ISD::MULHU, VT, Legal);
781       } else {
782         setOperationAction(ISD::MULHS, VT, Expand);
783         setOperationAction(ISD::MULHU, VT, Expand);
784       }
785       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
786       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
787 
788       setOperationAction(ISD::BSWAP, VT, Expand);
789       setOperationAction(ISD::CTTZ, VT, Expand);
790 
791       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
792         setTruncStoreAction(VT, InnerVT, Expand);
793         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
794         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
795         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
796       }
797     }
798 
799     // AArch64 has implementations of a lot of rounding-like FP operations.
800     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
801       setOperationAction(ISD::FFLOOR, Ty, Legal);
802       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
803       setOperationAction(ISD::FCEIL, Ty, Legal);
804       setOperationAction(ISD::FRINT, Ty, Legal);
805       setOperationAction(ISD::FTRUNC, Ty, Legal);
806       setOperationAction(ISD::FROUND, Ty, Legal);
807     }
808 
809     if (Subtarget->hasFullFP16()) {
810       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
811         setOperationAction(ISD::FFLOOR, Ty, Legal);
812         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
813         setOperationAction(ISD::FCEIL, Ty, Legal);
814         setOperationAction(ISD::FRINT, Ty, Legal);
815         setOperationAction(ISD::FTRUNC, Ty, Legal);
816         setOperationAction(ISD::FROUND, Ty, Legal);
817       }
818     }
819 
820     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
821   }
822 
823   if (Subtarget->hasSVE()) {
824     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
825     // splat of 0 or undef) once vector selects supported in SVE codegen. See
826     // D68877 for more details.
827     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
828       if (isTypeLegal(VT) && VT.getVectorElementType() != MVT::i1)
829         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
830     }
831   }
832 
833   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
834 }
835 
836 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
837   assert(VT.isVector() && "VT should be a vector type");
838 
839   if (VT.isFloatingPoint()) {
840     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
841     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
842     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
843   }
844 
845   // Mark vector float intrinsics as expand.
846   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
847     setOperationAction(ISD::FSIN, VT, Expand);
848     setOperationAction(ISD::FCOS, VT, Expand);
849     setOperationAction(ISD::FPOW, VT, Expand);
850     setOperationAction(ISD::FLOG, VT, Expand);
851     setOperationAction(ISD::FLOG2, VT, Expand);
852     setOperationAction(ISD::FLOG10, VT, Expand);
853     setOperationAction(ISD::FEXP, VT, Expand);
854     setOperationAction(ISD::FEXP2, VT, Expand);
855 
856     // But we do support custom-lowering for FCOPYSIGN.
857     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
858   }
859 
860   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
861   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
862   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
863   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
864   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
865   setOperationAction(ISD::SRA, VT, Custom);
866   setOperationAction(ISD::SRL, VT, Custom);
867   setOperationAction(ISD::SHL, VT, Custom);
868   setOperationAction(ISD::OR, VT, Custom);
869   setOperationAction(ISD::SETCC, VT, Custom);
870   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
871 
872   setOperationAction(ISD::SELECT, VT, Expand);
873   setOperationAction(ISD::SELECT_CC, VT, Expand);
874   setOperationAction(ISD::VSELECT, VT, Expand);
875   for (MVT InnerVT : MVT::all_valuetypes())
876     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
877 
878   // CNT supports only B element sizes, then use UADDLP to widen.
879   if (VT != MVT::v8i8 && VT != MVT::v16i8)
880     setOperationAction(ISD::CTPOP, VT, Custom);
881 
882   setOperationAction(ISD::UDIV, VT, Expand);
883   setOperationAction(ISD::SDIV, VT, Expand);
884   setOperationAction(ISD::UREM, VT, Expand);
885   setOperationAction(ISD::SREM, VT, Expand);
886   setOperationAction(ISD::FREM, VT, Expand);
887 
888   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
889   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
890 
891   if (!VT.isFloatingPoint())
892     setOperationAction(ISD::ABS, VT, Legal);
893 
894   // [SU][MIN|MAX] are available for all NEON types apart from i64.
895   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
896     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
897       setOperationAction(Opcode, VT, Legal);
898 
899   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
900   if (VT.isFloatingPoint() &&
901       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
902     for (unsigned Opcode :
903          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
904       setOperationAction(Opcode, VT, Legal);
905 
906   if (Subtarget->isLittleEndian()) {
907     for (unsigned im = (unsigned)ISD::PRE_INC;
908          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
909       setIndexedLoadAction(im, VT, Legal);
910       setIndexedStoreAction(im, VT, Legal);
911     }
912   }
913 }
914 
915 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
916   addRegisterClass(VT, &AArch64::FPR64RegClass);
917   addTypeForNEON(VT, MVT::v2i32);
918 }
919 
920 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
921   addRegisterClass(VT, &AArch64::FPR128RegClass);
922   addTypeForNEON(VT, MVT::v4i32);
923 }
924 
925 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
926                                               EVT VT) const {
927   if (!VT.isVector())
928     return MVT::i32;
929   return VT.changeVectorElementTypeToInteger();
930 }
931 
932 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
933                                const APInt &Demanded,
934                                TargetLowering::TargetLoweringOpt &TLO,
935                                unsigned NewOpc) {
936   uint64_t OldImm = Imm, NewImm, Enc;
937   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
938 
939   // Return if the immediate is already all zeros, all ones, a bimm32 or a
940   // bimm64.
941   if (Imm == 0 || Imm == Mask ||
942       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
943     return false;
944 
945   unsigned EltSize = Size;
946   uint64_t DemandedBits = Demanded.getZExtValue();
947 
948   // Clear bits that are not demanded.
949   Imm &= DemandedBits;
950 
951   while (true) {
952     // The goal here is to set the non-demanded bits in a way that minimizes
953     // the number of switching between 0 and 1. In order to achieve this goal,
954     // we set the non-demanded bits to the value of the preceding demanded bits.
955     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
956     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
957     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
958     // The final result is 0b11000011.
959     uint64_t NonDemandedBits = ~DemandedBits;
960     uint64_t InvertedImm = ~Imm & DemandedBits;
961     uint64_t RotatedImm =
962         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
963         NonDemandedBits;
964     uint64_t Sum = RotatedImm + NonDemandedBits;
965     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
966     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
967     NewImm = (Imm | Ones) & Mask;
968 
969     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
970     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
971     // we halve the element size and continue the search.
972     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
973       break;
974 
975     // We cannot shrink the element size any further if it is 2-bits.
976     if (EltSize == 2)
977       return false;
978 
979     EltSize /= 2;
980     Mask >>= EltSize;
981     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
982 
983     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
984     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
985       return false;
986 
987     // Merge the upper and lower halves of Imm and DemandedBits.
988     Imm |= Hi;
989     DemandedBits |= DemandedBitsHi;
990   }
991 
992   ++NumOptimizedImms;
993 
994   // Replicate the element across the register width.
995   while (EltSize < Size) {
996     NewImm |= NewImm << EltSize;
997     EltSize *= 2;
998   }
999 
1000   (void)OldImm;
1001   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1002          "demanded bits should never be altered");
1003   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1004 
1005   // Create the new constant immediate node.
1006   EVT VT = Op.getValueType();
1007   SDLoc DL(Op);
1008   SDValue New;
1009 
1010   // If the new constant immediate is all-zeros or all-ones, let the target
1011   // independent DAG combine optimize this node.
1012   if (NewImm == 0 || NewImm == OrigMask) {
1013     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1014                           TLO.DAG.getConstant(NewImm, DL, VT));
1015   // Otherwise, create a machine node so that target independent DAG combine
1016   // doesn't undo this optimization.
1017   } else {
1018     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1019     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1020     New = SDValue(
1021         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1022   }
1023 
1024   return TLO.CombineTo(Op, New);
1025 }
1026 
1027 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1028     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1029   // Delay this optimization to as late as possible.
1030   if (!TLO.LegalOps)
1031     return false;
1032 
1033   if (!EnableOptimizeLogicalImm)
1034     return false;
1035 
1036   EVT VT = Op.getValueType();
1037   if (VT.isVector())
1038     return false;
1039 
1040   unsigned Size = VT.getSizeInBits();
1041   assert((Size == 32 || Size == 64) &&
1042          "i32 or i64 is expected after legalization.");
1043 
1044   // Exit early if we demand all bits.
1045   if (Demanded.countPopulation() == Size)
1046     return false;
1047 
1048   unsigned NewOpc;
1049   switch (Op.getOpcode()) {
1050   default:
1051     return false;
1052   case ISD::AND:
1053     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1054     break;
1055   case ISD::OR:
1056     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1057     break;
1058   case ISD::XOR:
1059     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1060     break;
1061   }
1062   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1063   if (!C)
1064     return false;
1065   uint64_t Imm = C->getZExtValue();
1066   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1067 }
1068 
1069 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1070 /// Mask are known to be either zero or one and return them Known.
1071 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1072     const SDValue Op, KnownBits &Known,
1073     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1074   switch (Op.getOpcode()) {
1075   default:
1076     break;
1077   case AArch64ISD::CSEL: {
1078     KnownBits Known2;
1079     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1080     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1081     Known.Zero &= Known2.Zero;
1082     Known.One &= Known2.One;
1083     break;
1084   }
1085   case AArch64ISD::LOADgot:
1086   case AArch64ISD::ADDlow: {
1087     if (!Subtarget->isTargetILP32())
1088       break;
1089     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1090     Known.Zero = APInt::getHighBitsSet(64, 32);
1091     break;
1092   }
1093   case ISD::INTRINSIC_W_CHAIN: {
1094     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1095     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1096     switch (IntID) {
1097     default: return;
1098     case Intrinsic::aarch64_ldaxr:
1099     case Intrinsic::aarch64_ldxr: {
1100       unsigned BitWidth = Known.getBitWidth();
1101       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1102       unsigned MemBits = VT.getScalarSizeInBits();
1103       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1104       return;
1105     }
1106     }
1107     break;
1108   }
1109   case ISD::INTRINSIC_WO_CHAIN:
1110   case ISD::INTRINSIC_VOID: {
1111     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1112     switch (IntNo) {
1113     default:
1114       break;
1115     case Intrinsic::aarch64_neon_umaxv:
1116     case Intrinsic::aarch64_neon_uminv: {
1117       // Figure out the datatype of the vector operand. The UMINV instruction
1118       // will zero extend the result, so we can mark as known zero all the
1119       // bits larger than the element datatype. 32-bit or larget doesn't need
1120       // this as those are legal types and will be handled by isel directly.
1121       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1122       unsigned BitWidth = Known.getBitWidth();
1123       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1124         assert(BitWidth >= 8 && "Unexpected width!");
1125         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1126         Known.Zero |= Mask;
1127       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1128         assert(BitWidth >= 16 && "Unexpected width!");
1129         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1130         Known.Zero |= Mask;
1131       }
1132       break;
1133     } break;
1134     }
1135   }
1136   }
1137 }
1138 
1139 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1140                                                   EVT) const {
1141   return MVT::i64;
1142 }
1143 
1144 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1145     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1146     bool *Fast) const {
1147   if (Subtarget->requiresStrictAlign())
1148     return false;
1149 
1150   if (Fast) {
1151     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1152     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1153             // See comments in performSTORECombine() for more details about
1154             // these conditions.
1155 
1156             // Code that uses clang vector extensions can mark that it
1157             // wants unaligned accesses to be treated as fast by
1158             // underspecifying alignment to be 1 or 2.
1159             Align <= 2 ||
1160 
1161             // Disregard v2i64. Memcpy lowering produces those and splitting
1162             // them regresses performance on micro-benchmarks and olden/bh.
1163             VT == MVT::v2i64;
1164   }
1165   return true;
1166 }
1167 
1168 // Same as above but handling LLTs instead.
1169 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1170     LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1171     bool *Fast) const {
1172   if (Subtarget->requiresStrictAlign())
1173     return false;
1174 
1175   if (Fast) {
1176     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1177     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1178             Ty.getSizeInBytes() != 16 ||
1179             // See comments in performSTORECombine() for more details about
1180             // these conditions.
1181 
1182             // Code that uses clang vector extensions can mark that it
1183             // wants unaligned accesses to be treated as fast by
1184             // underspecifying alignment to be 1 or 2.
1185             Align <= 2 ||
1186 
1187             // Disregard v2i64. Memcpy lowering produces those and splitting
1188             // them regresses performance on micro-benchmarks and olden/bh.
1189             Ty == LLT::vector(2, 64);
1190   }
1191   return true;
1192 }
1193 
1194 FastISel *
1195 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1196                                       const TargetLibraryInfo *libInfo) const {
1197   return AArch64::createFastISel(funcInfo, libInfo);
1198 }
1199 
1200 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1201   switch ((AArch64ISD::NodeType)Opcode) {
1202   case AArch64ISD::FIRST_NUMBER:      break;
1203   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1204   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1205   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1206   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1207   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1208   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1209   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1210   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1211   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1212   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1213   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1214   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1215   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1216   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1217   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1218   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1219   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1220   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1221   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1222   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1223   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1224   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1225   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1226   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1227   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1228   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1229   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1230   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1231   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1232   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1233   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1234   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1235   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1236   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1237   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1238   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1239   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1240   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1241   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1242   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1243   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1244   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1245   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1246   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1247   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1248   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1249   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1250   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1251   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1252   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1253   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1254   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1255   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1256   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1257   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1258   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1259   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1260   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1261   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1262   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1263   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1264   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1265   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1266   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1267   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1268   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1269   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1270   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1271   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1272   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1273   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1274   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1275   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1276   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1277   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1278   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1279   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1280   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1281   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1282   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1283   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1284   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1285   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1286   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1287   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1288   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1289   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1290   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1291   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1292   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1293   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1294   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1295   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1296   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1297   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1298   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1299   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1300   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1301   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1302   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1303   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1304   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1305   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1306   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1307   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1308   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1309   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1310   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1311   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1312   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1313   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1314   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1315   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1316   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1317   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1318   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1319   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1320   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1321   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1322   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1323   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1324   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1325   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1326   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1327   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1328   case AArch64ISD::STG:               return "AArch64ISD::STG";
1329   case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1330   case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1331   case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1332   case AArch64ISD::SUNPKHI:           return "AArch64ISD::SUNPKHI";
1333   case AArch64ISD::SUNPKLO:           return "AArch64ISD::SUNPKLO";
1334   case AArch64ISD::UUNPKHI:           return "AArch64ISD::UUNPKHI";
1335   case AArch64ISD::UUNPKLO:           return "AArch64ISD::UUNPKLO";
1336   }
1337   return nullptr;
1338 }
1339 
1340 MachineBasicBlock *
1341 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1342                                     MachineBasicBlock *MBB) const {
1343   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1344   // phi node:
1345 
1346   // OrigBB:
1347   //     [... previous instrs leading to comparison ...]
1348   //     b.ne TrueBB
1349   //     b EndBB
1350   // TrueBB:
1351   //     ; Fallthrough
1352   // EndBB:
1353   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1354 
1355   MachineFunction *MF = MBB->getParent();
1356   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1357   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1358   DebugLoc DL = MI.getDebugLoc();
1359   MachineFunction::iterator It = ++MBB->getIterator();
1360 
1361   Register DestReg = MI.getOperand(0).getReg();
1362   Register IfTrueReg = MI.getOperand(1).getReg();
1363   Register IfFalseReg = MI.getOperand(2).getReg();
1364   unsigned CondCode = MI.getOperand(3).getImm();
1365   bool NZCVKilled = MI.getOperand(4).isKill();
1366 
1367   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1368   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1369   MF->insert(It, TrueBB);
1370   MF->insert(It, EndBB);
1371 
1372   // Transfer rest of current basic-block to EndBB
1373   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1374                 MBB->end());
1375   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1376 
1377   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1378   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1379   MBB->addSuccessor(TrueBB);
1380   MBB->addSuccessor(EndBB);
1381 
1382   // TrueBB falls through to the end.
1383   TrueBB->addSuccessor(EndBB);
1384 
1385   if (!NZCVKilled) {
1386     TrueBB->addLiveIn(AArch64::NZCV);
1387     EndBB->addLiveIn(AArch64::NZCV);
1388   }
1389 
1390   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1391       .addReg(IfTrueReg)
1392       .addMBB(TrueBB)
1393       .addReg(IfFalseReg)
1394       .addMBB(MBB);
1395 
1396   MI.eraseFromParent();
1397   return EndBB;
1398 }
1399 
1400 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1401        MachineInstr &MI, MachineBasicBlock *BB) const {
1402   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1403              BB->getParent()->getFunction().getPersonalityFn())) &&
1404          "SEH does not use catchret!");
1405   return BB;
1406 }
1407 
1408 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1409      MachineInstr &MI, MachineBasicBlock *BB) const {
1410   MI.eraseFromParent();
1411   return BB;
1412 }
1413 
1414 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1415     MachineInstr &MI, MachineBasicBlock *BB) const {
1416   switch (MI.getOpcode()) {
1417   default:
1418 #ifndef NDEBUG
1419     MI.dump();
1420 #endif
1421     llvm_unreachable("Unexpected instruction for custom inserter!");
1422 
1423   case AArch64::F128CSEL:
1424     return EmitF128CSEL(MI, BB);
1425 
1426   case TargetOpcode::STACKMAP:
1427   case TargetOpcode::PATCHPOINT:
1428     return emitPatchPoint(MI, BB);
1429 
1430   case AArch64::CATCHRET:
1431     return EmitLoweredCatchRet(MI, BB);
1432   case AArch64::CATCHPAD:
1433     return EmitLoweredCatchPad(MI, BB);
1434   }
1435 }
1436 
1437 //===----------------------------------------------------------------------===//
1438 // AArch64 Lowering private implementation.
1439 //===----------------------------------------------------------------------===//
1440 
1441 //===----------------------------------------------------------------------===//
1442 // Lowering Code
1443 //===----------------------------------------------------------------------===//
1444 
1445 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1446 /// CC
1447 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1448   switch (CC) {
1449   default:
1450     llvm_unreachable("Unknown condition code!");
1451   case ISD::SETNE:
1452     return AArch64CC::NE;
1453   case ISD::SETEQ:
1454     return AArch64CC::EQ;
1455   case ISD::SETGT:
1456     return AArch64CC::GT;
1457   case ISD::SETGE:
1458     return AArch64CC::GE;
1459   case ISD::SETLT:
1460     return AArch64CC::LT;
1461   case ISD::SETLE:
1462     return AArch64CC::LE;
1463   case ISD::SETUGT:
1464     return AArch64CC::HI;
1465   case ISD::SETUGE:
1466     return AArch64CC::HS;
1467   case ISD::SETULT:
1468     return AArch64CC::LO;
1469   case ISD::SETULE:
1470     return AArch64CC::LS;
1471   }
1472 }
1473 
1474 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1475 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1476                                   AArch64CC::CondCode &CondCode,
1477                                   AArch64CC::CondCode &CondCode2) {
1478   CondCode2 = AArch64CC::AL;
1479   switch (CC) {
1480   default:
1481     llvm_unreachable("Unknown FP condition!");
1482   case ISD::SETEQ:
1483   case ISD::SETOEQ:
1484     CondCode = AArch64CC::EQ;
1485     break;
1486   case ISD::SETGT:
1487   case ISD::SETOGT:
1488     CondCode = AArch64CC::GT;
1489     break;
1490   case ISD::SETGE:
1491   case ISD::SETOGE:
1492     CondCode = AArch64CC::GE;
1493     break;
1494   case ISD::SETOLT:
1495     CondCode = AArch64CC::MI;
1496     break;
1497   case ISD::SETOLE:
1498     CondCode = AArch64CC::LS;
1499     break;
1500   case ISD::SETONE:
1501     CondCode = AArch64CC::MI;
1502     CondCode2 = AArch64CC::GT;
1503     break;
1504   case ISD::SETO:
1505     CondCode = AArch64CC::VC;
1506     break;
1507   case ISD::SETUO:
1508     CondCode = AArch64CC::VS;
1509     break;
1510   case ISD::SETUEQ:
1511     CondCode = AArch64CC::EQ;
1512     CondCode2 = AArch64CC::VS;
1513     break;
1514   case ISD::SETUGT:
1515     CondCode = AArch64CC::HI;
1516     break;
1517   case ISD::SETUGE:
1518     CondCode = AArch64CC::PL;
1519     break;
1520   case ISD::SETLT:
1521   case ISD::SETULT:
1522     CondCode = AArch64CC::LT;
1523     break;
1524   case ISD::SETLE:
1525   case ISD::SETULE:
1526     CondCode = AArch64CC::LE;
1527     break;
1528   case ISD::SETNE:
1529   case ISD::SETUNE:
1530     CondCode = AArch64CC::NE;
1531     break;
1532   }
1533 }
1534 
1535 /// Convert a DAG fp condition code to an AArch64 CC.
1536 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1537 /// should be AND'ed instead of OR'ed.
1538 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1539                                      AArch64CC::CondCode &CondCode,
1540                                      AArch64CC::CondCode &CondCode2) {
1541   CondCode2 = AArch64CC::AL;
1542   switch (CC) {
1543   default:
1544     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1545     assert(CondCode2 == AArch64CC::AL);
1546     break;
1547   case ISD::SETONE:
1548     // (a one b)
1549     // == ((a olt b) || (a ogt b))
1550     // == ((a ord b) && (a une b))
1551     CondCode = AArch64CC::VC;
1552     CondCode2 = AArch64CC::NE;
1553     break;
1554   case ISD::SETUEQ:
1555     // (a ueq b)
1556     // == ((a uno b) || (a oeq b))
1557     // == ((a ule b) && (a uge b))
1558     CondCode = AArch64CC::PL;
1559     CondCode2 = AArch64CC::LE;
1560     break;
1561   }
1562 }
1563 
1564 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1565 /// CC usable with the vector instructions. Fewer operations are available
1566 /// without a real NZCV register, so we have to use less efficient combinations
1567 /// to get the same effect.
1568 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1569                                         AArch64CC::CondCode &CondCode,
1570                                         AArch64CC::CondCode &CondCode2,
1571                                         bool &Invert) {
1572   Invert = false;
1573   switch (CC) {
1574   default:
1575     // Mostly the scalar mappings work fine.
1576     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1577     break;
1578   case ISD::SETUO:
1579     Invert = true;
1580     LLVM_FALLTHROUGH;
1581   case ISD::SETO:
1582     CondCode = AArch64CC::MI;
1583     CondCode2 = AArch64CC::GE;
1584     break;
1585   case ISD::SETUEQ:
1586   case ISD::SETULT:
1587   case ISD::SETULE:
1588   case ISD::SETUGT:
1589   case ISD::SETUGE:
1590     // All of the compare-mask comparisons are ordered, but we can switch
1591     // between the two by a double inversion. E.g. ULE == !OGT.
1592     Invert = true;
1593     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1594     break;
1595   }
1596 }
1597 
1598 static bool isLegalArithImmed(uint64_t C) {
1599   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1600   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1601   LLVM_DEBUG(dbgs() << "Is imm " << C
1602                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1603   return IsLegal;
1604 }
1605 
1606 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1607 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1608 // can be set differently by this operation. It comes down to whether
1609 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1610 // everything is fine. If not then the optimization is wrong. Thus general
1611 // comparisons are only valid if op2 != 0.
1612 //
1613 // So, finally, the only LLVM-native comparisons that don't mention C and V
1614 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1615 // the absence of information about op2.
1616 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1617   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1618          (CC == ISD::SETEQ || CC == ISD::SETNE);
1619 }
1620 
1621 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1622                               const SDLoc &dl, SelectionDAG &DAG) {
1623   EVT VT = LHS.getValueType();
1624   const bool FullFP16 =
1625     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1626 
1627   if (VT.isFloatingPoint()) {
1628     assert(VT != MVT::f128);
1629     if (VT == MVT::f16 && !FullFP16) {
1630       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1631       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1632       VT = MVT::f32;
1633     }
1634     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1635   }
1636 
1637   // The CMP instruction is just an alias for SUBS, and representing it as
1638   // SUBS means that it's possible to get CSE with subtract operations.
1639   // A later phase can perform the optimization of setting the destination
1640   // register to WZR/XZR if it ends up being unused.
1641   unsigned Opcode = AArch64ISD::SUBS;
1642 
1643   if (isCMN(RHS, CC)) {
1644     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1645     Opcode = AArch64ISD::ADDS;
1646     RHS = RHS.getOperand(1);
1647   } else if (isCMN(LHS, CC)) {
1648     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1649     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1650     Opcode = AArch64ISD::ADDS;
1651     LHS = LHS.getOperand(1);
1652   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1653              !isUnsignedIntSetCC(CC)) {
1654     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1655     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1656     // of the signed comparisons.
1657     Opcode = AArch64ISD::ANDS;
1658     RHS = LHS.getOperand(1);
1659     LHS = LHS.getOperand(0);
1660   }
1661 
1662   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1663       .getValue(1);
1664 }
1665 
1666 /// \defgroup AArch64CCMP CMP;CCMP matching
1667 ///
1668 /// These functions deal with the formation of CMP;CCMP;... sequences.
1669 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1670 /// a comparison. They set the NZCV flags to a predefined value if their
1671 /// predicate is false. This allows to express arbitrary conjunctions, for
1672 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1673 /// expressed as:
1674 ///   cmp A
1675 ///   ccmp B, inv(CB), CA
1676 ///   check for CB flags
1677 ///
1678 /// This naturally lets us implement chains of AND operations with SETCC
1679 /// operands. And we can even implement some other situations by transforming
1680 /// them:
1681 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1682 ///     negating the flags used in a CCMP/FCCMP operations.
1683 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1684 ///     by negating the flags we test for afterwards. i.e.
1685 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1686 ///   - Note that we can only ever negate all previously processed results.
1687 ///     What we can not implement by flipping the flags to test is a negation
1688 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1689 ///     far, so the 2nd sub-tree we emit would also affect the first).
1690 /// With those tools we can implement some OR operations:
1691 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1692 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1693 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1694 ///     elimination rules from earlier to implement the whole thing as a
1695 ///     CCMP/FCCMP chain.
1696 ///
1697 /// As complete example:
1698 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1699 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1700 /// can be reassociated to:
1701 ///     or (and (setCC (cmp C)) setCD (cmp D))
1702 //         (or (setCA (cmp A)) (setCB (cmp B)))
1703 /// can be transformed to:
1704 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1705 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1706 /// which can be implemented as:
1707 ///   cmp C
1708 ///   ccmp D, inv(CD), CC
1709 ///   ccmp A, CA, inv(CD)
1710 ///   ccmp B, CB, inv(CA)
1711 ///   check for CB flags
1712 ///
1713 /// A counterexample is "or (and A B) (and C D)" which translates to
1714 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1715 /// can only implement 1 of the inner (not) operations, but not both!
1716 /// @{
1717 
1718 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1719 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1720                                          ISD::CondCode CC, SDValue CCOp,
1721                                          AArch64CC::CondCode Predicate,
1722                                          AArch64CC::CondCode OutCC,
1723                                          const SDLoc &DL, SelectionDAG &DAG) {
1724   unsigned Opcode = 0;
1725   const bool FullFP16 =
1726     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1727 
1728   if (LHS.getValueType().isFloatingPoint()) {
1729     assert(LHS.getValueType() != MVT::f128);
1730     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1731       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1732       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1733     }
1734     Opcode = AArch64ISD::FCCMP;
1735   } else if (RHS.getOpcode() == ISD::SUB) {
1736     SDValue SubOp0 = RHS.getOperand(0);
1737     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1738       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1739       Opcode = AArch64ISD::CCMN;
1740       RHS = RHS.getOperand(1);
1741     }
1742   }
1743   if (Opcode == 0)
1744     Opcode = AArch64ISD::CCMP;
1745 
1746   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1747   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1748   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1749   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1750   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1751 }
1752 
1753 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1754 /// expressed as a conjunction. See \ref AArch64CCMP.
1755 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1756 ///                     changing the conditions on the SETCC tests.
1757 ///                     (this means we can call emitConjunctionRec() with
1758 ///                      Negate==true on this sub-tree)
1759 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1760 ///                     cannot do the negation naturally. We are required to
1761 ///                     emit the subtree first in this case.
1762 /// \param WillNegate   Is true if are called when the result of this
1763 ///                     subexpression must be negated. This happens when the
1764 ///                     outer expression is an OR. We can use this fact to know
1765 ///                     that we have a double negation (or (or ...) ...) that
1766 ///                     can be implemented for free.
1767 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1768                                bool &MustBeFirst, bool WillNegate,
1769                                unsigned Depth = 0) {
1770   if (!Val.hasOneUse())
1771     return false;
1772   unsigned Opcode = Val->getOpcode();
1773   if (Opcode == ISD::SETCC) {
1774     if (Val->getOperand(0).getValueType() == MVT::f128)
1775       return false;
1776     CanNegate = true;
1777     MustBeFirst = false;
1778     return true;
1779   }
1780   // Protect against exponential runtime and stack overflow.
1781   if (Depth > 6)
1782     return false;
1783   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1784     bool IsOR = Opcode == ISD::OR;
1785     SDValue O0 = Val->getOperand(0);
1786     SDValue O1 = Val->getOperand(1);
1787     bool CanNegateL;
1788     bool MustBeFirstL;
1789     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1790       return false;
1791     bool CanNegateR;
1792     bool MustBeFirstR;
1793     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1794       return false;
1795 
1796     if (MustBeFirstL && MustBeFirstR)
1797       return false;
1798 
1799     if (IsOR) {
1800       // For an OR expression we need to be able to naturally negate at least
1801       // one side or we cannot do the transformation at all.
1802       if (!CanNegateL && !CanNegateR)
1803         return false;
1804       // If we the result of the OR will be negated and we can naturally negate
1805       // the leafs, then this sub-tree as a whole negates naturally.
1806       CanNegate = WillNegate && CanNegateL && CanNegateR;
1807       // If we cannot naturally negate the whole sub-tree, then this must be
1808       // emitted first.
1809       MustBeFirst = !CanNegate;
1810     } else {
1811       assert(Opcode == ISD::AND && "Must be OR or AND");
1812       // We cannot naturally negate an AND operation.
1813       CanNegate = false;
1814       MustBeFirst = MustBeFirstL || MustBeFirstR;
1815     }
1816     return true;
1817   }
1818   return false;
1819 }
1820 
1821 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1822 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1823 /// Tries to transform the given i1 producing node @p Val to a series compare
1824 /// and conditional compare operations. @returns an NZCV flags producing node
1825 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1826 /// transformation was not possible.
1827 /// \p Negate is true if we want this sub-tree being negated just by changing
1828 /// SETCC conditions.
1829 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1830     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1831     AArch64CC::CondCode Predicate) {
1832   // We're at a tree leaf, produce a conditional comparison operation.
1833   unsigned Opcode = Val->getOpcode();
1834   if (Opcode == ISD::SETCC) {
1835     SDValue LHS = Val->getOperand(0);
1836     SDValue RHS = Val->getOperand(1);
1837     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1838     bool isInteger = LHS.getValueType().isInteger();
1839     if (Negate)
1840       CC = getSetCCInverse(CC, isInteger);
1841     SDLoc DL(Val);
1842     // Determine OutCC and handle FP special case.
1843     if (isInteger) {
1844       OutCC = changeIntCCToAArch64CC(CC);
1845     } else {
1846       assert(LHS.getValueType().isFloatingPoint());
1847       AArch64CC::CondCode ExtraCC;
1848       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1849       // Some floating point conditions can't be tested with a single condition
1850       // code. Construct an additional comparison in this case.
1851       if (ExtraCC != AArch64CC::AL) {
1852         SDValue ExtraCmp;
1853         if (!CCOp.getNode())
1854           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1855         else
1856           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1857                                                ExtraCC, DL, DAG);
1858         CCOp = ExtraCmp;
1859         Predicate = ExtraCC;
1860       }
1861     }
1862 
1863     // Produce a normal comparison if we are first in the chain
1864     if (!CCOp)
1865       return emitComparison(LHS, RHS, CC, DL, DAG);
1866     // Otherwise produce a ccmp.
1867     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1868                                      DAG);
1869   }
1870   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1871 
1872   bool IsOR = Opcode == ISD::OR;
1873 
1874   SDValue LHS = Val->getOperand(0);
1875   bool CanNegateL;
1876   bool MustBeFirstL;
1877   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1878   assert(ValidL && "Valid conjunction/disjunction tree");
1879   (void)ValidL;
1880 
1881   SDValue RHS = Val->getOperand(1);
1882   bool CanNegateR;
1883   bool MustBeFirstR;
1884   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1885   assert(ValidR && "Valid conjunction/disjunction tree");
1886   (void)ValidR;
1887 
1888   // Swap sub-tree that must come first to the right side.
1889   if (MustBeFirstL) {
1890     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1891     std::swap(LHS, RHS);
1892     std::swap(CanNegateL, CanNegateR);
1893     std::swap(MustBeFirstL, MustBeFirstR);
1894   }
1895 
1896   bool NegateR;
1897   bool NegateAfterR;
1898   bool NegateL;
1899   bool NegateAfterAll;
1900   if (Opcode == ISD::OR) {
1901     // Swap the sub-tree that we can negate naturally to the left.
1902     if (!CanNegateL) {
1903       assert(CanNegateR && "at least one side must be negatable");
1904       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1905       assert(!Negate);
1906       std::swap(LHS, RHS);
1907       NegateR = false;
1908       NegateAfterR = true;
1909     } else {
1910       // Negate the left sub-tree if possible, otherwise negate the result.
1911       NegateR = CanNegateR;
1912       NegateAfterR = !CanNegateR;
1913     }
1914     NegateL = true;
1915     NegateAfterAll = !Negate;
1916   } else {
1917     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1918     assert(!Negate && "Valid conjunction/disjunction tree");
1919 
1920     NegateL = false;
1921     NegateR = false;
1922     NegateAfterR = false;
1923     NegateAfterAll = false;
1924   }
1925 
1926   // Emit sub-trees.
1927   AArch64CC::CondCode RHSCC;
1928   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1929   if (NegateAfterR)
1930     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1931   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1932   if (NegateAfterAll)
1933     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1934   return CmpL;
1935 }
1936 
1937 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1938 /// In some cases this is even possible with OR operations in the expression.
1939 /// See \ref AArch64CCMP.
1940 /// \see emitConjunctionRec().
1941 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1942                                AArch64CC::CondCode &OutCC) {
1943   bool DummyCanNegate;
1944   bool DummyMustBeFirst;
1945   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
1946     return SDValue();
1947 
1948   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1949 }
1950 
1951 /// @}
1952 
1953 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1954 /// extension operations.
1955 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1956   auto isSupportedExtend = [&](SDValue V) {
1957     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1958       return true;
1959 
1960     if (V.getOpcode() == ISD::AND)
1961       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1962         uint64_t Mask = MaskCst->getZExtValue();
1963         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1964       }
1965 
1966     return false;
1967   };
1968 
1969   if (!Op.hasOneUse())
1970     return 0;
1971 
1972   if (isSupportedExtend(Op))
1973     return 1;
1974 
1975   unsigned Opc = Op.getOpcode();
1976   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1977     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1978       uint64_t Shift = ShiftCst->getZExtValue();
1979       if (isSupportedExtend(Op.getOperand(0)))
1980         return (Shift <= 4) ? 2 : 1;
1981       EVT VT = Op.getValueType();
1982       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1983         return 1;
1984     }
1985 
1986   return 0;
1987 }
1988 
1989 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1990                              SDValue &AArch64cc, SelectionDAG &DAG,
1991                              const SDLoc &dl) {
1992   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1993     EVT VT = RHS.getValueType();
1994     uint64_t C = RHSC->getZExtValue();
1995     if (!isLegalArithImmed(C)) {
1996       // Constant does not fit, try adjusting it by one?
1997       switch (CC) {
1998       default:
1999         break;
2000       case ISD::SETLT:
2001       case ISD::SETGE:
2002         if ((VT == MVT::i32 && C != 0x80000000 &&
2003              isLegalArithImmed((uint32_t)(C - 1))) ||
2004             (VT == MVT::i64 && C != 0x80000000ULL &&
2005              isLegalArithImmed(C - 1ULL))) {
2006           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2007           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2008           RHS = DAG.getConstant(C, dl, VT);
2009         }
2010         break;
2011       case ISD::SETULT:
2012       case ISD::SETUGE:
2013         if ((VT == MVT::i32 && C != 0 &&
2014              isLegalArithImmed((uint32_t)(C - 1))) ||
2015             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2016           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2017           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2018           RHS = DAG.getConstant(C, dl, VT);
2019         }
2020         break;
2021       case ISD::SETLE:
2022       case ISD::SETGT:
2023         if ((VT == MVT::i32 && C != INT32_MAX &&
2024              isLegalArithImmed((uint32_t)(C + 1))) ||
2025             (VT == MVT::i64 && C != INT64_MAX &&
2026              isLegalArithImmed(C + 1ULL))) {
2027           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2028           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2029           RHS = DAG.getConstant(C, dl, VT);
2030         }
2031         break;
2032       case ISD::SETULE:
2033       case ISD::SETUGT:
2034         if ((VT == MVT::i32 && C != UINT32_MAX &&
2035              isLegalArithImmed((uint32_t)(C + 1))) ||
2036             (VT == MVT::i64 && C != UINT64_MAX &&
2037              isLegalArithImmed(C + 1ULL))) {
2038           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2039           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2040           RHS = DAG.getConstant(C, dl, VT);
2041         }
2042         break;
2043       }
2044     }
2045   }
2046 
2047   // Comparisons are canonicalized so that the RHS operand is simpler than the
2048   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2049   // can fold some shift+extend operations on the RHS operand, so swap the
2050   // operands if that can be done.
2051   //
2052   // For example:
2053   //    lsl     w13, w11, #1
2054   //    cmp     w13, w12
2055   // can be turned into:
2056   //    cmp     w12, w11, lsl #1
2057   if (!isa<ConstantSDNode>(RHS) ||
2058       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2059     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2060 
2061     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2062       std::swap(LHS, RHS);
2063       CC = ISD::getSetCCSwappedOperands(CC);
2064     }
2065   }
2066 
2067   SDValue Cmp;
2068   AArch64CC::CondCode AArch64CC;
2069   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2070     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2071 
2072     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2073     // For the i8 operand, the largest immediate is 255, so this can be easily
2074     // encoded in the compare instruction. For the i16 operand, however, the
2075     // largest immediate cannot be encoded in the compare.
2076     // Therefore, use a sign extending load and cmn to avoid materializing the
2077     // -1 constant. For example,
2078     // movz w1, #65535
2079     // ldrh w0, [x0, #0]
2080     // cmp w0, w1
2081     // >
2082     // ldrsh w0, [x0, #0]
2083     // cmn w0, #1
2084     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2085     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2086     // ensure both the LHS and RHS are truly zero extended and to make sure the
2087     // transformation is profitable.
2088     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2089         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2090         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2091         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2092       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2093       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2094         SDValue SExt =
2095             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2096                         DAG.getValueType(MVT::i16));
2097         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2098                                                    RHS.getValueType()),
2099                              CC, dl, DAG);
2100         AArch64CC = changeIntCCToAArch64CC(CC);
2101       }
2102     }
2103 
2104     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2105       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2106         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2107           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2108       }
2109     }
2110   }
2111 
2112   if (!Cmp) {
2113     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2114     AArch64CC = changeIntCCToAArch64CC(CC);
2115   }
2116   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2117   return Cmp;
2118 }
2119 
2120 static std::pair<SDValue, SDValue>
2121 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2122   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2123          "Unsupported value type");
2124   SDValue Value, Overflow;
2125   SDLoc DL(Op);
2126   SDValue LHS = Op.getOperand(0);
2127   SDValue RHS = Op.getOperand(1);
2128   unsigned Opc = 0;
2129   switch (Op.getOpcode()) {
2130   default:
2131     llvm_unreachable("Unknown overflow instruction!");
2132   case ISD::SADDO:
2133     Opc = AArch64ISD::ADDS;
2134     CC = AArch64CC::VS;
2135     break;
2136   case ISD::UADDO:
2137     Opc = AArch64ISD::ADDS;
2138     CC = AArch64CC::HS;
2139     break;
2140   case ISD::SSUBO:
2141     Opc = AArch64ISD::SUBS;
2142     CC = AArch64CC::VS;
2143     break;
2144   case ISD::USUBO:
2145     Opc = AArch64ISD::SUBS;
2146     CC = AArch64CC::LO;
2147     break;
2148   // Multiply needs a little bit extra work.
2149   case ISD::SMULO:
2150   case ISD::UMULO: {
2151     CC = AArch64CC::NE;
2152     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2153     if (Op.getValueType() == MVT::i32) {
2154       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2155       // For a 32 bit multiply with overflow check we want the instruction
2156       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2157       // need to generate the following pattern:
2158       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2159       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2160       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2161       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2162       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2163                                 DAG.getConstant(0, DL, MVT::i64));
2164       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2165       // operation. We need to clear out the upper 32 bits, because we used a
2166       // widening multiply that wrote all 64 bits. In the end this should be a
2167       // noop.
2168       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2169       if (IsSigned) {
2170         // The signed overflow check requires more than just a simple check for
2171         // any bit set in the upper 32 bits of the result. These bits could be
2172         // just the sign bits of a negative number. To perform the overflow
2173         // check we have to arithmetic shift right the 32nd bit of the result by
2174         // 31 bits. Then we compare the result to the upper 32 bits.
2175         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2176                                         DAG.getConstant(32, DL, MVT::i64));
2177         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2178         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2179                                         DAG.getConstant(31, DL, MVT::i64));
2180         // It is important that LowerBits is last, otherwise the arithmetic
2181         // shift will not be folded into the compare (SUBS).
2182         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2183         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2184                        .getValue(1);
2185       } else {
2186         // The overflow check for unsigned multiply is easy. We only need to
2187         // check if any of the upper 32 bits are set. This can be done with a
2188         // CMP (shifted register). For that we need to generate the following
2189         // pattern:
2190         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2191         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2192                                         DAG.getConstant(32, DL, MVT::i64));
2193         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2194         Overflow =
2195             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2196                         DAG.getConstant(0, DL, MVT::i64),
2197                         UpperBits).getValue(1);
2198       }
2199       break;
2200     }
2201     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2202     // For the 64 bit multiply
2203     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2204     if (IsSigned) {
2205       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2206       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2207                                       DAG.getConstant(63, DL, MVT::i64));
2208       // It is important that LowerBits is last, otherwise the arithmetic
2209       // shift will not be folded into the compare (SUBS).
2210       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2211       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2212                      .getValue(1);
2213     } else {
2214       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2215       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2216       Overflow =
2217           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2218                       DAG.getConstant(0, DL, MVT::i64),
2219                       UpperBits).getValue(1);
2220     }
2221     break;
2222   }
2223   } // switch (...)
2224 
2225   if (Opc) {
2226     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2227 
2228     // Emit the AArch64 operation with overflow check.
2229     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2230     Overflow = Value.getValue(1);
2231   }
2232   return std::make_pair(Value, Overflow);
2233 }
2234 
2235 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2236                                              RTLIB::Libcall Call) const {
2237   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2238   MakeLibCallOptions CallOptions;
2239   return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first;
2240 }
2241 
2242 // Returns true if the given Op is the overflow flag result of an overflow
2243 // intrinsic operation.
2244 static bool isOverflowIntrOpRes(SDValue Op) {
2245   unsigned Opc = Op.getOpcode();
2246   return (Op.getResNo() == 1 &&
2247           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2248            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2249 }
2250 
2251 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2252   SDValue Sel = Op.getOperand(0);
2253   SDValue Other = Op.getOperand(1);
2254   SDLoc dl(Sel);
2255 
2256   // If the operand is an overflow checking operation, invert the condition
2257   // code and kill the Not operation. I.e., transform:
2258   // (xor (overflow_op_bool, 1))
2259   //   -->
2260   // (csel 1, 0, invert(cc), overflow_op_bool)
2261   // ... which later gets transformed to just a cset instruction with an
2262   // inverted condition code, rather than a cset + eor sequence.
2263   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2264     // Only lower legal XALUO ops.
2265     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2266       return SDValue();
2267 
2268     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2269     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2270     AArch64CC::CondCode CC;
2271     SDValue Value, Overflow;
2272     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2273     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2274     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2275                        CCVal, Overflow);
2276   }
2277   // If neither operand is a SELECT_CC, give up.
2278   if (Sel.getOpcode() != ISD::SELECT_CC)
2279     std::swap(Sel, Other);
2280   if (Sel.getOpcode() != ISD::SELECT_CC)
2281     return Op;
2282 
2283   // The folding we want to perform is:
2284   // (xor x, (select_cc a, b, cc, 0, -1) )
2285   //   -->
2286   // (csel x, (xor x, -1), cc ...)
2287   //
2288   // The latter will get matched to a CSINV instruction.
2289 
2290   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2291   SDValue LHS = Sel.getOperand(0);
2292   SDValue RHS = Sel.getOperand(1);
2293   SDValue TVal = Sel.getOperand(2);
2294   SDValue FVal = Sel.getOperand(3);
2295 
2296   // FIXME: This could be generalized to non-integer comparisons.
2297   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2298     return Op;
2299 
2300   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2301   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2302 
2303   // The values aren't constants, this isn't the pattern we're looking for.
2304   if (!CFVal || !CTVal)
2305     return Op;
2306 
2307   // We can commute the SELECT_CC by inverting the condition.  This
2308   // might be needed to make this fit into a CSINV pattern.
2309   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2310     std::swap(TVal, FVal);
2311     std::swap(CTVal, CFVal);
2312     CC = ISD::getSetCCInverse(CC, true);
2313   }
2314 
2315   // If the constants line up, perform the transform!
2316   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2317     SDValue CCVal;
2318     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2319 
2320     FVal = Other;
2321     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2322                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2323 
2324     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2325                        CCVal, Cmp);
2326   }
2327 
2328   return Op;
2329 }
2330 
2331 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2332   EVT VT = Op.getValueType();
2333 
2334   // Let legalize expand this if it isn't a legal type yet.
2335   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2336     return SDValue();
2337 
2338   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2339 
2340   unsigned Opc;
2341   bool ExtraOp = false;
2342   switch (Op.getOpcode()) {
2343   default:
2344     llvm_unreachable("Invalid code");
2345   case ISD::ADDC:
2346     Opc = AArch64ISD::ADDS;
2347     break;
2348   case ISD::SUBC:
2349     Opc = AArch64ISD::SUBS;
2350     break;
2351   case ISD::ADDE:
2352     Opc = AArch64ISD::ADCS;
2353     ExtraOp = true;
2354     break;
2355   case ISD::SUBE:
2356     Opc = AArch64ISD::SBCS;
2357     ExtraOp = true;
2358     break;
2359   }
2360 
2361   if (!ExtraOp)
2362     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2363   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2364                      Op.getOperand(2));
2365 }
2366 
2367 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2368   // Let legalize expand this if it isn't a legal type yet.
2369   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2370     return SDValue();
2371 
2372   SDLoc dl(Op);
2373   AArch64CC::CondCode CC;
2374   // The actual operation that sets the overflow or carry flag.
2375   SDValue Value, Overflow;
2376   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2377 
2378   // We use 0 and 1 as false and true values.
2379   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2380   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2381 
2382   // We use an inverted condition, because the conditional select is inverted
2383   // too. This will allow it to be selected to a single instruction:
2384   // CSINC Wd, WZR, WZR, invert(cond).
2385   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2386   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2387                          CCVal, Overflow);
2388 
2389   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2390   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2391 }
2392 
2393 // Prefetch operands are:
2394 // 1: Address to prefetch
2395 // 2: bool isWrite
2396 // 3: int locality (0 = no locality ... 3 = extreme locality)
2397 // 4: bool isDataCache
2398 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2399   SDLoc DL(Op);
2400   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2401   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2402   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2403 
2404   bool IsStream = !Locality;
2405   // When the locality number is set
2406   if (Locality) {
2407     // The front-end should have filtered out the out-of-range values
2408     assert(Locality <= 3 && "Prefetch locality out-of-range");
2409     // The locality degree is the opposite of the cache speed.
2410     // Put the number the other way around.
2411     // The encoding starts at 0 for level 1
2412     Locality = 3 - Locality;
2413   }
2414 
2415   // built the mask value encoding the expected behavior.
2416   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2417                    (!IsData << 3) |     // IsDataCache bit
2418                    (Locality << 1) |    // Cache level bits
2419                    (unsigned)IsStream;  // Stream bit
2420   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2421                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2422 }
2423 
2424 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2425                                               SelectionDAG &DAG) const {
2426   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2427 
2428   RTLIB::Libcall LC;
2429   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2430 
2431   return LowerF128Call(Op, DAG, LC);
2432 }
2433 
2434 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2435                                              SelectionDAG &DAG) const {
2436   if (Op.getOperand(0).getValueType() != MVT::f128) {
2437     // It's legal except when f128 is involved
2438     return Op;
2439   }
2440 
2441   RTLIB::Libcall LC;
2442   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2443 
2444   // FP_ROUND node has a second operand indicating whether it is known to be
2445   // precise. That doesn't take part in the LibCall so we can't directly use
2446   // LowerF128Call.
2447   SDValue SrcVal = Op.getOperand(0);
2448   MakeLibCallOptions CallOptions;
2449   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions,
2450                      SDLoc(Op)).first;
2451 }
2452 
2453 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2454                                                     SelectionDAG &DAG) const {
2455   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2456   // Any additional optimization in this function should be recorded
2457   // in the cost tables.
2458   EVT InVT = Op.getOperand(0).getValueType();
2459   EVT VT = Op.getValueType();
2460   unsigned NumElts = InVT.getVectorNumElements();
2461 
2462   // f16 conversions are promoted to f32 when full fp16 is not supported.
2463   if (InVT.getVectorElementType() == MVT::f16 &&
2464       !Subtarget->hasFullFP16()) {
2465     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2466     SDLoc dl(Op);
2467     return DAG.getNode(
2468         Op.getOpcode(), dl, Op.getValueType(),
2469         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2470   }
2471 
2472   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2473     SDLoc dl(Op);
2474     SDValue Cv =
2475         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2476                     Op.getOperand(0));
2477     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2478   }
2479 
2480   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2481     SDLoc dl(Op);
2482     MVT ExtVT =
2483         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2484                          VT.getVectorNumElements());
2485     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2486     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2487   }
2488 
2489   // Type changing conversions are illegal.
2490   return Op;
2491 }
2492 
2493 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2494                                               SelectionDAG &DAG) const {
2495   if (Op.getOperand(0).getValueType().isVector())
2496     return LowerVectorFP_TO_INT(Op, DAG);
2497 
2498   // f16 conversions are promoted to f32 when full fp16 is not supported.
2499   if (Op.getOperand(0).getValueType() == MVT::f16 &&
2500       !Subtarget->hasFullFP16()) {
2501     SDLoc dl(Op);
2502     return DAG.getNode(
2503         Op.getOpcode(), dl, Op.getValueType(),
2504         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2505   }
2506 
2507   if (Op.getOperand(0).getValueType() != MVT::f128) {
2508     // It's legal except when f128 is involved
2509     return Op;
2510   }
2511 
2512   RTLIB::Libcall LC;
2513   if (Op.getOpcode() == ISD::FP_TO_SINT)
2514     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2515   else
2516     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2517 
2518   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2519   MakeLibCallOptions CallOptions;
2520   return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first;
2521 }
2522 
2523 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2524   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2525   // Any additional optimization in this function should be recorded
2526   // in the cost tables.
2527   EVT VT = Op.getValueType();
2528   SDLoc dl(Op);
2529   SDValue In = Op.getOperand(0);
2530   EVT InVT = In.getValueType();
2531 
2532   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2533     MVT CastVT =
2534         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2535                          InVT.getVectorNumElements());
2536     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2537     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2538   }
2539 
2540   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2541     unsigned CastOpc =
2542         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2543     EVT CastVT = VT.changeVectorElementTypeToInteger();
2544     In = DAG.getNode(CastOpc, dl, CastVT, In);
2545     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2546   }
2547 
2548   return Op;
2549 }
2550 
2551 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2552                                             SelectionDAG &DAG) const {
2553   if (Op.getValueType().isVector())
2554     return LowerVectorINT_TO_FP(Op, DAG);
2555 
2556   // f16 conversions are promoted to f32 when full fp16 is not supported.
2557   if (Op.getValueType() == MVT::f16 &&
2558       !Subtarget->hasFullFP16()) {
2559     SDLoc dl(Op);
2560     return DAG.getNode(
2561         ISD::FP_ROUND, dl, MVT::f16,
2562         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2563         DAG.getIntPtrConstant(0, dl));
2564   }
2565 
2566   // i128 conversions are libcalls.
2567   if (Op.getOperand(0).getValueType() == MVT::i128)
2568     return SDValue();
2569 
2570   // Other conversions are legal, unless it's to the completely software-based
2571   // fp128.
2572   if (Op.getValueType() != MVT::f128)
2573     return Op;
2574 
2575   RTLIB::Libcall LC;
2576   if (Op.getOpcode() == ISD::SINT_TO_FP)
2577     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2578   else
2579     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2580 
2581   return LowerF128Call(Op, DAG, LC);
2582 }
2583 
2584 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2585                                             SelectionDAG &DAG) const {
2586   // For iOS, we want to call an alternative entry point: __sincos_stret,
2587   // which returns the values in two S / D registers.
2588   SDLoc dl(Op);
2589   SDValue Arg = Op.getOperand(0);
2590   EVT ArgVT = Arg.getValueType();
2591   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2592 
2593   ArgListTy Args;
2594   ArgListEntry Entry;
2595 
2596   Entry.Node = Arg;
2597   Entry.Ty = ArgTy;
2598   Entry.IsSExt = false;
2599   Entry.IsZExt = false;
2600   Args.push_back(Entry);
2601 
2602   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2603                                         : RTLIB::SINCOS_STRET_F32;
2604   const char *LibcallName = getLibcallName(LC);
2605   SDValue Callee =
2606       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2607 
2608   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2609   TargetLowering::CallLoweringInfo CLI(DAG);
2610   CLI.setDebugLoc(dl)
2611       .setChain(DAG.getEntryNode())
2612       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2613 
2614   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2615   return CallResult.first;
2616 }
2617 
2618 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2619   if (Op.getValueType() != MVT::f16)
2620     return SDValue();
2621 
2622   assert(Op.getOperand(0).getValueType() == MVT::i16);
2623   SDLoc DL(Op);
2624 
2625   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2626   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2627   return SDValue(
2628       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2629                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2630       0);
2631 }
2632 
2633 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2634   if (OrigVT.getSizeInBits() >= 64)
2635     return OrigVT;
2636 
2637   assert(OrigVT.isSimple() && "Expecting a simple value type");
2638 
2639   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2640   switch (OrigSimpleTy) {
2641   default: llvm_unreachable("Unexpected Vector Type");
2642   case MVT::v2i8:
2643   case MVT::v2i16:
2644      return MVT::v2i32;
2645   case MVT::v4i8:
2646     return  MVT::v4i16;
2647   }
2648 }
2649 
2650 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2651                                                  const EVT &OrigTy,
2652                                                  const EVT &ExtTy,
2653                                                  unsigned ExtOpcode) {
2654   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2655   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2656   // 64-bits we need to insert a new extension so that it will be 64-bits.
2657   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2658   if (OrigTy.getSizeInBits() >= 64)
2659     return N;
2660 
2661   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2662   EVT NewVT = getExtensionTo64Bits(OrigTy);
2663 
2664   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2665 }
2666 
2667 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2668                                    bool isSigned) {
2669   EVT VT = N->getValueType(0);
2670 
2671   if (N->getOpcode() != ISD::BUILD_VECTOR)
2672     return false;
2673 
2674   for (const SDValue &Elt : N->op_values()) {
2675     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2676       unsigned EltSize = VT.getScalarSizeInBits();
2677       unsigned HalfSize = EltSize / 2;
2678       if (isSigned) {
2679         if (!isIntN(HalfSize, C->getSExtValue()))
2680           return false;
2681       } else {
2682         if (!isUIntN(HalfSize, C->getZExtValue()))
2683           return false;
2684       }
2685       continue;
2686     }
2687     return false;
2688   }
2689 
2690   return true;
2691 }
2692 
2693 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2694   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2695     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2696                                              N->getOperand(0)->getValueType(0),
2697                                              N->getValueType(0),
2698                                              N->getOpcode());
2699 
2700   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2701   EVT VT = N->getValueType(0);
2702   SDLoc dl(N);
2703   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2704   unsigned NumElts = VT.getVectorNumElements();
2705   MVT TruncVT = MVT::getIntegerVT(EltSize);
2706   SmallVector<SDValue, 8> Ops;
2707   for (unsigned i = 0; i != NumElts; ++i) {
2708     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2709     const APInt &CInt = C->getAPIntValue();
2710     // Element types smaller than 32 bits are not legal, so use i32 elements.
2711     // The values are implicitly truncated so sext vs. zext doesn't matter.
2712     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2713   }
2714   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2715 }
2716 
2717 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2718   return N->getOpcode() == ISD::SIGN_EXTEND ||
2719          isExtendedBUILD_VECTOR(N, DAG, true);
2720 }
2721 
2722 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2723   return N->getOpcode() == ISD::ZERO_EXTEND ||
2724          isExtendedBUILD_VECTOR(N, DAG, false);
2725 }
2726 
2727 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2728   unsigned Opcode = N->getOpcode();
2729   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2730     SDNode *N0 = N->getOperand(0).getNode();
2731     SDNode *N1 = N->getOperand(1).getNode();
2732     return N0->hasOneUse() && N1->hasOneUse() &&
2733       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2734   }
2735   return false;
2736 }
2737 
2738 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2739   unsigned Opcode = N->getOpcode();
2740   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2741     SDNode *N0 = N->getOperand(0).getNode();
2742     SDNode *N1 = N->getOperand(1).getNode();
2743     return N0->hasOneUse() && N1->hasOneUse() &&
2744       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2745   }
2746   return false;
2747 }
2748 
2749 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2750                                                 SelectionDAG &DAG) const {
2751   // The rounding mode is in bits 23:22 of the FPSCR.
2752   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2753   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2754   // so that the shift + and get folded into a bitfield extract.
2755   SDLoc dl(Op);
2756 
2757   SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2758                                 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2759                                                 MVT::i64));
2760   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2761   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2762                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2763   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2764                               DAG.getConstant(22, dl, MVT::i32));
2765   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2766                      DAG.getConstant(3, dl, MVT::i32));
2767 }
2768 
2769 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2770   // Multiplications are only custom-lowered for 128-bit vectors so that
2771   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2772   EVT VT = Op.getValueType();
2773   assert(VT.is128BitVector() && VT.isInteger() &&
2774          "unexpected type for custom-lowering ISD::MUL");
2775   SDNode *N0 = Op.getOperand(0).getNode();
2776   SDNode *N1 = Op.getOperand(1).getNode();
2777   unsigned NewOpc = 0;
2778   bool isMLA = false;
2779   bool isN0SExt = isSignExtended(N0, DAG);
2780   bool isN1SExt = isSignExtended(N1, DAG);
2781   if (isN0SExt && isN1SExt)
2782     NewOpc = AArch64ISD::SMULL;
2783   else {
2784     bool isN0ZExt = isZeroExtended(N0, DAG);
2785     bool isN1ZExt = isZeroExtended(N1, DAG);
2786     if (isN0ZExt && isN1ZExt)
2787       NewOpc = AArch64ISD::UMULL;
2788     else if (isN1SExt || isN1ZExt) {
2789       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2790       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2791       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2792         NewOpc = AArch64ISD::SMULL;
2793         isMLA = true;
2794       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2795         NewOpc =  AArch64ISD::UMULL;
2796         isMLA = true;
2797       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2798         std::swap(N0, N1);
2799         NewOpc =  AArch64ISD::UMULL;
2800         isMLA = true;
2801       }
2802     }
2803 
2804     if (!NewOpc) {
2805       if (VT == MVT::v2i64)
2806         // Fall through to expand this.  It is not legal.
2807         return SDValue();
2808       else
2809         // Other vector multiplications are legal.
2810         return Op;
2811     }
2812   }
2813 
2814   // Legalize to a S/UMULL instruction
2815   SDLoc DL(Op);
2816   SDValue Op0;
2817   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2818   if (!isMLA) {
2819     Op0 = skipExtensionForVectorMULL(N0, DAG);
2820     assert(Op0.getValueType().is64BitVector() &&
2821            Op1.getValueType().is64BitVector() &&
2822            "unexpected types for extended operands to VMULL");
2823     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2824   }
2825   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2826   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2827   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2828   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2829   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2830   EVT Op1VT = Op1.getValueType();
2831   return DAG.getNode(N0->getOpcode(), DL, VT,
2832                      DAG.getNode(NewOpc, DL, VT,
2833                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2834                      DAG.getNode(NewOpc, DL, VT,
2835                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2836 }
2837 
2838 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2839                                                      SelectionDAG &DAG) const {
2840   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2841   SDLoc dl(Op);
2842   switch (IntNo) {
2843   default: return SDValue();    // Don't custom lower most intrinsics.
2844   case Intrinsic::thread_pointer: {
2845     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2846     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2847   }
2848   case Intrinsic::aarch64_neon_abs: {
2849     EVT Ty = Op.getValueType();
2850     if (Ty == MVT::i64) {
2851       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2852                                    Op.getOperand(1));
2853       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2854       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2855     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2856       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2857     } else {
2858       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2859     }
2860   }
2861   case Intrinsic::aarch64_neon_smax:
2862     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2863                        Op.getOperand(1), Op.getOperand(2));
2864   case Intrinsic::aarch64_neon_umax:
2865     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2866                        Op.getOperand(1), Op.getOperand(2));
2867   case Intrinsic::aarch64_neon_smin:
2868     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2869                        Op.getOperand(1), Op.getOperand(2));
2870   case Intrinsic::aarch64_neon_umin:
2871     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2872                        Op.getOperand(1), Op.getOperand(2));
2873 
2874   case Intrinsic::aarch64_sve_sunpkhi:
2875     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
2876                        Op.getOperand(1));
2877   case Intrinsic::aarch64_sve_sunpklo:
2878     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
2879                        Op.getOperand(1));
2880   case Intrinsic::aarch64_sve_uunpkhi:
2881     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
2882                        Op.getOperand(1));
2883   case Intrinsic::aarch64_sve_uunpklo:
2884     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
2885                        Op.getOperand(1));
2886 
2887   case Intrinsic::localaddress: {
2888     const auto &MF = DAG.getMachineFunction();
2889     const auto *RegInfo = Subtarget->getRegisterInfo();
2890     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
2891     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2892                               Op.getSimpleValueType());
2893   }
2894 
2895   case Intrinsic::eh_recoverfp: {
2896     // FIXME: This needs to be implemented to correctly handle highly aligned
2897     // stack objects. For now we simply return the incoming FP. Refer D53541
2898     // for more details.
2899     SDValue FnOp = Op.getOperand(1);
2900     SDValue IncomingFPOp = Op.getOperand(2);
2901     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2902     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2903     if (!Fn)
2904       report_fatal_error(
2905           "llvm.eh.recoverfp must take a function as the first argument");
2906     return IncomingFPOp;
2907   }
2908   }
2909 }
2910 
2911 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
2912   return ExtVal.getValueType().isScalableVector();
2913 }
2914 
2915 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2916 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2917                                         EVT VT, EVT MemVT,
2918                                         SelectionDAG &DAG) {
2919   assert(VT.isVector() && "VT should be a vector type");
2920   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2921 
2922   SDValue Value = ST->getValue();
2923 
2924   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2925   // the word lane which represent the v4i8 subvector.  It optimizes the store
2926   // to:
2927   //
2928   //   xtn  v0.8b, v0.8h
2929   //   str  s0, [x0]
2930 
2931   SDValue Undef = DAG.getUNDEF(MVT::i16);
2932   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2933                                         {Undef, Undef, Undef, Undef});
2934 
2935   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2936                                  Value, UndefVec);
2937   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2938 
2939   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2940   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2941                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
2942 
2943   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2944                       ST->getBasePtr(), ST->getMemOperand());
2945 }
2946 
2947 // Custom lowering for any store, vector or scalar and/or default or with
2948 // a truncate operations.  Currently only custom lower truncate operation
2949 // from vector v4i16 to v4i8.
2950 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2951                                           SelectionDAG &DAG) const {
2952   SDLoc Dl(Op);
2953   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2954   assert (StoreNode && "Can only custom lower store nodes");
2955 
2956   SDValue Value = StoreNode->getValue();
2957 
2958   EVT VT = Value.getValueType();
2959   EVT MemVT = StoreNode->getMemoryVT();
2960 
2961   assert (VT.isVector() && "Can only custom lower vector store types");
2962 
2963   unsigned AS = StoreNode->getAddressSpace();
2964   unsigned Align = StoreNode->getAlignment();
2965   if (Align < MemVT.getStoreSize() &&
2966       !allowsMisalignedMemoryAccesses(
2967           MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
2968     return scalarizeVectorStore(StoreNode, DAG);
2969   }
2970 
2971   if (StoreNode->isTruncatingStore()) {
2972     return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2973   }
2974 
2975   return SDValue();
2976 }
2977 
2978 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2979                                               SelectionDAG &DAG) const {
2980   LLVM_DEBUG(dbgs() << "Custom lowering: ");
2981   LLVM_DEBUG(Op.dump());
2982 
2983   switch (Op.getOpcode()) {
2984   default:
2985     llvm_unreachable("unimplemented operand");
2986     return SDValue();
2987   case ISD::BITCAST:
2988     return LowerBITCAST(Op, DAG);
2989   case ISD::GlobalAddress:
2990     return LowerGlobalAddress(Op, DAG);
2991   case ISD::GlobalTLSAddress:
2992     return LowerGlobalTLSAddress(Op, DAG);
2993   case ISD::SETCC:
2994     return LowerSETCC(Op, DAG);
2995   case ISD::BR_CC:
2996     return LowerBR_CC(Op, DAG);
2997   case ISD::SELECT:
2998     return LowerSELECT(Op, DAG);
2999   case ISD::SELECT_CC:
3000     return LowerSELECT_CC(Op, DAG);
3001   case ISD::JumpTable:
3002     return LowerJumpTable(Op, DAG);
3003   case ISD::BR_JT:
3004     return LowerBR_JT(Op, DAG);
3005   case ISD::ConstantPool:
3006     return LowerConstantPool(Op, DAG);
3007   case ISD::BlockAddress:
3008     return LowerBlockAddress(Op, DAG);
3009   case ISD::VASTART:
3010     return LowerVASTART(Op, DAG);
3011   case ISD::VACOPY:
3012     return LowerVACOPY(Op, DAG);
3013   case ISD::VAARG:
3014     return LowerVAARG(Op, DAG);
3015   case ISD::ADDC:
3016   case ISD::ADDE:
3017   case ISD::SUBC:
3018   case ISD::SUBE:
3019     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3020   case ISD::SADDO:
3021   case ISD::UADDO:
3022   case ISD::SSUBO:
3023   case ISD::USUBO:
3024   case ISD::SMULO:
3025   case ISD::UMULO:
3026     return LowerXALUO(Op, DAG);
3027   case ISD::FADD:
3028     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3029   case ISD::FSUB:
3030     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3031   case ISD::FMUL:
3032     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3033   case ISD::FDIV:
3034     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3035   case ISD::FP_ROUND:
3036     return LowerFP_ROUND(Op, DAG);
3037   case ISD::FP_EXTEND:
3038     return LowerFP_EXTEND(Op, DAG);
3039   case ISD::FRAMEADDR:
3040     return LowerFRAMEADDR(Op, DAG);
3041   case ISD::SPONENTRY:
3042     return LowerSPONENTRY(Op, DAG);
3043   case ISD::RETURNADDR:
3044     return LowerRETURNADDR(Op, DAG);
3045   case ISD::ADDROFRETURNADDR:
3046     return LowerADDROFRETURNADDR(Op, DAG);
3047   case ISD::INSERT_VECTOR_ELT:
3048     return LowerINSERT_VECTOR_ELT(Op, DAG);
3049   case ISD::EXTRACT_VECTOR_ELT:
3050     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3051   case ISD::BUILD_VECTOR:
3052     return LowerBUILD_VECTOR(Op, DAG);
3053   case ISD::VECTOR_SHUFFLE:
3054     return LowerVECTOR_SHUFFLE(Op, DAG);
3055   case ISD::SPLAT_VECTOR:
3056     return LowerSPLAT_VECTOR(Op, DAG);
3057   case ISD::EXTRACT_SUBVECTOR:
3058     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3059   case ISD::SRA:
3060   case ISD::SRL:
3061   case ISD::SHL:
3062     return LowerVectorSRA_SRL_SHL(Op, DAG);
3063   case ISD::SHL_PARTS:
3064     return LowerShiftLeftParts(Op, DAG);
3065   case ISD::SRL_PARTS:
3066   case ISD::SRA_PARTS:
3067     return LowerShiftRightParts(Op, DAG);
3068   case ISD::CTPOP:
3069     return LowerCTPOP(Op, DAG);
3070   case ISD::FCOPYSIGN:
3071     return LowerFCOPYSIGN(Op, DAG);
3072   case ISD::OR:
3073     return LowerVectorOR(Op, DAG);
3074   case ISD::XOR:
3075     return LowerXOR(Op, DAG);
3076   case ISD::PREFETCH:
3077     return LowerPREFETCH(Op, DAG);
3078   case ISD::SINT_TO_FP:
3079   case ISD::UINT_TO_FP:
3080     return LowerINT_TO_FP(Op, DAG);
3081   case ISD::FP_TO_SINT:
3082   case ISD::FP_TO_UINT:
3083     return LowerFP_TO_INT(Op, DAG);
3084   case ISD::FSINCOS:
3085     return LowerFSINCOS(Op, DAG);
3086   case ISD::FLT_ROUNDS_:
3087     return LowerFLT_ROUNDS_(Op, DAG);
3088   case ISD::MUL:
3089     return LowerMUL(Op, DAG);
3090   case ISD::INTRINSIC_WO_CHAIN:
3091     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3092   case ISD::STORE:
3093     return LowerSTORE(Op, DAG);
3094   case ISD::VECREDUCE_ADD:
3095   case ISD::VECREDUCE_SMAX:
3096   case ISD::VECREDUCE_SMIN:
3097   case ISD::VECREDUCE_UMAX:
3098   case ISD::VECREDUCE_UMIN:
3099   case ISD::VECREDUCE_FMAX:
3100   case ISD::VECREDUCE_FMIN:
3101     return LowerVECREDUCE(Op, DAG);
3102   case ISD::ATOMIC_LOAD_SUB:
3103     return LowerATOMIC_LOAD_SUB(Op, DAG);
3104   case ISD::ATOMIC_LOAD_AND:
3105     return LowerATOMIC_LOAD_AND(Op, DAG);
3106   case ISD::DYNAMIC_STACKALLOC:
3107     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3108   }
3109 }
3110 
3111 //===----------------------------------------------------------------------===//
3112 //                      Calling Convention Implementation
3113 //===----------------------------------------------------------------------===//
3114 
3115 /// Selects the correct CCAssignFn for a given CallingConvention value.
3116 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3117                                                      bool IsVarArg) const {
3118   switch (CC) {
3119   default:
3120     report_fatal_error("Unsupported calling convention.");
3121   case CallingConv::WebKit_JS:
3122     return CC_AArch64_WebKit_JS;
3123   case CallingConv::GHC:
3124     return CC_AArch64_GHC;
3125   case CallingConv::C:
3126   case CallingConv::Fast:
3127   case CallingConv::PreserveMost:
3128   case CallingConv::CXX_FAST_TLS:
3129   case CallingConv::Swift:
3130     if (Subtarget->isTargetWindows() && IsVarArg)
3131       return CC_AArch64_Win64_VarArg;
3132     if (!Subtarget->isTargetDarwin())
3133       return CC_AArch64_AAPCS;
3134     if (!IsVarArg)
3135       return CC_AArch64_DarwinPCS;
3136     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3137                                       : CC_AArch64_DarwinPCS_VarArg;
3138    case CallingConv::Win64:
3139     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3140    case CallingConv::CFGuard_Check:
3141      return CC_AArch64_Win64_CFGuard_Check;
3142    case CallingConv::AArch64_VectorCall:
3143      return CC_AArch64_AAPCS;
3144   }
3145 }
3146 
3147 CCAssignFn *
3148 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3149   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3150                                       : RetCC_AArch64_AAPCS;
3151 }
3152 
3153 SDValue AArch64TargetLowering::LowerFormalArguments(
3154     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3155     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3156     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3157   MachineFunction &MF = DAG.getMachineFunction();
3158   MachineFrameInfo &MFI = MF.getFrameInfo();
3159   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3160 
3161   // Assign locations to all of the incoming arguments.
3162   SmallVector<CCValAssign, 16> ArgLocs;
3163   DenseMap<unsigned, SDValue> CopiedRegs;
3164   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3165                  *DAG.getContext());
3166 
3167   // At this point, Ins[].VT may already be promoted to i32. To correctly
3168   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3169   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3170   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3171   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3172   // LocVT.
3173   unsigned NumArgs = Ins.size();
3174   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3175   unsigned CurArgIdx = 0;
3176   for (unsigned i = 0; i != NumArgs; ++i) {
3177     MVT ValVT = Ins[i].VT;
3178     if (Ins[i].isOrigArg()) {
3179       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3180       CurArgIdx = Ins[i].getOrigArgIndex();
3181 
3182       // Get type of the original argument.
3183       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3184                                   /*AllowUnknown*/ true);
3185       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3186       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3187       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3188         ValVT = MVT::i8;
3189       else if (ActualMVT == MVT::i16)
3190         ValVT = MVT::i16;
3191     }
3192     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3193     bool Res =
3194         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3195     assert(!Res && "Call operand has unhandled type");
3196     (void)Res;
3197   }
3198   assert(ArgLocs.size() == Ins.size());
3199   SmallVector<SDValue, 16> ArgValues;
3200   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3201     CCValAssign &VA = ArgLocs[i];
3202 
3203     if (Ins[i].Flags.isByVal()) {
3204       // Byval is used for HFAs in the PCS, but the system should work in a
3205       // non-compliant manner for larger structs.
3206       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3207       int Size = Ins[i].Flags.getByValSize();
3208       unsigned NumRegs = (Size + 7) / 8;
3209 
3210       // FIXME: This works on big-endian for composite byvals, which are the common
3211       // case. It should also work for fundamental types too.
3212       unsigned FrameIdx =
3213         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3214       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3215       InVals.push_back(FrameIdxN);
3216 
3217       continue;
3218     }
3219 
3220     SDValue ArgValue;
3221     if (VA.isRegLoc()) {
3222       // Arguments stored in registers.
3223       EVT RegVT = VA.getLocVT();
3224       const TargetRegisterClass *RC;
3225 
3226       if (RegVT == MVT::i32)
3227         RC = &AArch64::GPR32RegClass;
3228       else if (RegVT == MVT::i64)
3229         RC = &AArch64::GPR64RegClass;
3230       else if (RegVT == MVT::f16)
3231         RC = &AArch64::FPR16RegClass;
3232       else if (RegVT == MVT::f32)
3233         RC = &AArch64::FPR32RegClass;
3234       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3235         RC = &AArch64::FPR64RegClass;
3236       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3237         RC = &AArch64::FPR128RegClass;
3238       else if (RegVT.isScalableVector() &&
3239                RegVT.getVectorElementType() == MVT::i1)
3240         RC = &AArch64::PPRRegClass;
3241       else if (RegVT.isScalableVector())
3242         RC = &AArch64::ZPRRegClass;
3243       else
3244         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3245 
3246       // Transform the arguments in physical registers into virtual ones.
3247       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3248       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3249 
3250       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3251       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3252       // truncate to the right size.
3253       switch (VA.getLocInfo()) {
3254       default:
3255         llvm_unreachable("Unknown loc info!");
3256       case CCValAssign::Full:
3257         break;
3258       case CCValAssign::Indirect:
3259         assert(VA.getValVT().isScalableVector() &&
3260                "Only scalable vectors can be passed indirectly");
3261         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3262       case CCValAssign::BCvt:
3263         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3264         break;
3265       case CCValAssign::AExt:
3266       case CCValAssign::SExt:
3267       case CCValAssign::ZExt:
3268         break;
3269       case CCValAssign::AExtUpper:
3270         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3271                                DAG.getConstant(32, DL, RegVT));
3272         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3273         break;
3274       }
3275     } else { // VA.isRegLoc()
3276       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3277       unsigned ArgOffset = VA.getLocMemOffset();
3278       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3279 
3280       uint32_t BEAlign = 0;
3281       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3282           !Ins[i].Flags.isInConsecutiveRegs())
3283         BEAlign = 8 - ArgSize;
3284 
3285       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3286 
3287       // Create load nodes to retrieve arguments from the stack.
3288       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3289 
3290       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3291       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3292       MVT MemVT = VA.getValVT();
3293 
3294       switch (VA.getLocInfo()) {
3295       default:
3296         break;
3297       case CCValAssign::Trunc:
3298       case CCValAssign::BCvt:
3299         MemVT = VA.getLocVT();
3300         break;
3301       case CCValAssign::Indirect:
3302         assert(VA.getValVT().isScalableVector() &&
3303                "Only scalable vectors can be passed indirectly");
3304         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3305       case CCValAssign::SExt:
3306         ExtType = ISD::SEXTLOAD;
3307         break;
3308       case CCValAssign::ZExt:
3309         ExtType = ISD::ZEXTLOAD;
3310         break;
3311       case CCValAssign::AExt:
3312         ExtType = ISD::EXTLOAD;
3313         break;
3314       }
3315 
3316       ArgValue = DAG.getExtLoad(
3317           ExtType, DL, VA.getLocVT(), Chain, FIN,
3318           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3319           MemVT);
3320 
3321     }
3322     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3323       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3324                              ArgValue, DAG.getValueType(MVT::i32));
3325     InVals.push_back(ArgValue);
3326   }
3327 
3328   // varargs
3329   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3330   if (isVarArg) {
3331     if (!Subtarget->isTargetDarwin() || IsWin64) {
3332       // The AAPCS variadic function ABI is identical to the non-variadic
3333       // one. As a result there may be more arguments in registers and we should
3334       // save them for future reference.
3335       // Win64 variadic functions also pass arguments in registers, but all float
3336       // arguments are passed in integer registers.
3337       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3338     }
3339 
3340     // This will point to the next argument passed via stack.
3341     unsigned StackOffset = CCInfo.getNextStackOffset();
3342     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3343     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3344     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3345 
3346     if (MFI.hasMustTailInVarArgFunc()) {
3347       SmallVector<MVT, 2> RegParmTypes;
3348       RegParmTypes.push_back(MVT::i64);
3349       RegParmTypes.push_back(MVT::f128);
3350       // Compute the set of forwarded registers. The rest are scratch.
3351       SmallVectorImpl<ForwardedRegister> &Forwards =
3352                                        FuncInfo->getForwardedMustTailRegParms();
3353       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3354                                                CC_AArch64_AAPCS);
3355 
3356       // Conservatively forward X8, since it might be used for aggregate return.
3357       if (!CCInfo.isAllocated(AArch64::X8)) {
3358         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3359         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3360       }
3361     }
3362   }
3363 
3364   // On Windows, InReg pointers must be returned, so record the pointer in a
3365   // virtual register at the start of the function so it can be returned in the
3366   // epilogue.
3367   if (IsWin64) {
3368     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3369       if (Ins[I].Flags.isInReg()) {
3370         assert(!FuncInfo->getSRetReturnReg());
3371 
3372         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3373         Register Reg =
3374             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3375         FuncInfo->setSRetReturnReg(Reg);
3376 
3377         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3378         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3379         break;
3380       }
3381     }
3382   }
3383 
3384   unsigned StackArgSize = CCInfo.getNextStackOffset();
3385   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3386   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3387     // This is a non-standard ABI so by fiat I say we're allowed to make full
3388     // use of the stack area to be popped, which must be aligned to 16 bytes in
3389     // any case:
3390     StackArgSize = alignTo(StackArgSize, 16);
3391 
3392     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3393     // a multiple of 16.
3394     FuncInfo->setArgumentStackToRestore(StackArgSize);
3395 
3396     // This realignment carries over to the available bytes below. Our own
3397     // callers will guarantee the space is free by giving an aligned value to
3398     // CALLSEQ_START.
3399   }
3400   // Even if we're not expected to free up the space, it's useful to know how
3401   // much is there while considering tail calls (because we can reuse it).
3402   FuncInfo->setBytesInStackArgArea(StackArgSize);
3403 
3404   if (Subtarget->hasCustomCallingConv())
3405     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3406 
3407   return Chain;
3408 }
3409 
3410 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3411                                                 SelectionDAG &DAG,
3412                                                 const SDLoc &DL,
3413                                                 SDValue &Chain) const {
3414   MachineFunction &MF = DAG.getMachineFunction();
3415   MachineFrameInfo &MFI = MF.getFrameInfo();
3416   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3417   auto PtrVT = getPointerTy(DAG.getDataLayout());
3418   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3419 
3420   SmallVector<SDValue, 8> MemOps;
3421 
3422   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3423                                           AArch64::X3, AArch64::X4, AArch64::X5,
3424                                           AArch64::X6, AArch64::X7 };
3425   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3426   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3427 
3428   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3429   int GPRIdx = 0;
3430   if (GPRSaveSize != 0) {
3431     if (IsWin64) {
3432       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3433       if (GPRSaveSize & 15)
3434         // The extra size here, if triggered, will always be 8.
3435         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3436     } else
3437       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3438 
3439     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3440 
3441     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3442       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3443       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3444       SDValue Store = DAG.getStore(
3445           Val.getValue(1), DL, Val, FIN,
3446           IsWin64
3447               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3448                                                   GPRIdx,
3449                                                   (i - FirstVariadicGPR) * 8)
3450               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3451       MemOps.push_back(Store);
3452       FIN =
3453           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3454     }
3455   }
3456   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3457   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3458 
3459   if (Subtarget->hasFPARMv8() && !IsWin64) {
3460     static const MCPhysReg FPRArgRegs[] = {
3461         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3462         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3463     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3464     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3465 
3466     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3467     int FPRIdx = 0;
3468     if (FPRSaveSize != 0) {
3469       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3470 
3471       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3472 
3473       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3474         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3475         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3476 
3477         SDValue Store = DAG.getStore(
3478             Val.getValue(1), DL, Val, FIN,
3479             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3480         MemOps.push_back(Store);
3481         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3482                           DAG.getConstant(16, DL, PtrVT));
3483       }
3484     }
3485     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3486     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3487   }
3488 
3489   if (!MemOps.empty()) {
3490     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3491   }
3492 }
3493 
3494 /// LowerCallResult - Lower the result values of a call into the
3495 /// appropriate copies out of appropriate physical registers.
3496 SDValue AArch64TargetLowering::LowerCallResult(
3497     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3498     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3499     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3500     SDValue ThisVal) const {
3501   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3502                           ? RetCC_AArch64_WebKit_JS
3503                           : RetCC_AArch64_AAPCS;
3504   // Assign locations to each value returned by this call.
3505   SmallVector<CCValAssign, 16> RVLocs;
3506   DenseMap<unsigned, SDValue> CopiedRegs;
3507   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3508                  *DAG.getContext());
3509   CCInfo.AnalyzeCallResult(Ins, RetCC);
3510 
3511   // Copy all of the result registers out of their specified physreg.
3512   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3513     CCValAssign VA = RVLocs[i];
3514 
3515     // Pass 'this' value directly from the argument to return value, to avoid
3516     // reg unit interference
3517     if (i == 0 && isThisReturn) {
3518       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3519              "unexpected return calling convention register assignment");
3520       InVals.push_back(ThisVal);
3521       continue;
3522     }
3523 
3524     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3525     // allows one use of a physreg per block.
3526     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3527     if (!Val) {
3528       Val =
3529           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3530       Chain = Val.getValue(1);
3531       InFlag = Val.getValue(2);
3532       CopiedRegs[VA.getLocReg()] = Val;
3533     }
3534 
3535     switch (VA.getLocInfo()) {
3536     default:
3537       llvm_unreachable("Unknown loc info!");
3538     case CCValAssign::Full:
3539       break;
3540     case CCValAssign::BCvt:
3541       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3542       break;
3543     case CCValAssign::AExtUpper:
3544       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3545                         DAG.getConstant(32, DL, VA.getLocVT()));
3546       LLVM_FALLTHROUGH;
3547     case CCValAssign::AExt:
3548       LLVM_FALLTHROUGH;
3549     case CCValAssign::ZExt:
3550       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3551       break;
3552     }
3553 
3554     InVals.push_back(Val);
3555   }
3556 
3557   return Chain;
3558 }
3559 
3560 /// Return true if the calling convention is one that we can guarantee TCO for.
3561 static bool canGuaranteeTCO(CallingConv::ID CC) {
3562   return CC == CallingConv::Fast;
3563 }
3564 
3565 /// Return true if we might ever do TCO for calls with this calling convention.
3566 static bool mayTailCallThisCC(CallingConv::ID CC) {
3567   switch (CC) {
3568   case CallingConv::C:
3569   case CallingConv::PreserveMost:
3570   case CallingConv::Swift:
3571     return true;
3572   default:
3573     return canGuaranteeTCO(CC);
3574   }
3575 }
3576 
3577 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3578     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3579     const SmallVectorImpl<ISD::OutputArg> &Outs,
3580     const SmallVectorImpl<SDValue> &OutVals,
3581     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3582   if (!mayTailCallThisCC(CalleeCC))
3583     return false;
3584 
3585   MachineFunction &MF = DAG.getMachineFunction();
3586   const Function &CallerF = MF.getFunction();
3587   CallingConv::ID CallerCC = CallerF.getCallingConv();
3588   bool CCMatch = CallerCC == CalleeCC;
3589 
3590   // Byval parameters hand the function a pointer directly into the stack area
3591   // we want to reuse during a tail call. Working around this *is* possible (see
3592   // X86) but less efficient and uglier in LowerCall.
3593   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3594                                     e = CallerF.arg_end();
3595        i != e; ++i) {
3596     if (i->hasByValAttr())
3597       return false;
3598 
3599     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3600     // In this case, it is necessary to save/restore X0 in the callee. Tail
3601     // call opt interferes with this. So we disable tail call opt when the
3602     // caller has an argument with "inreg" attribute.
3603 
3604     // FIXME: Check whether the callee also has an "inreg" argument.
3605     if (i->hasInRegAttr())
3606       return false;
3607   }
3608 
3609   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3610     return canGuaranteeTCO(CalleeCC) && CCMatch;
3611 
3612   // Externally-defined functions with weak linkage should not be
3613   // tail-called on AArch64 when the OS does not support dynamic
3614   // pre-emption of symbols, as the AAELF spec requires normal calls
3615   // to undefined weak functions to be replaced with a NOP or jump to the
3616   // next instruction. The behaviour of branch instructions in this
3617   // situation (as used for tail calls) is implementation-defined, so we
3618   // cannot rely on the linker replacing the tail call with a return.
3619   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3620     const GlobalValue *GV = G->getGlobal();
3621     const Triple &TT = getTargetMachine().getTargetTriple();
3622     if (GV->hasExternalWeakLinkage() &&
3623         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3624       return false;
3625   }
3626 
3627   // Now we search for cases where we can use a tail call without changing the
3628   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3629   // concept.
3630 
3631   // I want anyone implementing a new calling convention to think long and hard
3632   // about this assert.
3633   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3634          "Unexpected variadic calling convention");
3635 
3636   LLVMContext &C = *DAG.getContext();
3637   if (isVarArg && !Outs.empty()) {
3638     // At least two cases here: if caller is fastcc then we can't have any
3639     // memory arguments (we'd be expected to clean up the stack afterwards). If
3640     // caller is C then we could potentially use its argument area.
3641 
3642     // FIXME: for now we take the most conservative of these in both cases:
3643     // disallow all variadic memory operands.
3644     SmallVector<CCValAssign, 16> ArgLocs;
3645     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3646 
3647     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3648     for (const CCValAssign &ArgLoc : ArgLocs)
3649       if (!ArgLoc.isRegLoc())
3650         return false;
3651   }
3652 
3653   // Check that the call results are passed in the same way.
3654   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3655                                   CCAssignFnForCall(CalleeCC, isVarArg),
3656                                   CCAssignFnForCall(CallerCC, isVarArg)))
3657     return false;
3658   // The callee has to preserve all registers the caller needs to preserve.
3659   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3660   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3661   if (!CCMatch) {
3662     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3663     if (Subtarget->hasCustomCallingConv()) {
3664       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3665       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3666     }
3667     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3668       return false;
3669   }
3670 
3671   // Nothing more to check if the callee is taking no arguments
3672   if (Outs.empty())
3673     return true;
3674 
3675   SmallVector<CCValAssign, 16> ArgLocs;
3676   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3677 
3678   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3679 
3680   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3681 
3682   // If the stack arguments for this call do not fit into our own save area then
3683   // the call cannot be made tail.
3684   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3685     return false;
3686 
3687   const MachineRegisterInfo &MRI = MF.getRegInfo();
3688   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3689     return false;
3690 
3691   return true;
3692 }
3693 
3694 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3695                                                    SelectionDAG &DAG,
3696                                                    MachineFrameInfo &MFI,
3697                                                    int ClobberedFI) const {
3698   SmallVector<SDValue, 8> ArgChains;
3699   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3700   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3701 
3702   // Include the original chain at the beginning of the list. When this is
3703   // used by target LowerCall hooks, this helps legalize find the
3704   // CALLSEQ_BEGIN node.
3705   ArgChains.push_back(Chain);
3706 
3707   // Add a chain value for each stack argument corresponding
3708   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3709                             UE = DAG.getEntryNode().getNode()->use_end();
3710        U != UE; ++U)
3711     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3712       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3713         if (FI->getIndex() < 0) {
3714           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3715           int64_t InLastByte = InFirstByte;
3716           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3717 
3718           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3719               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3720             ArgChains.push_back(SDValue(L, 1));
3721         }
3722 
3723   // Build a tokenfactor for all the chains.
3724   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3725 }
3726 
3727 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3728                                                    bool TailCallOpt) const {
3729   return CallCC == CallingConv::Fast && TailCallOpt;
3730 }
3731 
3732 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3733 /// and add input and output parameter nodes.
3734 SDValue
3735 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3736                                  SmallVectorImpl<SDValue> &InVals) const {
3737   SelectionDAG &DAG = CLI.DAG;
3738   SDLoc &DL = CLI.DL;
3739   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3740   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3741   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3742   SDValue Chain = CLI.Chain;
3743   SDValue Callee = CLI.Callee;
3744   bool &IsTailCall = CLI.IsTailCall;
3745   CallingConv::ID CallConv = CLI.CallConv;
3746   bool IsVarArg = CLI.IsVarArg;
3747 
3748   MachineFunction &MF = DAG.getMachineFunction();
3749   MachineFunction::CallSiteInfo CSInfo;
3750   bool IsThisReturn = false;
3751 
3752   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3753   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3754   bool IsSibCall = false;
3755 
3756   if (IsTailCall) {
3757     // Check if it's really possible to do a tail call.
3758     IsTailCall = isEligibleForTailCallOptimization(
3759         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3760     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3761       report_fatal_error("failed to perform tail call elimination on a call "
3762                          "site marked musttail");
3763 
3764     // A sibling call is one where we're under the usual C ABI and not planning
3765     // to change that but can still do a tail call:
3766     if (!TailCallOpt && IsTailCall)
3767       IsSibCall = true;
3768 
3769     if (IsTailCall)
3770       ++NumTailCalls;
3771   }
3772 
3773   // Analyze operands of the call, assigning locations to each operand.
3774   SmallVector<CCValAssign, 16> ArgLocs;
3775   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3776                  *DAG.getContext());
3777 
3778   if (IsVarArg) {
3779     // Handle fixed and variable vector arguments differently.
3780     // Variable vector arguments always go into memory.
3781     unsigned NumArgs = Outs.size();
3782 
3783     for (unsigned i = 0; i != NumArgs; ++i) {
3784       MVT ArgVT = Outs[i].VT;
3785       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3786       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3787                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3788       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3789       assert(!Res && "Call operand has unhandled type");
3790       (void)Res;
3791     }
3792   } else {
3793     // At this point, Outs[].VT may already be promoted to i32. To correctly
3794     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3795     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3796     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3797     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3798     // LocVT.
3799     unsigned NumArgs = Outs.size();
3800     for (unsigned i = 0; i != NumArgs; ++i) {
3801       MVT ValVT = Outs[i].VT;
3802       // Get type of the original argument.
3803       EVT ActualVT = getValueType(DAG.getDataLayout(),
3804                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3805                                   /*AllowUnknown*/ true);
3806       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3807       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3808       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3809       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3810         ValVT = MVT::i8;
3811       else if (ActualMVT == MVT::i16)
3812         ValVT = MVT::i16;
3813 
3814       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3815       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3816       assert(!Res && "Call operand has unhandled type");
3817       (void)Res;
3818     }
3819   }
3820 
3821   // Get a count of how many bytes are to be pushed on the stack.
3822   unsigned NumBytes = CCInfo.getNextStackOffset();
3823 
3824   if (IsSibCall) {
3825     // Since we're not changing the ABI to make this a tail call, the memory
3826     // operands are already available in the caller's incoming argument space.
3827     NumBytes = 0;
3828   }
3829 
3830   // FPDiff is the byte offset of the call's argument area from the callee's.
3831   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3832   // by this amount for a tail call. In a sibling call it must be 0 because the
3833   // caller will deallocate the entire stack and the callee still expects its
3834   // arguments to begin at SP+0. Completely unused for non-tail calls.
3835   int FPDiff = 0;
3836 
3837   if (IsTailCall && !IsSibCall) {
3838     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3839 
3840     // Since callee will pop argument stack as a tail call, we must keep the
3841     // popped size 16-byte aligned.
3842     NumBytes = alignTo(NumBytes, 16);
3843 
3844     // FPDiff will be negative if this tail call requires more space than we
3845     // would automatically have in our incoming argument space. Positive if we
3846     // can actually shrink the stack.
3847     FPDiff = NumReusableBytes - NumBytes;
3848 
3849     // The stack pointer must be 16-byte aligned at all times it's used for a
3850     // memory operation, which in practice means at *all* times and in
3851     // particular across call boundaries. Therefore our own arguments started at
3852     // a 16-byte aligned SP and the delta applied for the tail call should
3853     // satisfy the same constraint.
3854     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3855   }
3856 
3857   // Adjust the stack pointer for the new arguments...
3858   // These operations are automatically eliminated by the prolog/epilog pass
3859   if (!IsSibCall)
3860     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3861 
3862   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3863                                         getPointerTy(DAG.getDataLayout()));
3864 
3865   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3866   SmallSet<unsigned, 8> RegsUsed;
3867   SmallVector<SDValue, 8> MemOpChains;
3868   auto PtrVT = getPointerTy(DAG.getDataLayout());
3869 
3870   if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3871     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3872     for (const auto &F : Forwards) {
3873       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3874        RegsToPass.emplace_back(F.PReg, Val);
3875     }
3876   }
3877 
3878   // Walk the register/memloc assignments, inserting copies/loads.
3879   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3880        ++i, ++realArgIdx) {
3881     CCValAssign &VA = ArgLocs[i];
3882     SDValue Arg = OutVals[realArgIdx];
3883     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3884 
3885     // Promote the value if needed.
3886     switch (VA.getLocInfo()) {
3887     default:
3888       llvm_unreachable("Unknown loc info!");
3889     case CCValAssign::Full:
3890       break;
3891     case CCValAssign::SExt:
3892       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3893       break;
3894     case CCValAssign::ZExt:
3895       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3896       break;
3897     case CCValAssign::AExt:
3898       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3899         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3900         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3901         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3902       }
3903       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3904       break;
3905     case CCValAssign::AExtUpper:
3906       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
3907       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3908       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
3909                         DAG.getConstant(32, DL, VA.getLocVT()));
3910       break;
3911     case CCValAssign::BCvt:
3912       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
3913       break;
3914     case CCValAssign::Trunc:
3915       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
3916       break;
3917     case CCValAssign::FPExt:
3918       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3919       break;
3920     case CCValAssign::Indirect:
3921       assert(VA.getValVT().isScalableVector() &&
3922              "Only scalable vectors can be passed indirectly");
3923       llvm_unreachable("Spilling of SVE vectors not yet implemented");
3924     }
3925 
3926     if (VA.isRegLoc()) {
3927       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3928           Outs[0].VT == MVT::i64) {
3929         assert(VA.getLocVT() == MVT::i64 &&
3930                "unexpected calling convention register assignment");
3931         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3932                "unexpected use of 'returned'");
3933         IsThisReturn = true;
3934       }
3935       if (RegsUsed.count(VA.getLocReg())) {
3936         // If this register has already been used then we're trying to pack
3937         // parts of an [N x i32] into an X-register. The extension type will
3938         // take care of putting the two halves in the right place but we have to
3939         // combine them.
3940         SDValue &Bits =
3941             std::find_if(RegsToPass.begin(), RegsToPass.end(),
3942                          [=](const std::pair<unsigned, SDValue> &Elt) {
3943                            return Elt.first == VA.getLocReg();
3944                          })
3945                 ->second;
3946         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
3947         // Call site info is used for function's parameter entry value
3948         // tracking. For now we track only simple cases when parameter
3949         // is transferred through whole register.
3950         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
3951                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
3952                                       return ArgReg.Reg == VA.getLocReg();
3953                                     }),
3954                      CSInfo.end());
3955       } else {
3956         RegsToPass.emplace_back(VA.getLocReg(), Arg);
3957         RegsUsed.insert(VA.getLocReg());
3958         const TargetOptions &Options = DAG.getTarget().Options;
3959         if (Options.EnableDebugEntryValues)
3960           CSInfo.emplace_back(VA.getLocReg(), i);
3961       }
3962     } else {
3963       assert(VA.isMemLoc());
3964 
3965       SDValue DstAddr;
3966       MachinePointerInfo DstInfo;
3967 
3968       // FIXME: This works on big-endian for composite byvals, which are the
3969       // common case. It should also work for fundamental types too.
3970       uint32_t BEAlign = 0;
3971       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3972                                         : VA.getValVT().getSizeInBits();
3973       OpSize = (OpSize + 7) / 8;
3974       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3975           !Flags.isInConsecutiveRegs()) {
3976         if (OpSize < 8)
3977           BEAlign = 8 - OpSize;
3978       }
3979       unsigned LocMemOffset = VA.getLocMemOffset();
3980       int32_t Offset = LocMemOffset + BEAlign;
3981       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3982       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3983 
3984       if (IsTailCall) {
3985         Offset = Offset + FPDiff;
3986         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3987 
3988         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3989         DstInfo =
3990             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3991 
3992         // Make sure any stack arguments overlapping with where we're storing
3993         // are loaded before this eventual operation. Otherwise they'll be
3994         // clobbered.
3995         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3996       } else {
3997         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3998 
3999         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4000         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4001                                                LocMemOffset);
4002       }
4003 
4004       if (Outs[i].Flags.isByVal()) {
4005         SDValue SizeNode =
4006             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4007         SDValue Cpy = DAG.getMemcpy(
4008             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
4009             /*isVol = */ false, /*AlwaysInline = */ false,
4010             /*isTailCall = */ false,
4011             DstInfo, MachinePointerInfo());
4012 
4013         MemOpChains.push_back(Cpy);
4014       } else {
4015         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4016         // promoted to a legal register type i32, we should truncate Arg back to
4017         // i1/i8/i16.
4018         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4019             VA.getValVT() == MVT::i16)
4020           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4021 
4022         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4023         MemOpChains.push_back(Store);
4024       }
4025     }
4026   }
4027 
4028   if (!MemOpChains.empty())
4029     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4030 
4031   // Build a sequence of copy-to-reg nodes chained together with token chain
4032   // and flag operands which copy the outgoing args into the appropriate regs.
4033   SDValue InFlag;
4034   for (auto &RegToPass : RegsToPass) {
4035     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4036                              RegToPass.second, InFlag);
4037     InFlag = Chain.getValue(1);
4038   }
4039 
4040   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4041   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4042   // node so that legalize doesn't hack it.
4043   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4044     auto GV = G->getGlobal();
4045     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
4046         AArch64II::MO_GOT) {
4047       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
4048       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4049     } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
4050       assert(Subtarget->isTargetWindows() &&
4051              "Windows is the only supported COFF target");
4052       Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
4053     } else {
4054       const GlobalValue *GV = G->getGlobal();
4055       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4056     }
4057   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4058     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4059         Subtarget->isTargetMachO()) {
4060       const char *Sym = S->getSymbol();
4061       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4062       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4063     } else {
4064       const char *Sym = S->getSymbol();
4065       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4066     }
4067   }
4068 
4069   // We don't usually want to end the call-sequence here because we would tidy
4070   // the frame up *after* the call, however in the ABI-changing tail-call case
4071   // we've carefully laid out the parameters so that when sp is reset they'll be
4072   // in the correct location.
4073   if (IsTailCall && !IsSibCall) {
4074     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4075                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4076     InFlag = Chain.getValue(1);
4077   }
4078 
4079   std::vector<SDValue> Ops;
4080   Ops.push_back(Chain);
4081   Ops.push_back(Callee);
4082 
4083   if (IsTailCall) {
4084     // Each tail call may have to adjust the stack by a different amount, so
4085     // this information must travel along with the operation for eventual
4086     // consumption by emitEpilogue.
4087     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4088   }
4089 
4090   // Add argument registers to the end of the list so that they are known live
4091   // into the call.
4092   for (auto &RegToPass : RegsToPass)
4093     Ops.push_back(DAG.getRegister(RegToPass.first,
4094                                   RegToPass.second.getValueType()));
4095 
4096   // Check callee args/returns for SVE registers and set calling convention
4097   // accordingly.
4098   if (CallConv == CallingConv::C) {
4099     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4100       return Out.VT.isScalableVector();
4101     });
4102     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4103       return In.VT.isScalableVector();
4104     });
4105 
4106     if (CalleeInSVE || CalleeOutSVE)
4107       CallConv = CallingConv::AArch64_SVE_VectorCall;
4108   }
4109 
4110   // Add a register mask operand representing the call-preserved registers.
4111   const uint32_t *Mask;
4112   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4113   if (IsThisReturn) {
4114     // For 'this' returns, use the X0-preserving mask if applicable
4115     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4116     if (!Mask) {
4117       IsThisReturn = false;
4118       Mask = TRI->getCallPreservedMask(MF, CallConv);
4119     }
4120   } else
4121     Mask = TRI->getCallPreservedMask(MF, CallConv);
4122 
4123   if (Subtarget->hasCustomCallingConv())
4124     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4125 
4126   if (TRI->isAnyArgRegReserved(MF))
4127     TRI->emitReservedArgRegCallError(MF);
4128 
4129   assert(Mask && "Missing call preserved mask for calling convention");
4130   Ops.push_back(DAG.getRegisterMask(Mask));
4131 
4132   if (InFlag.getNode())
4133     Ops.push_back(InFlag);
4134 
4135   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4136 
4137   // If we're doing a tall call, use a TC_RETURN here rather than an
4138   // actual call instruction.
4139   if (IsTailCall) {
4140     MF.getFrameInfo().setHasTailCall();
4141     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4142     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4143     return Ret;
4144   }
4145 
4146   // Returns a chain and a flag for retval copy to use.
4147   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4148   InFlag = Chain.getValue(1);
4149   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4150 
4151   uint64_t CalleePopBytes =
4152       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4153 
4154   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4155                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4156                              InFlag, DL);
4157   if (!Ins.empty())
4158     InFlag = Chain.getValue(1);
4159 
4160   // Handle result values, copying them out of physregs into vregs that we
4161   // return.
4162   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4163                          InVals, IsThisReturn,
4164                          IsThisReturn ? OutVals[0] : SDValue());
4165 }
4166 
4167 bool AArch64TargetLowering::CanLowerReturn(
4168     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4169     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4170   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4171                           ? RetCC_AArch64_WebKit_JS
4172                           : RetCC_AArch64_AAPCS;
4173   SmallVector<CCValAssign, 16> RVLocs;
4174   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4175   return CCInfo.CheckReturn(Outs, RetCC);
4176 }
4177 
4178 SDValue
4179 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4180                                    bool isVarArg,
4181                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4182                                    const SmallVectorImpl<SDValue> &OutVals,
4183                                    const SDLoc &DL, SelectionDAG &DAG) const {
4184   auto &MF = DAG.getMachineFunction();
4185   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4186 
4187   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4188                           ? RetCC_AArch64_WebKit_JS
4189                           : RetCC_AArch64_AAPCS;
4190   SmallVector<CCValAssign, 16> RVLocs;
4191   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4192                  *DAG.getContext());
4193   CCInfo.AnalyzeReturn(Outs, RetCC);
4194 
4195   // Copy the result values into the output registers.
4196   SDValue Flag;
4197   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4198   SmallSet<unsigned, 4> RegsUsed;
4199   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4200        ++i, ++realRVLocIdx) {
4201     CCValAssign &VA = RVLocs[i];
4202     assert(VA.isRegLoc() && "Can only return in registers!");
4203     SDValue Arg = OutVals[realRVLocIdx];
4204 
4205     switch (VA.getLocInfo()) {
4206     default:
4207       llvm_unreachable("Unknown loc info!");
4208     case CCValAssign::Full:
4209       if (Outs[i].ArgVT == MVT::i1) {
4210         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4211         // value. This is strictly redundant on Darwin (which uses "zeroext
4212         // i1"), but will be optimised out before ISel.
4213         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4214         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4215       }
4216       break;
4217     case CCValAssign::BCvt:
4218       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4219       break;
4220     case CCValAssign::AExt:
4221     case CCValAssign::ZExt:
4222       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4223       break;
4224     case CCValAssign::AExtUpper:
4225       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4226       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4227       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4228                         DAG.getConstant(32, DL, VA.getLocVT()));
4229       break;
4230     }
4231 
4232     if (RegsUsed.count(VA.getLocReg())) {
4233       SDValue &Bits =
4234           std::find_if(RetVals.begin(), RetVals.end(),
4235                        [=](const std::pair<unsigned, SDValue> &Elt) {
4236                          return Elt.first == VA.getLocReg();
4237                        })
4238               ->second;
4239       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4240     } else {
4241       RetVals.emplace_back(VA.getLocReg(), Arg);
4242       RegsUsed.insert(VA.getLocReg());
4243     }
4244   }
4245 
4246   SmallVector<SDValue, 4> RetOps(1, Chain);
4247   for (auto &RetVal : RetVals) {
4248     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4249     Flag = Chain.getValue(1);
4250     RetOps.push_back(
4251         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4252   }
4253 
4254   // Windows AArch64 ABIs require that for returning structs by value we copy
4255   // the sret argument into X0 for the return.
4256   // We saved the argument into a virtual register in the entry block,
4257   // so now we copy the value out and into X0.
4258   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4259     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4260                                      getPointerTy(MF.getDataLayout()));
4261 
4262     unsigned RetValReg = AArch64::X0;
4263     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4264     Flag = Chain.getValue(1);
4265 
4266     RetOps.push_back(
4267       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4268   }
4269 
4270   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4271   const MCPhysReg *I =
4272       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4273   if (I) {
4274     for (; *I; ++I) {
4275       if (AArch64::GPR64RegClass.contains(*I))
4276         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4277       else if (AArch64::FPR64RegClass.contains(*I))
4278         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4279       else
4280         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4281     }
4282   }
4283 
4284   RetOps[0] = Chain; // Update chain.
4285 
4286   // Add the flag if we have it.
4287   if (Flag.getNode())
4288     RetOps.push_back(Flag);
4289 
4290   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4291 }
4292 
4293 //===----------------------------------------------------------------------===//
4294 //  Other Lowering Code
4295 //===----------------------------------------------------------------------===//
4296 
4297 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4298                                              SelectionDAG &DAG,
4299                                              unsigned Flag) const {
4300   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4301                                     N->getOffset(), Flag);
4302 }
4303 
4304 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4305                                              SelectionDAG &DAG,
4306                                              unsigned Flag) const {
4307   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4308 }
4309 
4310 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4311                                              SelectionDAG &DAG,
4312                                              unsigned Flag) const {
4313   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4314                                    N->getOffset(), Flag);
4315 }
4316 
4317 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4318                                              SelectionDAG &DAG,
4319                                              unsigned Flag) const {
4320   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4321 }
4322 
4323 // (loadGOT sym)
4324 template <class NodeTy>
4325 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4326                                       unsigned Flags) const {
4327   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4328   SDLoc DL(N);
4329   EVT Ty = getPointerTy(DAG.getDataLayout());
4330   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4331   // FIXME: Once remat is capable of dealing with instructions with register
4332   // operands, expand this into two nodes instead of using a wrapper node.
4333   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4334 }
4335 
4336 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4337 template <class NodeTy>
4338 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4339                                             unsigned Flags) const {
4340   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4341   SDLoc DL(N);
4342   EVT Ty = getPointerTy(DAG.getDataLayout());
4343   const unsigned char MO_NC = AArch64II::MO_NC;
4344   return DAG.getNode(
4345       AArch64ISD::WrapperLarge, DL, Ty,
4346       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4347       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4348       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4349       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4350 }
4351 
4352 // (addlow (adrp %hi(sym)) %lo(sym))
4353 template <class NodeTy>
4354 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4355                                        unsigned Flags) const {
4356   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4357   SDLoc DL(N);
4358   EVT Ty = getPointerTy(DAG.getDataLayout());
4359   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4360   SDValue Lo = getTargetNode(N, Ty, DAG,
4361                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4362   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4363   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4364 }
4365 
4366 // (adr sym)
4367 template <class NodeTy>
4368 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4369                                            unsigned Flags) const {
4370   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4371   SDLoc DL(N);
4372   EVT Ty = getPointerTy(DAG.getDataLayout());
4373   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4374   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4375 }
4376 
4377 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4378                                                   SelectionDAG &DAG) const {
4379   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4380   const GlobalValue *GV = GN->getGlobal();
4381   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4382 
4383   if (OpFlags != AArch64II::MO_NO_FLAG)
4384     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4385            "unexpected offset in global node");
4386 
4387   // This also catches the large code model case for Darwin, and tiny code
4388   // model with got relocations.
4389   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4390     return getGOT(GN, DAG, OpFlags);
4391   }
4392 
4393   SDValue Result;
4394   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4395     Result = getAddrLarge(GN, DAG, OpFlags);
4396   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4397     Result = getAddrTiny(GN, DAG, OpFlags);
4398   } else {
4399     Result = getAddr(GN, DAG, OpFlags);
4400   }
4401   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4402   SDLoc DL(GN);
4403   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4404     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4405                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4406   return Result;
4407 }
4408 
4409 /// Convert a TLS address reference into the correct sequence of loads
4410 /// and calls to compute the variable's address (for Darwin, currently) and
4411 /// return an SDValue containing the final node.
4412 
4413 /// Darwin only has one TLS scheme which must be capable of dealing with the
4414 /// fully general situation, in the worst case. This means:
4415 ///     + "extern __thread" declaration.
4416 ///     + Defined in a possibly unknown dynamic library.
4417 ///
4418 /// The general system is that each __thread variable has a [3 x i64] descriptor
4419 /// which contains information used by the runtime to calculate the address. The
4420 /// only part of this the compiler needs to know about is the first xword, which
4421 /// contains a function pointer that must be called with the address of the
4422 /// entire descriptor in "x0".
4423 ///
4424 /// Since this descriptor may be in a different unit, in general even the
4425 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4426 /// is:
4427 ///     adrp x0, _var@TLVPPAGE
4428 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4429 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4430 ///                                      ; the function pointer
4431 ///     blr x1                           ; Uses descriptor address in x0
4432 ///     ; Address of _var is now in x0.
4433 ///
4434 /// If the address of _var's descriptor *is* known to the linker, then it can
4435 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4436 /// a slight efficiency gain.
4437 SDValue
4438 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4439                                                    SelectionDAG &DAG) const {
4440   assert(Subtarget->isTargetDarwin() &&
4441          "This function expects a Darwin target");
4442 
4443   SDLoc DL(Op);
4444   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4445   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4446   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4447 
4448   SDValue TLVPAddr =
4449       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4450   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4451 
4452   // The first entry in the descriptor is a function pointer that we must call
4453   // to obtain the address of the variable.
4454   SDValue Chain = DAG.getEntryNode();
4455   SDValue FuncTLVGet = DAG.getLoad(
4456       PtrMemVT, DL, Chain, DescAddr,
4457       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4458       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4459       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4460   Chain = FuncTLVGet.getValue(1);
4461 
4462   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4463   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4464 
4465   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4466   MFI.setAdjustsStack(true);
4467 
4468   // TLS calls preserve all registers except those that absolutely must be
4469   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4470   // silly).
4471   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4472   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4473   if (Subtarget->hasCustomCallingConv())
4474     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4475 
4476   // Finally, we can make the call. This is just a degenerate version of a
4477   // normal AArch64 call node: x0 takes the address of the descriptor, and
4478   // returns the address of the variable in this thread.
4479   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4480   Chain =
4481       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4482                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4483                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4484   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4485 }
4486 
4487 /// When accessing thread-local variables under either the general-dynamic or
4488 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4489 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4490 /// is a function pointer to carry out the resolution.
4491 ///
4492 /// The sequence is:
4493 ///    adrp  x0, :tlsdesc:var
4494 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4495 ///    add   x0, x0, #:tlsdesc_lo12:var
4496 ///    .tlsdesccall var
4497 ///    blr   x1
4498 ///    (TPIDR_EL0 offset now in x0)
4499 ///
4500 ///  The above sequence must be produced unscheduled, to enable the linker to
4501 ///  optimize/relax this sequence.
4502 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4503 ///  above sequence, and expanded really late in the compilation flow, to ensure
4504 ///  the sequence is produced as per above.
4505 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4506                                                       const SDLoc &DL,
4507                                                       SelectionDAG &DAG) const {
4508   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4509 
4510   SDValue Chain = DAG.getEntryNode();
4511   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4512 
4513   Chain =
4514       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4515   SDValue Glue = Chain.getValue(1);
4516 
4517   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4518 }
4519 
4520 SDValue
4521 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4522                                                 SelectionDAG &DAG) const {
4523   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4524   if (getTargetMachine().getCodeModel() == CodeModel::Large)
4525     report_fatal_error("ELF TLS only supported in small memory model");
4526   // Different choices can be made for the maximum size of the TLS area for a
4527   // module. For the small address model, the default TLS size is 16MiB and the
4528   // maximum TLS size is 4GiB.
4529   // FIXME: add -mtls-size command line option and make it control the 16MiB
4530   // vs. 4GiB code sequence generation.
4531   // FIXME: add tiny codemodel support. We currently generate the same code as
4532   // small, which may be larger than needed.
4533   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4534 
4535   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4536 
4537   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4538     if (Model == TLSModel::LocalDynamic)
4539       Model = TLSModel::GeneralDynamic;
4540   }
4541 
4542   SDValue TPOff;
4543   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4544   SDLoc DL(Op);
4545   const GlobalValue *GV = GA->getGlobal();
4546 
4547   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4548 
4549   if (Model == TLSModel::LocalExec) {
4550     SDValue HiVar = DAG.getTargetGlobalAddress(
4551         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4552     SDValue LoVar = DAG.getTargetGlobalAddress(
4553         GV, DL, PtrVT, 0,
4554         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4555 
4556     SDValue TPWithOff_lo =
4557         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4558                                    HiVar,
4559                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4560                 0);
4561     SDValue TPWithOff =
4562         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4563                                    LoVar,
4564                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4565                 0);
4566     return TPWithOff;
4567   } else if (Model == TLSModel::InitialExec) {
4568     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4569     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4570   } else if (Model == TLSModel::LocalDynamic) {
4571     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4572     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4573     // the beginning of the module's TLS region, followed by a DTPREL offset
4574     // calculation.
4575 
4576     // These accesses will need deduplicating if there's more than one.
4577     AArch64FunctionInfo *MFI =
4578         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4579     MFI->incNumLocalDynamicTLSAccesses();
4580 
4581     // The call needs a relocation too for linker relaxation. It doesn't make
4582     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4583     // the address.
4584     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4585                                                   AArch64II::MO_TLS);
4586 
4587     // Now we can calculate the offset from TPIDR_EL0 to this module's
4588     // thread-local area.
4589     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4590 
4591     // Now use :dtprel_whatever: operations to calculate this variable's offset
4592     // in its thread-storage area.
4593     SDValue HiVar = DAG.getTargetGlobalAddress(
4594         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4595     SDValue LoVar = DAG.getTargetGlobalAddress(
4596         GV, DL, MVT::i64, 0,
4597         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4598 
4599     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4600                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4601                     0);
4602     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4603                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4604                     0);
4605   } else if (Model == TLSModel::GeneralDynamic) {
4606     // The call needs a relocation too for linker relaxation. It doesn't make
4607     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4608     // the address.
4609     SDValue SymAddr =
4610         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4611 
4612     // Finally we can make a call to calculate the offset from tpidr_el0.
4613     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4614   } else
4615     llvm_unreachable("Unsupported ELF TLS access model");
4616 
4617   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4618 }
4619 
4620 SDValue
4621 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4622                                                     SelectionDAG &DAG) const {
4623   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4624 
4625   SDValue Chain = DAG.getEntryNode();
4626   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4627   SDLoc DL(Op);
4628 
4629   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4630 
4631   // Load the ThreadLocalStoragePointer from the TEB
4632   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4633   SDValue TLSArray =
4634       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4635   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4636   Chain = TLSArray.getValue(1);
4637 
4638   // Load the TLS index from the C runtime;
4639   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4640   // This also does the same as LOADgot, but using a generic i32 load,
4641   // while LOADgot only loads i64.
4642   SDValue TLSIndexHi =
4643       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4644   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4645       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4646   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4647   SDValue TLSIndex =
4648       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4649   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4650   Chain = TLSIndex.getValue(1);
4651 
4652   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4653   // offset into the TLSArray.
4654   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4655   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4656                              DAG.getConstant(3, DL, PtrVT));
4657   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4658                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4659                             MachinePointerInfo());
4660   Chain = TLS.getValue(1);
4661 
4662   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4663   const GlobalValue *GV = GA->getGlobal();
4664   SDValue TGAHi = DAG.getTargetGlobalAddress(
4665       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4666   SDValue TGALo = DAG.getTargetGlobalAddress(
4667       GV, DL, PtrVT, 0,
4668       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4669 
4670   // Add the offset from the start of the .tls section (section base).
4671   SDValue Addr =
4672       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4673                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4674               0);
4675   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4676   return Addr;
4677 }
4678 
4679 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4680                                                      SelectionDAG &DAG) const {
4681   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4682   if (DAG.getTarget().useEmulatedTLS())
4683     return LowerToTLSEmulatedModel(GA, DAG);
4684 
4685   if (Subtarget->isTargetDarwin())
4686     return LowerDarwinGlobalTLSAddress(Op, DAG);
4687   if (Subtarget->isTargetELF())
4688     return LowerELFGlobalTLSAddress(Op, DAG);
4689   if (Subtarget->isTargetWindows())
4690     return LowerWindowsGlobalTLSAddress(Op, DAG);
4691 
4692   llvm_unreachable("Unexpected platform trying to use TLS");
4693 }
4694 
4695 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4696   SDValue Chain = Op.getOperand(0);
4697   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4698   SDValue LHS = Op.getOperand(2);
4699   SDValue RHS = Op.getOperand(3);
4700   SDValue Dest = Op.getOperand(4);
4701   SDLoc dl(Op);
4702 
4703   MachineFunction &MF = DAG.getMachineFunction();
4704   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4705   // will not be produced, as they are conditional branch instructions that do
4706   // not set flags.
4707   bool ProduceNonFlagSettingCondBr =
4708       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4709 
4710   // Handle f128 first, since lowering it will result in comparing the return
4711   // value of a libcall against zero, which is just what the rest of LowerBR_CC
4712   // is expecting to deal with.
4713   if (LHS.getValueType() == MVT::f128) {
4714     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4715 
4716     // If softenSetCCOperands returned a scalar, we need to compare the result
4717     // against zero to select between true and false values.
4718     if (!RHS.getNode()) {
4719       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4720       CC = ISD::SETNE;
4721     }
4722   }
4723 
4724   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4725   // instruction.
4726   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4727       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4728     // Only lower legal XALUO ops.
4729     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4730       return SDValue();
4731 
4732     // The actual operation with overflow check.
4733     AArch64CC::CondCode OFCC;
4734     SDValue Value, Overflow;
4735     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4736 
4737     if (CC == ISD::SETNE)
4738       OFCC = getInvertedCondCode(OFCC);
4739     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4740 
4741     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4742                        Overflow);
4743   }
4744 
4745   if (LHS.getValueType().isInteger()) {
4746     assert((LHS.getValueType() == RHS.getValueType()) &&
4747            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4748 
4749     // If the RHS of the comparison is zero, we can potentially fold this
4750     // to a specialized branch.
4751     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4752     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4753       if (CC == ISD::SETEQ) {
4754         // See if we can use a TBZ to fold in an AND as well.
4755         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4756         // out of bounds, a late MI-layer pass rewrites branches.
4757         // 403.gcc is an example that hits this case.
4758         if (LHS.getOpcode() == ISD::AND &&
4759             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4760             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4761           SDValue Test = LHS.getOperand(0);
4762           uint64_t Mask = LHS.getConstantOperandVal(1);
4763           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4764                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4765                              Dest);
4766         }
4767 
4768         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4769       } else if (CC == ISD::SETNE) {
4770         // See if we can use a TBZ to fold in an AND as well.
4771         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4772         // out of bounds, a late MI-layer pass rewrites branches.
4773         // 403.gcc is an example that hits this case.
4774         if (LHS.getOpcode() == ISD::AND &&
4775             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4776             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4777           SDValue Test = LHS.getOperand(0);
4778           uint64_t Mask = LHS.getConstantOperandVal(1);
4779           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4780                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4781                              Dest);
4782         }
4783 
4784         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4785       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4786         // Don't combine AND since emitComparison converts the AND to an ANDS
4787         // (a.k.a. TST) and the test in the test bit and branch instruction
4788         // becomes redundant.  This would also increase register pressure.
4789         uint64_t Mask = LHS.getValueSizeInBits() - 1;
4790         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4791                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
4792       }
4793     }
4794     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4795         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4796       // Don't combine AND since emitComparison converts the AND to an ANDS
4797       // (a.k.a. TST) and the test in the test bit and branch instruction
4798       // becomes redundant.  This would also increase register pressure.
4799       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4800       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4801                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4802     }
4803 
4804     SDValue CCVal;
4805     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4806     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4807                        Cmp);
4808   }
4809 
4810   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4811          LHS.getValueType() == MVT::f64);
4812 
4813   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4814   // clean.  Some of them require two branches to implement.
4815   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4816   AArch64CC::CondCode CC1, CC2;
4817   changeFPCCToAArch64CC(CC, CC1, CC2);
4818   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4819   SDValue BR1 =
4820       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4821   if (CC2 != AArch64CC::AL) {
4822     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4823     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4824                        Cmp);
4825   }
4826 
4827   return BR1;
4828 }
4829 
4830 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4831                                               SelectionDAG &DAG) const {
4832   EVT VT = Op.getValueType();
4833   SDLoc DL(Op);
4834 
4835   SDValue In1 = Op.getOperand(0);
4836   SDValue In2 = Op.getOperand(1);
4837   EVT SrcVT = In2.getValueType();
4838 
4839   if (SrcVT.bitsLT(VT))
4840     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4841   else if (SrcVT.bitsGT(VT))
4842     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4843 
4844   EVT VecVT;
4845   uint64_t EltMask;
4846   SDValue VecVal1, VecVal2;
4847 
4848   auto setVecVal = [&] (int Idx) {
4849     if (!VT.isVector()) {
4850       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4851                                           DAG.getUNDEF(VecVT), In1);
4852       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4853                                           DAG.getUNDEF(VecVT), In2);
4854     } else {
4855       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4856       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4857     }
4858   };
4859 
4860   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4861     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4862     EltMask = 0x80000000ULL;
4863     setVecVal(AArch64::ssub);
4864   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4865     VecVT = MVT::v2i64;
4866 
4867     // We want to materialize a mask with the high bit set, but the AdvSIMD
4868     // immediate moves cannot materialize that in a single instruction for
4869     // 64-bit elements. Instead, materialize zero and then negate it.
4870     EltMask = 0;
4871 
4872     setVecVal(AArch64::dsub);
4873   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4874     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4875     EltMask = 0x8000ULL;
4876     setVecVal(AArch64::hsub);
4877   } else {
4878     llvm_unreachable("Invalid type for copysign!");
4879   }
4880 
4881   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4882 
4883   // If we couldn't materialize the mask above, then the mask vector will be
4884   // the zero vector, and we need to negate it here.
4885   if (VT == MVT::f64 || VT == MVT::v2f64) {
4886     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4887     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4888     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4889   }
4890 
4891   SDValue Sel =
4892       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4893 
4894   if (VT == MVT::f16)
4895     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4896   if (VT == MVT::f32)
4897     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4898   else if (VT == MVT::f64)
4899     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4900   else
4901     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4902 }
4903 
4904 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4905   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4906           Attribute::NoImplicitFloat))
4907     return SDValue();
4908 
4909   if (!Subtarget->hasNEON())
4910     return SDValue();
4911 
4912   // While there is no integer popcount instruction, it can
4913   // be more efficiently lowered to the following sequence that uses
4914   // AdvSIMD registers/instructions as long as the copies to/from
4915   // the AdvSIMD registers are cheap.
4916   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4917   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4918   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4919   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4920   SDValue Val = Op.getOperand(0);
4921   SDLoc DL(Op);
4922   EVT VT = Op.getValueType();
4923 
4924   if (VT == MVT::i32 || VT == MVT::i64) {
4925     if (VT == MVT::i32)
4926       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4927     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4928 
4929     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4930     SDValue UaddLV = DAG.getNode(
4931         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4932         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4933 
4934     if (VT == MVT::i64)
4935       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4936     return UaddLV;
4937   }
4938 
4939   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4940           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4941          "Unexpected type for custom ctpop lowering");
4942 
4943   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4944   Val = DAG.getBitcast(VT8Bit, Val);
4945   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4946 
4947   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4948   unsigned EltSize = 8;
4949   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4950   while (EltSize != VT.getScalarSizeInBits()) {
4951     EltSize *= 2;
4952     NumElts /= 2;
4953     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4954     Val = DAG.getNode(
4955         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4956         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4957   }
4958 
4959   return Val;
4960 }
4961 
4962 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4963 
4964   if (Op.getValueType().isVector())
4965     return LowerVSETCC(Op, DAG);
4966 
4967   SDValue LHS = Op.getOperand(0);
4968   SDValue RHS = Op.getOperand(1);
4969   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4970   SDLoc dl(Op);
4971 
4972   // We chose ZeroOrOneBooleanContents, so use zero and one.
4973   EVT VT = Op.getValueType();
4974   SDValue TVal = DAG.getConstant(1, dl, VT);
4975   SDValue FVal = DAG.getConstant(0, dl, VT);
4976 
4977   // Handle f128 first, since one possible outcome is a normal integer
4978   // comparison which gets picked up by the next if statement.
4979   if (LHS.getValueType() == MVT::f128) {
4980     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4981 
4982     // If softenSetCCOperands returned a scalar, use it.
4983     if (!RHS.getNode()) {
4984       assert(LHS.getValueType() == Op.getValueType() &&
4985              "Unexpected setcc expansion!");
4986       return LHS;
4987     }
4988   }
4989 
4990   if (LHS.getValueType().isInteger()) {
4991     SDValue CCVal;
4992     SDValue Cmp =
4993         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4994 
4995     // Note that we inverted the condition above, so we reverse the order of
4996     // the true and false operands here.  This will allow the setcc to be
4997     // matched to a single CSINC instruction.
4998     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4999   }
5000 
5001   // Now we know we're dealing with FP values.
5002   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5003          LHS.getValueType() == MVT::f64);
5004 
5005   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5006   // and do the comparison.
5007   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5008 
5009   AArch64CC::CondCode CC1, CC2;
5010   changeFPCCToAArch64CC(CC, CC1, CC2);
5011   if (CC2 == AArch64CC::AL) {
5012     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
5013     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5014 
5015     // Note that we inverted the condition above, so we reverse the order of
5016     // the true and false operands here.  This will allow the setcc to be
5017     // matched to a single CSINC instruction.
5018     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5019   } else {
5020     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5021     // totally clean.  Some of them require two CSELs to implement.  As is in
5022     // this case, we emit the first CSEL and then emit a second using the output
5023     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5024 
5025     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5026     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5027     SDValue CS1 =
5028         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5029 
5030     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5031     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5032   }
5033 }
5034 
5035 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5036                                               SDValue RHS, SDValue TVal,
5037                                               SDValue FVal, const SDLoc &dl,
5038                                               SelectionDAG &DAG) const {
5039   // Handle f128 first, because it will result in a comparison of some RTLIB
5040   // call result against zero.
5041   if (LHS.getValueType() == MVT::f128) {
5042     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5043 
5044     // If softenSetCCOperands returned a scalar, we need to compare the result
5045     // against zero to select between true and false values.
5046     if (!RHS.getNode()) {
5047       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5048       CC = ISD::SETNE;
5049     }
5050   }
5051 
5052   // Also handle f16, for which we need to do a f32 comparison.
5053   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5054     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5055     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5056   }
5057 
5058   // Next, handle integers.
5059   if (LHS.getValueType().isInteger()) {
5060     assert((LHS.getValueType() == RHS.getValueType()) &&
5061            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5062 
5063     unsigned Opcode = AArch64ISD::CSEL;
5064 
5065     // If both the TVal and the FVal are constants, see if we can swap them in
5066     // order to for a CSINV or CSINC out of them.
5067     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5068     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5069 
5070     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5071       std::swap(TVal, FVal);
5072       std::swap(CTVal, CFVal);
5073       CC = ISD::getSetCCInverse(CC, true);
5074     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5075       std::swap(TVal, FVal);
5076       std::swap(CTVal, CFVal);
5077       CC = ISD::getSetCCInverse(CC, true);
5078     } else if (TVal.getOpcode() == ISD::XOR) {
5079       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5080       // with a CSINV rather than a CSEL.
5081       if (isAllOnesConstant(TVal.getOperand(1))) {
5082         std::swap(TVal, FVal);
5083         std::swap(CTVal, CFVal);
5084         CC = ISD::getSetCCInverse(CC, true);
5085       }
5086     } else if (TVal.getOpcode() == ISD::SUB) {
5087       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5088       // that we can match with a CSNEG rather than a CSEL.
5089       if (isNullConstant(TVal.getOperand(0))) {
5090         std::swap(TVal, FVal);
5091         std::swap(CTVal, CFVal);
5092         CC = ISD::getSetCCInverse(CC, true);
5093       }
5094     } else if (CTVal && CFVal) {
5095       const int64_t TrueVal = CTVal->getSExtValue();
5096       const int64_t FalseVal = CFVal->getSExtValue();
5097       bool Swap = false;
5098 
5099       // If both TVal and FVal are constants, see if FVal is the
5100       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5101       // instead of a CSEL in that case.
5102       if (TrueVal == ~FalseVal) {
5103         Opcode = AArch64ISD::CSINV;
5104       } else if (TrueVal == -FalseVal) {
5105         Opcode = AArch64ISD::CSNEG;
5106       } else if (TVal.getValueType() == MVT::i32) {
5107         // If our operands are only 32-bit wide, make sure we use 32-bit
5108         // arithmetic for the check whether we can use CSINC. This ensures that
5109         // the addition in the check will wrap around properly in case there is
5110         // an overflow (which would not be the case if we do the check with
5111         // 64-bit arithmetic).
5112         const uint32_t TrueVal32 = CTVal->getZExtValue();
5113         const uint32_t FalseVal32 = CFVal->getZExtValue();
5114 
5115         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5116           Opcode = AArch64ISD::CSINC;
5117 
5118           if (TrueVal32 > FalseVal32) {
5119             Swap = true;
5120           }
5121         }
5122         // 64-bit check whether we can use CSINC.
5123       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5124         Opcode = AArch64ISD::CSINC;
5125 
5126         if (TrueVal > FalseVal) {
5127           Swap = true;
5128         }
5129       }
5130 
5131       // Swap TVal and FVal if necessary.
5132       if (Swap) {
5133         std::swap(TVal, FVal);
5134         std::swap(CTVal, CFVal);
5135         CC = ISD::getSetCCInverse(CC, true);
5136       }
5137 
5138       if (Opcode != AArch64ISD::CSEL) {
5139         // Drop FVal since we can get its value by simply inverting/negating
5140         // TVal.
5141         FVal = TVal;
5142       }
5143     }
5144 
5145     // Avoid materializing a constant when possible by reusing a known value in
5146     // a register.  However, don't perform this optimization if the known value
5147     // is one, zero or negative one in the case of a CSEL.  We can always
5148     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5149     // FVal, respectively.
5150     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5151     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5152         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5153       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5154       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5155       // "a != C ? x : a" to avoid materializing C.
5156       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5157         TVal = LHS;
5158       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5159         FVal = LHS;
5160     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5161       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5162       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5163       // avoid materializing C.
5164       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5165       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5166         Opcode = AArch64ISD::CSINV;
5167         TVal = LHS;
5168         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5169       }
5170     }
5171 
5172     SDValue CCVal;
5173     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5174     EVT VT = TVal.getValueType();
5175     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5176   }
5177 
5178   // Now we know we're dealing with FP values.
5179   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5180          LHS.getValueType() == MVT::f64);
5181   assert(LHS.getValueType() == RHS.getValueType());
5182   EVT VT = TVal.getValueType();
5183   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5184 
5185   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5186   // clean.  Some of them require two CSELs to implement.
5187   AArch64CC::CondCode CC1, CC2;
5188   changeFPCCToAArch64CC(CC, CC1, CC2);
5189 
5190   if (DAG.getTarget().Options.UnsafeFPMath) {
5191     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5192     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5193     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5194     if (RHSVal && RHSVal->isZero()) {
5195       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5196       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5197 
5198       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5199           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5200         TVal = LHS;
5201       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5202                CFVal && CFVal->isZero() &&
5203                FVal.getValueType() == LHS.getValueType())
5204         FVal = LHS;
5205     }
5206   }
5207 
5208   // Emit first, and possibly only, CSEL.
5209   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5210   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5211 
5212   // If we need a second CSEL, emit it, using the output of the first as the
5213   // RHS.  We're effectively OR'ing the two CC's together.
5214   if (CC2 != AArch64CC::AL) {
5215     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5216     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5217   }
5218 
5219   // Otherwise, return the output of the first CSEL.
5220   return CS1;
5221 }
5222 
5223 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5224                                               SelectionDAG &DAG) const {
5225   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5226   SDValue LHS = Op.getOperand(0);
5227   SDValue RHS = Op.getOperand(1);
5228   SDValue TVal = Op.getOperand(2);
5229   SDValue FVal = Op.getOperand(3);
5230   SDLoc DL(Op);
5231   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5232 }
5233 
5234 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5235                                            SelectionDAG &DAG) const {
5236   SDValue CCVal = Op->getOperand(0);
5237   SDValue TVal = Op->getOperand(1);
5238   SDValue FVal = Op->getOperand(2);
5239   SDLoc DL(Op);
5240 
5241   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5242   // instruction.
5243   if (isOverflowIntrOpRes(CCVal)) {
5244     // Only lower legal XALUO ops.
5245     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5246       return SDValue();
5247 
5248     AArch64CC::CondCode OFCC;
5249     SDValue Value, Overflow;
5250     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5251     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5252 
5253     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5254                        CCVal, Overflow);
5255   }
5256 
5257   // Lower it the same way as we would lower a SELECT_CC node.
5258   ISD::CondCode CC;
5259   SDValue LHS, RHS;
5260   if (CCVal.getOpcode() == ISD::SETCC) {
5261     LHS = CCVal.getOperand(0);
5262     RHS = CCVal.getOperand(1);
5263     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5264   } else {
5265     LHS = CCVal;
5266     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5267     CC = ISD::SETNE;
5268   }
5269   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5270 }
5271 
5272 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5273                                               SelectionDAG &DAG) const {
5274   // Jump table entries as PC relative offsets. No additional tweaking
5275   // is necessary here. Just get the address of the jump table.
5276   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5277 
5278   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5279       !Subtarget->isTargetMachO()) {
5280     return getAddrLarge(JT, DAG);
5281   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5282     return getAddrTiny(JT, DAG);
5283   }
5284   return getAddr(JT, DAG);
5285 }
5286 
5287 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5288                                           SelectionDAG &DAG) const {
5289   // Jump table entries as PC relative offsets. No additional tweaking
5290   // is necessary here. Just get the address of the jump table.
5291   SDLoc DL(Op);
5292   SDValue JT = Op.getOperand(1);
5293   SDValue Entry = Op.getOperand(2);
5294   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5295 
5296   SDNode *Dest =
5297       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5298                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5299   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5300                      SDValue(Dest, 0));
5301 }
5302 
5303 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5304                                                  SelectionDAG &DAG) const {
5305   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5306 
5307   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5308     // Use the GOT for the large code model on iOS.
5309     if (Subtarget->isTargetMachO()) {
5310       return getGOT(CP, DAG);
5311     }
5312     return getAddrLarge(CP, DAG);
5313   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5314     return getAddrTiny(CP, DAG);
5315   } else {
5316     return getAddr(CP, DAG);
5317   }
5318 }
5319 
5320 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5321                                                SelectionDAG &DAG) const {
5322   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5323   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5324       !Subtarget->isTargetMachO()) {
5325     return getAddrLarge(BA, DAG);
5326   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5327     return getAddrTiny(BA, DAG);
5328   }
5329   return getAddr(BA, DAG);
5330 }
5331 
5332 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5333                                                  SelectionDAG &DAG) const {
5334   AArch64FunctionInfo *FuncInfo =
5335       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5336 
5337   SDLoc DL(Op);
5338   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5339                                  getPointerTy(DAG.getDataLayout()));
5340   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5341   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5342   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5343                       MachinePointerInfo(SV));
5344 }
5345 
5346 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5347                                                   SelectionDAG &DAG) const {
5348   AArch64FunctionInfo *FuncInfo =
5349       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5350 
5351   SDLoc DL(Op);
5352   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5353                                      ? FuncInfo->getVarArgsGPRIndex()
5354                                      : FuncInfo->getVarArgsStackIndex(),
5355                                  getPointerTy(DAG.getDataLayout()));
5356   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5357   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5358                       MachinePointerInfo(SV));
5359 }
5360 
5361 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5362                                                 SelectionDAG &DAG) const {
5363   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5364   // Standard, section B.3.
5365   MachineFunction &MF = DAG.getMachineFunction();
5366   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5367   auto PtrVT = getPointerTy(DAG.getDataLayout());
5368   SDLoc DL(Op);
5369 
5370   SDValue Chain = Op.getOperand(0);
5371   SDValue VAList = Op.getOperand(1);
5372   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5373   SmallVector<SDValue, 4> MemOps;
5374 
5375   // void *__stack at offset 0
5376   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5377   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5378                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5379 
5380   // void *__gr_top at offset 8
5381   int GPRSize = FuncInfo->getVarArgsGPRSize();
5382   if (GPRSize > 0) {
5383     SDValue GRTop, GRTopAddr;
5384 
5385     GRTopAddr =
5386         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5387 
5388     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5389     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5390                         DAG.getConstant(GPRSize, DL, PtrVT));
5391 
5392     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5393                                   MachinePointerInfo(SV, 8),
5394                                   /* Alignment = */ 8));
5395   }
5396 
5397   // void *__vr_top at offset 16
5398   int FPRSize = FuncInfo->getVarArgsFPRSize();
5399   if (FPRSize > 0) {
5400     SDValue VRTop, VRTopAddr;
5401     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5402                             DAG.getConstant(16, DL, PtrVT));
5403 
5404     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5405     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5406                         DAG.getConstant(FPRSize, DL, PtrVT));
5407 
5408     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5409                                   MachinePointerInfo(SV, 16),
5410                                   /* Alignment = */ 8));
5411   }
5412 
5413   // int __gr_offs at offset 24
5414   SDValue GROffsAddr =
5415       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5416   MemOps.push_back(DAG.getStore(
5417       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5418       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5419 
5420   // int __vr_offs at offset 28
5421   SDValue VROffsAddr =
5422       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5423   MemOps.push_back(DAG.getStore(
5424       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5425       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5426 
5427   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5428 }
5429 
5430 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5431                                             SelectionDAG &DAG) const {
5432   MachineFunction &MF = DAG.getMachineFunction();
5433 
5434   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5435     return LowerWin64_VASTART(Op, DAG);
5436   else if (Subtarget->isTargetDarwin())
5437     return LowerDarwin_VASTART(Op, DAG);
5438   else
5439     return LowerAAPCS_VASTART(Op, DAG);
5440 }
5441 
5442 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5443                                            SelectionDAG &DAG) const {
5444   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5445   // pointer.
5446   SDLoc DL(Op);
5447   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5448   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5449                          Subtarget->isTargetWindows()) ? PtrSize : 32;
5450   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5451   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5452 
5453   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5454                        DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize,
5455                        false, false, false, MachinePointerInfo(DestSV),
5456                        MachinePointerInfo(SrcSV));
5457 }
5458 
5459 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5460   assert(Subtarget->isTargetDarwin() &&
5461          "automatic va_arg instruction only works on Darwin");
5462 
5463   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5464   EVT VT = Op.getValueType();
5465   SDLoc DL(Op);
5466   SDValue Chain = Op.getOperand(0);
5467   SDValue Addr = Op.getOperand(1);
5468   unsigned Align = Op.getConstantOperandVal(3);
5469   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5470   auto PtrVT = getPointerTy(DAG.getDataLayout());
5471   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5472   SDValue VAList =
5473       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5474   Chain = VAList.getValue(1);
5475   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5476 
5477   if (Align > MinSlotSize) {
5478     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5479     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5480                          DAG.getConstant(Align - 1, DL, PtrVT));
5481     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5482                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5483   }
5484 
5485   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5486   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5487 
5488   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5489   // up to 64 bits.  At the very least, we have to increase the striding of the
5490   // vaargs list to match this, and for FP values we need to introduce
5491   // FP_ROUND nodes as well.
5492   if (VT.isInteger() && !VT.isVector())
5493     ArgSize = std::max(ArgSize, MinSlotSize);
5494   bool NeedFPTrunc = false;
5495   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5496     ArgSize = 8;
5497     NeedFPTrunc = true;
5498   }
5499 
5500   // Increment the pointer, VAList, to the next vaarg
5501   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5502                                DAG.getConstant(ArgSize, DL, PtrVT));
5503   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5504 
5505   // Store the incremented VAList to the legalized pointer
5506   SDValue APStore =
5507       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5508 
5509   // Load the actual argument out of the pointer VAList
5510   if (NeedFPTrunc) {
5511     // Load the value as an f64.
5512     SDValue WideFP =
5513         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5514     // Round the value down to an f32.
5515     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5516                                    DAG.getIntPtrConstant(1, DL));
5517     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5518     // Merge the rounded value with the chain output of the load.
5519     return DAG.getMergeValues(Ops, DL);
5520   }
5521 
5522   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5523 }
5524 
5525 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5526                                               SelectionDAG &DAG) const {
5527   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5528   MFI.setFrameAddressIsTaken(true);
5529 
5530   EVT VT = Op.getValueType();
5531   SDLoc DL(Op);
5532   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5533   SDValue FrameAddr =
5534       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5535   while (Depth--)
5536     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5537                             MachinePointerInfo());
5538 
5539   if (Subtarget->isTargetILP32())
5540     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5541                             DAG.getValueType(VT));
5542 
5543   return FrameAddr;
5544 }
5545 
5546 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5547                                               SelectionDAG &DAG) const {
5548   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5549 
5550   EVT VT = getPointerTy(DAG.getDataLayout());
5551   SDLoc DL(Op);
5552   int FI = MFI.CreateFixedObject(4, 0, false);
5553   return DAG.getFrameIndex(FI, VT);
5554 }
5555 
5556 #define GET_REGISTER_MATCHER
5557 #include "AArch64GenAsmMatcher.inc"
5558 
5559 // FIXME? Maybe this could be a TableGen attribute on some registers and
5560 // this table could be generated automatically from RegInfo.
5561 Register AArch64TargetLowering::
5562 getRegisterByName(const char* RegName, EVT VT, const MachineFunction &MF) const {
5563   Register Reg = MatchRegisterName(RegName);
5564   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5565     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5566     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5567     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5568       Reg = 0;
5569   }
5570   if (Reg)
5571     return Reg;
5572   report_fatal_error(Twine("Invalid register name \""
5573                               + StringRef(RegName)  + "\"."));
5574 }
5575 
5576 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5577                                                      SelectionDAG &DAG) const {
5578   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5579 
5580   EVT VT = Op.getValueType();
5581   SDLoc DL(Op);
5582 
5583   SDValue FrameAddr =
5584       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5585   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5586 
5587   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5588 }
5589 
5590 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5591                                                SelectionDAG &DAG) const {
5592   MachineFunction &MF = DAG.getMachineFunction();
5593   MachineFrameInfo &MFI = MF.getFrameInfo();
5594   MFI.setReturnAddressIsTaken(true);
5595 
5596   EVT VT = Op.getValueType();
5597   SDLoc DL(Op);
5598   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5599   if (Depth) {
5600     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5601     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5602     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5603                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5604                        MachinePointerInfo());
5605   }
5606 
5607   // Return LR, which contains the return address. Mark it an implicit live-in.
5608   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5609   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5610 }
5611 
5612 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5613 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5614 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5615                                                     SelectionDAG &DAG) const {
5616   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5617   EVT VT = Op.getValueType();
5618   unsigned VTBits = VT.getSizeInBits();
5619   SDLoc dl(Op);
5620   SDValue ShOpLo = Op.getOperand(0);
5621   SDValue ShOpHi = Op.getOperand(1);
5622   SDValue ShAmt = Op.getOperand(2);
5623   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5624 
5625   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5626 
5627   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5628                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5629   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5630 
5631   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5632   // is "undef". We wanted 0, so CSEL it directly.
5633   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5634                                ISD::SETEQ, dl, DAG);
5635   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5636   HiBitsForLo =
5637       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5638                   HiBitsForLo, CCVal, Cmp);
5639 
5640   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5641                                    DAG.getConstant(VTBits, dl, MVT::i64));
5642 
5643   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5644   SDValue LoForNormalShift =
5645       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5646 
5647   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5648                        dl, DAG);
5649   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5650   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5651   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5652                            LoForNormalShift, CCVal, Cmp);
5653 
5654   // AArch64 shifts larger than the register width are wrapped rather than
5655   // clamped, so we can't just emit "hi >> x".
5656   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5657   SDValue HiForBigShift =
5658       Opc == ISD::SRA
5659           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5660                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5661           : DAG.getConstant(0, dl, VT);
5662   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5663                            HiForNormalShift, CCVal, Cmp);
5664 
5665   SDValue Ops[2] = { Lo, Hi };
5666   return DAG.getMergeValues(Ops, dl);
5667 }
5668 
5669 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5670 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5671 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5672                                                    SelectionDAG &DAG) const {
5673   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5674   EVT VT = Op.getValueType();
5675   unsigned VTBits = VT.getSizeInBits();
5676   SDLoc dl(Op);
5677   SDValue ShOpLo = Op.getOperand(0);
5678   SDValue ShOpHi = Op.getOperand(1);
5679   SDValue ShAmt = Op.getOperand(2);
5680 
5681   assert(Op.getOpcode() == ISD::SHL_PARTS);
5682   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5683                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5684   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5685 
5686   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5687   // is "undef". We wanted 0, so CSEL it directly.
5688   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5689                                ISD::SETEQ, dl, DAG);
5690   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5691   LoBitsForHi =
5692       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5693                   LoBitsForHi, CCVal, Cmp);
5694 
5695   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5696                                    DAG.getConstant(VTBits, dl, MVT::i64));
5697   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5698   SDValue HiForNormalShift =
5699       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5700 
5701   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5702 
5703   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5704                        dl, DAG);
5705   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5706   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5707                            HiForNormalShift, CCVal, Cmp);
5708 
5709   // AArch64 shifts of larger than register sizes are wrapped rather than
5710   // clamped, so we can't just emit "lo << a" if a is too big.
5711   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5712   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5713   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5714                            LoForNormalShift, CCVal, Cmp);
5715 
5716   SDValue Ops[2] = { Lo, Hi };
5717   return DAG.getMergeValues(Ops, dl);
5718 }
5719 
5720 bool AArch64TargetLowering::isOffsetFoldingLegal(
5721     const GlobalAddressSDNode *GA) const {
5722   // Offsets are folded in the DAG combine rather than here so that we can
5723   // intelligently choose an offset based on the uses.
5724   return false;
5725 }
5726 
5727 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5728                                          bool OptForSize) const {
5729   bool IsLegal = false;
5730   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5731   // 16-bit case when target has full fp16 support.
5732   // FIXME: We should be able to handle f128 as well with a clever lowering.
5733   const APInt ImmInt = Imm.bitcastToAPInt();
5734   if (VT == MVT::f64)
5735     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5736   else if (VT == MVT::f32)
5737     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5738   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5739     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5740   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5741   //       generate that fmov.
5742 
5743   // If we can not materialize in immediate field for fmov, check if the
5744   // value can be encoded as the immediate operand of a logical instruction.
5745   // The immediate value will be created with either MOVZ, MOVN, or ORR.
5746   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5747     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5748     // however the mov+fmov sequence is always better because of the reduced
5749     // cache pressure. The timings are still the same if you consider
5750     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5751     // movw+movk is fused). So we limit up to 2 instrdduction at most.
5752     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5753     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5754 			      Insn);
5755     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5756     IsLegal = Insn.size() <= Limit;
5757   }
5758 
5759   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5760                     << " imm value: "; Imm.dump(););
5761   return IsLegal;
5762 }
5763 
5764 //===----------------------------------------------------------------------===//
5765 //                          AArch64 Optimization Hooks
5766 //===----------------------------------------------------------------------===//
5767 
5768 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5769                            SDValue Operand, SelectionDAG &DAG,
5770                            int &ExtraSteps) {
5771   EVT VT = Operand.getValueType();
5772   if (ST->hasNEON() &&
5773       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5774        VT == MVT::f32 || VT == MVT::v1f32 ||
5775        VT == MVT::v2f32 || VT == MVT::v4f32)) {
5776     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5777       // For the reciprocal estimates, convergence is quadratic, so the number
5778       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
5779       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
5780       // the result for float (23 mantissa bits) is 2 and for double (52
5781       // mantissa bits) is 3.
5782       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5783 
5784     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5785   }
5786 
5787   return SDValue();
5788 }
5789 
5790 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5791                                                SelectionDAG &DAG, int Enabled,
5792                                                int &ExtraSteps,
5793                                                bool &UseOneConst,
5794                                                bool Reciprocal) const {
5795   if (Enabled == ReciprocalEstimate::Enabled ||
5796       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5797     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5798                                        DAG, ExtraSteps)) {
5799       SDLoc DL(Operand);
5800       EVT VT = Operand.getValueType();
5801 
5802       SDNodeFlags Flags;
5803       Flags.setAllowReassociation(true);
5804 
5805       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5806       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5807       for (int i = ExtraSteps; i > 0; --i) {
5808         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5809                                    Flags);
5810         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5811         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5812       }
5813       if (!Reciprocal) {
5814         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5815                                       VT);
5816         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5817         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5818 
5819         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5820         // Correct the result if the operand is 0.0.
5821         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5822                                VT, Eq, Operand, Estimate);
5823       }
5824 
5825       ExtraSteps = 0;
5826       return Estimate;
5827     }
5828 
5829   return SDValue();
5830 }
5831 
5832 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5833                                                 SelectionDAG &DAG, int Enabled,
5834                                                 int &ExtraSteps) const {
5835   if (Enabled == ReciprocalEstimate::Enabled)
5836     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5837                                        DAG, ExtraSteps)) {
5838       SDLoc DL(Operand);
5839       EVT VT = Operand.getValueType();
5840 
5841       SDNodeFlags Flags;
5842       Flags.setAllowReassociation(true);
5843 
5844       // Newton reciprocal iteration: E * (2 - X * E)
5845       // AArch64 reciprocal iteration instruction: (2 - M * N)
5846       for (int i = ExtraSteps; i > 0; --i) {
5847         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5848                                    Estimate, Flags);
5849         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5850       }
5851 
5852       ExtraSteps = 0;
5853       return Estimate;
5854     }
5855 
5856   return SDValue();
5857 }
5858 
5859 //===----------------------------------------------------------------------===//
5860 //                          AArch64 Inline Assembly Support
5861 //===----------------------------------------------------------------------===//
5862 
5863 // Table of Constraints
5864 // TODO: This is the current set of constraints supported by ARM for the
5865 // compiler, not all of them may make sense.
5866 //
5867 // r - A general register
5868 // w - An FP/SIMD register of some size in the range v0-v31
5869 // x - An FP/SIMD register of some size in the range v0-v15
5870 // I - Constant that can be used with an ADD instruction
5871 // J - Constant that can be used with a SUB instruction
5872 // K - Constant that can be used with a 32-bit logical instruction
5873 // L - Constant that can be used with a 64-bit logical instruction
5874 // M - Constant that can be used as a 32-bit MOV immediate
5875 // N - Constant that can be used as a 64-bit MOV immediate
5876 // Q - A memory reference with base register and no offset
5877 // S - A symbolic address
5878 // Y - Floating point constant zero
5879 // Z - Integer constant zero
5880 //
5881 //   Note that general register operands will be output using their 64-bit x
5882 // register name, whatever the size of the variable, unless the asm operand
5883 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5884 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5885 // %q modifier.
5886 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5887   // At this point, we have to lower this constraint to something else, so we
5888   // lower it to an "r" or "w". However, by doing this we will force the result
5889   // to be in register, while the X constraint is much more permissive.
5890   //
5891   // Although we are correct (we are free to emit anything, without
5892   // constraints), we might break use cases that would expect us to be more
5893   // efficient and emit something else.
5894   if (!Subtarget->hasFPARMv8())
5895     return "r";
5896 
5897   if (ConstraintVT.isFloatingPoint())
5898     return "w";
5899 
5900   if (ConstraintVT.isVector() &&
5901      (ConstraintVT.getSizeInBits() == 64 ||
5902       ConstraintVT.getSizeInBits() == 128))
5903     return "w";
5904 
5905   return "r";
5906 }
5907 
5908 enum PredicateConstraint {
5909   Upl,
5910   Upa,
5911   Invalid
5912 };
5913 
5914 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
5915   PredicateConstraint P = PredicateConstraint::Invalid;
5916   if (Constraint == "Upa")
5917     P = PredicateConstraint::Upa;
5918   if (Constraint == "Upl")
5919     P = PredicateConstraint::Upl;
5920   return P;
5921 }
5922 
5923 /// getConstraintType - Given a constraint letter, return the type of
5924 /// constraint it is for this target.
5925 AArch64TargetLowering::ConstraintType
5926 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5927   if (Constraint.size() == 1) {
5928     switch (Constraint[0]) {
5929     default:
5930       break;
5931     case 'x':
5932     case 'w':
5933     case 'y':
5934       return C_RegisterClass;
5935     // An address with a single base register. Due to the way we
5936     // currently handle addresses it is the same as 'r'.
5937     case 'Q':
5938       return C_Memory;
5939     case 'I':
5940     case 'J':
5941     case 'K':
5942     case 'L':
5943     case 'M':
5944     case 'N':
5945     case 'Y':
5946     case 'Z':
5947       return C_Immediate;
5948     case 'z':
5949     case 'S': // A symbolic address
5950       return C_Other;
5951     }
5952   } else if (parsePredicateConstraint(Constraint) !=
5953              PredicateConstraint::Invalid)
5954       return C_RegisterClass;
5955   return TargetLowering::getConstraintType(Constraint);
5956 }
5957 
5958 /// Examine constraint type and operand type and determine a weight value.
5959 /// This object must already have been set up with the operand type
5960 /// and the current alternative constraint selected.
5961 TargetLowering::ConstraintWeight
5962 AArch64TargetLowering::getSingleConstraintMatchWeight(
5963     AsmOperandInfo &info, const char *constraint) const {
5964   ConstraintWeight weight = CW_Invalid;
5965   Value *CallOperandVal = info.CallOperandVal;
5966   // If we don't have a value, we can't do a match,
5967   // but allow it at the lowest weight.
5968   if (!CallOperandVal)
5969     return CW_Default;
5970   Type *type = CallOperandVal->getType();
5971   // Look at the constraint type.
5972   switch (*constraint) {
5973   default:
5974     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5975     break;
5976   case 'x':
5977   case 'w':
5978   case 'y':
5979     if (type->isFloatingPointTy() || type->isVectorTy())
5980       weight = CW_Register;
5981     break;
5982   case 'z':
5983     weight = CW_Constant;
5984     break;
5985   case 'U':
5986     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
5987       weight = CW_Register;
5988     break;
5989   }
5990   return weight;
5991 }
5992 
5993 std::pair<unsigned, const TargetRegisterClass *>
5994 AArch64TargetLowering::getRegForInlineAsmConstraint(
5995     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5996   if (Constraint.size() == 1) {
5997     switch (Constraint[0]) {
5998     case 'r':
5999       if (VT.getSizeInBits() == 64)
6000         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6001       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6002     case 'w':
6003       if (!Subtarget->hasFPARMv8())
6004         break;
6005       if (VT.isScalableVector())
6006         return std::make_pair(0U, &AArch64::ZPRRegClass);
6007       if (VT.getSizeInBits() == 16)
6008         return std::make_pair(0U, &AArch64::FPR16RegClass);
6009       if (VT.getSizeInBits() == 32)
6010         return std::make_pair(0U, &AArch64::FPR32RegClass);
6011       if (VT.getSizeInBits() == 64)
6012         return std::make_pair(0U, &AArch64::FPR64RegClass);
6013       if (VT.getSizeInBits() == 128)
6014         return std::make_pair(0U, &AArch64::FPR128RegClass);
6015       break;
6016     // The instructions that this constraint is designed for can
6017     // only take 128-bit registers so just use that regclass.
6018     case 'x':
6019       if (!Subtarget->hasFPARMv8())
6020         break;
6021       if (VT.isScalableVector())
6022         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6023       if (VT.getSizeInBits() == 128)
6024         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6025       break;
6026     case 'y':
6027       if (!Subtarget->hasFPARMv8())
6028         break;
6029       if (VT.isScalableVector())
6030         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6031       break;
6032     }
6033   } else {
6034     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6035     if (PC != PredicateConstraint::Invalid) {
6036       assert(VT.isScalableVector());
6037       bool restricted = (PC == PredicateConstraint::Upl);
6038       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6039                           : std::make_pair(0U, &AArch64::PPRRegClass);
6040     }
6041   }
6042   if (StringRef("{cc}").equals_lower(Constraint))
6043     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6044 
6045   // Use the default implementation in TargetLowering to convert the register
6046   // constraint into a member of a register class.
6047   std::pair<unsigned, const TargetRegisterClass *> Res;
6048   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6049 
6050   // Not found as a standard register?
6051   if (!Res.second) {
6052     unsigned Size = Constraint.size();
6053     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6054         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6055       int RegNo;
6056       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6057       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6058         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6059         // By default we'll emit v0-v31 for this unless there's a modifier where
6060         // we'll emit the correct register as well.
6061         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6062           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6063           Res.second = &AArch64::FPR64RegClass;
6064         } else {
6065           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6066           Res.second = &AArch64::FPR128RegClass;
6067         }
6068       }
6069     }
6070   }
6071 
6072   if (Res.second && !Subtarget->hasFPARMv8() &&
6073       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6074       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6075     return std::make_pair(0U, nullptr);
6076 
6077   return Res;
6078 }
6079 
6080 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6081 /// vector.  If it is invalid, don't add anything to Ops.
6082 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6083     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6084     SelectionDAG &DAG) const {
6085   SDValue Result;
6086 
6087   // Currently only support length 1 constraints.
6088   if (Constraint.length() != 1)
6089     return;
6090 
6091   char ConstraintLetter = Constraint[0];
6092   switch (ConstraintLetter) {
6093   default:
6094     break;
6095 
6096   // This set of constraints deal with valid constants for various instructions.
6097   // Validate and return a target constant for them if we can.
6098   case 'z': {
6099     // 'z' maps to xzr or wzr so it needs an input of 0.
6100     if (!isNullConstant(Op))
6101       return;
6102 
6103     if (Op.getValueType() == MVT::i64)
6104       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6105     else
6106       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6107     break;
6108   }
6109   case 'S': {
6110     // An absolute symbolic address or label reference.
6111     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6112       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6113                                           GA->getValueType(0));
6114     } else if (const BlockAddressSDNode *BA =
6115                    dyn_cast<BlockAddressSDNode>(Op)) {
6116       Result =
6117           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6118     } else if (const ExternalSymbolSDNode *ES =
6119                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6120       Result =
6121           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6122     } else
6123       return;
6124     break;
6125   }
6126 
6127   case 'I':
6128   case 'J':
6129   case 'K':
6130   case 'L':
6131   case 'M':
6132   case 'N':
6133     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6134     if (!C)
6135       return;
6136 
6137     // Grab the value and do some validation.
6138     uint64_t CVal = C->getZExtValue();
6139     switch (ConstraintLetter) {
6140     // The I constraint applies only to simple ADD or SUB immediate operands:
6141     // i.e. 0 to 4095 with optional shift by 12
6142     // The J constraint applies only to ADD or SUB immediates that would be
6143     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6144     // instruction [or vice versa], in other words -1 to -4095 with optional
6145     // left shift by 12.
6146     case 'I':
6147       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6148         break;
6149       return;
6150     case 'J': {
6151       uint64_t NVal = -C->getSExtValue();
6152       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6153         CVal = C->getSExtValue();
6154         break;
6155       }
6156       return;
6157     }
6158     // The K and L constraints apply *only* to logical immediates, including
6159     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6160     // been removed and MOV should be used). So these constraints have to
6161     // distinguish between bit patterns that are valid 32-bit or 64-bit
6162     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6163     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6164     // versa.
6165     case 'K':
6166       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6167         break;
6168       return;
6169     case 'L':
6170       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6171         break;
6172       return;
6173     // The M and N constraints are a superset of K and L respectively, for use
6174     // with the MOV (immediate) alias. As well as the logical immediates they
6175     // also match 32 or 64-bit immediates that can be loaded either using a
6176     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6177     // (M) or 64-bit 0x1234000000000000 (N) etc.
6178     // As a note some of this code is liberally stolen from the asm parser.
6179     case 'M': {
6180       if (!isUInt<32>(CVal))
6181         return;
6182       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6183         break;
6184       if ((CVal & 0xFFFF) == CVal)
6185         break;
6186       if ((CVal & 0xFFFF0000ULL) == CVal)
6187         break;
6188       uint64_t NCVal = ~(uint32_t)CVal;
6189       if ((NCVal & 0xFFFFULL) == NCVal)
6190         break;
6191       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6192         break;
6193       return;
6194     }
6195     case 'N': {
6196       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6197         break;
6198       if ((CVal & 0xFFFFULL) == CVal)
6199         break;
6200       if ((CVal & 0xFFFF0000ULL) == CVal)
6201         break;
6202       if ((CVal & 0xFFFF00000000ULL) == CVal)
6203         break;
6204       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6205         break;
6206       uint64_t NCVal = ~CVal;
6207       if ((NCVal & 0xFFFFULL) == NCVal)
6208         break;
6209       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6210         break;
6211       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6212         break;
6213       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6214         break;
6215       return;
6216     }
6217     default:
6218       return;
6219     }
6220 
6221     // All assembler immediates are 64-bit integers.
6222     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6223     break;
6224   }
6225 
6226   if (Result.getNode()) {
6227     Ops.push_back(Result);
6228     return;
6229   }
6230 
6231   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6232 }
6233 
6234 //===----------------------------------------------------------------------===//
6235 //                     AArch64 Advanced SIMD Support
6236 //===----------------------------------------------------------------------===//
6237 
6238 /// WidenVector - Given a value in the V64 register class, produce the
6239 /// equivalent value in the V128 register class.
6240 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6241   EVT VT = V64Reg.getValueType();
6242   unsigned NarrowSize = VT.getVectorNumElements();
6243   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6244   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6245   SDLoc DL(V64Reg);
6246 
6247   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6248                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6249 }
6250 
6251 /// getExtFactor - Determine the adjustment factor for the position when
6252 /// generating an "extract from vector registers" instruction.
6253 static unsigned getExtFactor(SDValue &V) {
6254   EVT EltType = V.getValueType().getVectorElementType();
6255   return EltType.getSizeInBits() / 8;
6256 }
6257 
6258 /// NarrowVector - Given a value in the V128 register class, produce the
6259 /// equivalent value in the V64 register class.
6260 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6261   EVT VT = V128Reg.getValueType();
6262   unsigned WideSize = VT.getVectorNumElements();
6263   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6264   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6265   SDLoc DL(V128Reg);
6266 
6267   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6268 }
6269 
6270 // Gather data to see if the operation can be modelled as a
6271 // shuffle in combination with VEXTs.
6272 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6273                                                   SelectionDAG &DAG) const {
6274   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6275   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6276   SDLoc dl(Op);
6277   EVT VT = Op.getValueType();
6278   unsigned NumElts = VT.getVectorNumElements();
6279 
6280   struct ShuffleSourceInfo {
6281     SDValue Vec;
6282     unsigned MinElt;
6283     unsigned MaxElt;
6284 
6285     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6286     // be compatible with the shuffle we intend to construct. As a result
6287     // ShuffleVec will be some sliding window into the original Vec.
6288     SDValue ShuffleVec;
6289 
6290     // Code should guarantee that element i in Vec starts at element "WindowBase
6291     // + i * WindowScale in ShuffleVec".
6292     int WindowBase;
6293     int WindowScale;
6294 
6295     ShuffleSourceInfo(SDValue Vec)
6296       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6297           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6298 
6299     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6300   };
6301 
6302   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6303   // node.
6304   SmallVector<ShuffleSourceInfo, 2> Sources;
6305   for (unsigned i = 0; i < NumElts; ++i) {
6306     SDValue V = Op.getOperand(i);
6307     if (V.isUndef())
6308       continue;
6309     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6310              !isa<ConstantSDNode>(V.getOperand(1))) {
6311       LLVM_DEBUG(
6312           dbgs() << "Reshuffle failed: "
6313                     "a shuffle can only come from building a vector from "
6314                     "various elements of other vectors, provided their "
6315                     "indices are constant\n");
6316       return SDValue();
6317     }
6318 
6319     // Add this element source to the list if it's not already there.
6320     SDValue SourceVec = V.getOperand(0);
6321     auto Source = find(Sources, SourceVec);
6322     if (Source == Sources.end())
6323       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6324 
6325     // Update the minimum and maximum lane number seen.
6326     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6327     Source->MinElt = std::min(Source->MinElt, EltNo);
6328     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6329   }
6330 
6331   if (Sources.size() > 2) {
6332     LLVM_DEBUG(
6333         dbgs() << "Reshuffle failed: currently only do something sane when at "
6334                   "most two source vectors are involved\n");
6335     return SDValue();
6336   }
6337 
6338   // Find out the smallest element size among result and two sources, and use
6339   // it as element size to build the shuffle_vector.
6340   EVT SmallestEltTy = VT.getVectorElementType();
6341   for (auto &Source : Sources) {
6342     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6343     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6344       SmallestEltTy = SrcEltTy;
6345     }
6346   }
6347   unsigned ResMultiplier =
6348       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6349   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6350   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6351 
6352   // If the source vector is too wide or too narrow, we may nevertheless be able
6353   // to construct a compatible shuffle either by concatenating it with UNDEF or
6354   // extracting a suitable range of elements.
6355   for (auto &Src : Sources) {
6356     EVT SrcVT = Src.ShuffleVec.getValueType();
6357 
6358     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6359       continue;
6360 
6361     // This stage of the search produces a source with the same element type as
6362     // the original, but with a total width matching the BUILD_VECTOR output.
6363     EVT EltVT = SrcVT.getVectorElementType();
6364     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6365     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6366 
6367     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6368       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6369       // We can pad out the smaller vector for free, so if it's part of a
6370       // shuffle...
6371       Src.ShuffleVec =
6372           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6373                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6374       continue;
6375     }
6376 
6377     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6378 
6379     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6380       LLVM_DEBUG(
6381           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6382       return SDValue();
6383     }
6384 
6385     if (Src.MinElt >= NumSrcElts) {
6386       // The extraction can just take the second half
6387       Src.ShuffleVec =
6388           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6389                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6390       Src.WindowBase = -NumSrcElts;
6391     } else if (Src.MaxElt < NumSrcElts) {
6392       // The extraction can just take the first half
6393       Src.ShuffleVec =
6394           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6395                       DAG.getConstant(0, dl, MVT::i64));
6396     } else {
6397       // An actual VEXT is needed
6398       SDValue VEXTSrc1 =
6399           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6400                       DAG.getConstant(0, dl, MVT::i64));
6401       SDValue VEXTSrc2 =
6402           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6403                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6404       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6405 
6406       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6407                                    VEXTSrc2,
6408                                    DAG.getConstant(Imm, dl, MVT::i32));
6409       Src.WindowBase = -Src.MinElt;
6410     }
6411   }
6412 
6413   // Another possible incompatibility occurs from the vector element types. We
6414   // can fix this by bitcasting the source vectors to the same type we intend
6415   // for the shuffle.
6416   for (auto &Src : Sources) {
6417     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6418     if (SrcEltTy == SmallestEltTy)
6419       continue;
6420     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6421     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6422     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6423     Src.WindowBase *= Src.WindowScale;
6424   }
6425 
6426   // Final sanity check before we try to actually produce a shuffle.
6427   LLVM_DEBUG(for (auto Src
6428                   : Sources)
6429                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6430 
6431   // The stars all align, our next step is to produce the mask for the shuffle.
6432   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6433   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6434   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6435     SDValue Entry = Op.getOperand(i);
6436     if (Entry.isUndef())
6437       continue;
6438 
6439     auto Src = find(Sources, Entry.getOperand(0));
6440     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6441 
6442     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6443     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6444     // segment.
6445     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6446     int BitsDefined =
6447         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6448     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6449 
6450     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6451     // starting at the appropriate offset.
6452     int *LaneMask = &Mask[i * ResMultiplier];
6453 
6454     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6455     ExtractBase += NumElts * (Src - Sources.begin());
6456     for (int j = 0; j < LanesDefined; ++j)
6457       LaneMask[j] = ExtractBase + j;
6458   }
6459 
6460   // Final check before we try to produce nonsense...
6461   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6462     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6463     return SDValue();
6464   }
6465 
6466   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6467   for (unsigned i = 0; i < Sources.size(); ++i)
6468     ShuffleOps[i] = Sources[i].ShuffleVec;
6469 
6470   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6471                                          ShuffleOps[1], Mask);
6472   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6473 
6474   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6475              dbgs() << "Reshuffle, creating node: "; V.dump(););
6476 
6477   return V;
6478 }
6479 
6480 // check if an EXT instruction can handle the shuffle mask when the
6481 // vector sources of the shuffle are the same.
6482 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6483   unsigned NumElts = VT.getVectorNumElements();
6484 
6485   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6486   if (M[0] < 0)
6487     return false;
6488 
6489   Imm = M[0];
6490 
6491   // If this is a VEXT shuffle, the immediate value is the index of the first
6492   // element.  The other shuffle indices must be the successive elements after
6493   // the first one.
6494   unsigned ExpectedElt = Imm;
6495   for (unsigned i = 1; i < NumElts; ++i) {
6496     // Increment the expected index.  If it wraps around, just follow it
6497     // back to index zero and keep going.
6498     ++ExpectedElt;
6499     if (ExpectedElt == NumElts)
6500       ExpectedElt = 0;
6501 
6502     if (M[i] < 0)
6503       continue; // ignore UNDEF indices
6504     if (ExpectedElt != static_cast<unsigned>(M[i]))
6505       return false;
6506   }
6507 
6508   return true;
6509 }
6510 
6511 // check if an EXT instruction can handle the shuffle mask when the
6512 // vector sources of the shuffle are different.
6513 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6514                       unsigned &Imm) {
6515   // Look for the first non-undef element.
6516   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6517 
6518   // Benefit form APInt to handle overflow when calculating expected element.
6519   unsigned NumElts = VT.getVectorNumElements();
6520   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6521   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6522   // The following shuffle indices must be the successive elements after the
6523   // first real element.
6524   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6525       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6526   if (FirstWrongElt != M.end())
6527     return false;
6528 
6529   // The index of an EXT is the first element if it is not UNDEF.
6530   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6531   // value of the first element.  E.g.
6532   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6533   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6534   // ExpectedElt is the last mask index plus 1.
6535   Imm = ExpectedElt.getZExtValue();
6536 
6537   // There are two difference cases requiring to reverse input vectors.
6538   // For example, for vector <4 x i32> we have the following cases,
6539   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6540   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6541   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6542   // to reverse two input vectors.
6543   if (Imm < NumElts)
6544     ReverseEXT = true;
6545   else
6546     Imm -= NumElts;
6547 
6548   return true;
6549 }
6550 
6551 /// isREVMask - Check if a vector shuffle corresponds to a REV
6552 /// instruction with the specified blocksize.  (The order of the elements
6553 /// within each block of the vector is reversed.)
6554 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6555   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6556          "Only possible block sizes for REV are: 16, 32, 64");
6557 
6558   unsigned EltSz = VT.getScalarSizeInBits();
6559   if (EltSz == 64)
6560     return false;
6561 
6562   unsigned NumElts = VT.getVectorNumElements();
6563   unsigned BlockElts = M[0] + 1;
6564   // If the first shuffle index is UNDEF, be optimistic.
6565   if (M[0] < 0)
6566     BlockElts = BlockSize / EltSz;
6567 
6568   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6569     return false;
6570 
6571   for (unsigned i = 0; i < NumElts; ++i) {
6572     if (M[i] < 0)
6573       continue; // ignore UNDEF indices
6574     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6575       return false;
6576   }
6577 
6578   return true;
6579 }
6580 
6581 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6582   unsigned NumElts = VT.getVectorNumElements();
6583   if (NumElts % 2 != 0)
6584     return false;
6585   WhichResult = (M[0] == 0 ? 0 : 1);
6586   unsigned Idx = WhichResult * NumElts / 2;
6587   for (unsigned i = 0; i != NumElts; i += 2) {
6588     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6589         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6590       return false;
6591     Idx += 1;
6592   }
6593 
6594   return true;
6595 }
6596 
6597 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6598   unsigned NumElts = VT.getVectorNumElements();
6599   WhichResult = (M[0] == 0 ? 0 : 1);
6600   for (unsigned i = 0; i != NumElts; ++i) {
6601     if (M[i] < 0)
6602       continue; // ignore UNDEF indices
6603     if ((unsigned)M[i] != 2 * i + WhichResult)
6604       return false;
6605   }
6606 
6607   return true;
6608 }
6609 
6610 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6611   unsigned NumElts = VT.getVectorNumElements();
6612   if (NumElts % 2 != 0)
6613     return false;
6614   WhichResult = (M[0] == 0 ? 0 : 1);
6615   for (unsigned i = 0; i < NumElts; i += 2) {
6616     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6617         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6618       return false;
6619   }
6620   return true;
6621 }
6622 
6623 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6624 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6625 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6626 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6627   unsigned NumElts = VT.getVectorNumElements();
6628   if (NumElts % 2 != 0)
6629     return false;
6630   WhichResult = (M[0] == 0 ? 0 : 1);
6631   unsigned Idx = WhichResult * NumElts / 2;
6632   for (unsigned i = 0; i != NumElts; i += 2) {
6633     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6634         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6635       return false;
6636     Idx += 1;
6637   }
6638 
6639   return true;
6640 }
6641 
6642 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6643 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6644 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6645 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6646   unsigned Half = VT.getVectorNumElements() / 2;
6647   WhichResult = (M[0] == 0 ? 0 : 1);
6648   for (unsigned j = 0; j != 2; ++j) {
6649     unsigned Idx = WhichResult;
6650     for (unsigned i = 0; i != Half; ++i) {
6651       int MIdx = M[i + j * Half];
6652       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6653         return false;
6654       Idx += 2;
6655     }
6656   }
6657 
6658   return true;
6659 }
6660 
6661 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6662 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6663 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6664 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6665   unsigned NumElts = VT.getVectorNumElements();
6666   if (NumElts % 2 != 0)
6667     return false;
6668   WhichResult = (M[0] == 0 ? 0 : 1);
6669   for (unsigned i = 0; i < NumElts; i += 2) {
6670     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6671         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6672       return false;
6673   }
6674   return true;
6675 }
6676 
6677 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6678                       bool &DstIsLeft, int &Anomaly) {
6679   if (M.size() != static_cast<size_t>(NumInputElements))
6680     return false;
6681 
6682   int NumLHSMatch = 0, NumRHSMatch = 0;
6683   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6684 
6685   for (int i = 0; i < NumInputElements; ++i) {
6686     if (M[i] == -1) {
6687       ++NumLHSMatch;
6688       ++NumRHSMatch;
6689       continue;
6690     }
6691 
6692     if (M[i] == i)
6693       ++NumLHSMatch;
6694     else
6695       LastLHSMismatch = i;
6696 
6697     if (M[i] == i + NumInputElements)
6698       ++NumRHSMatch;
6699     else
6700       LastRHSMismatch = i;
6701   }
6702 
6703   if (NumLHSMatch == NumInputElements - 1) {
6704     DstIsLeft = true;
6705     Anomaly = LastLHSMismatch;
6706     return true;
6707   } else if (NumRHSMatch == NumInputElements - 1) {
6708     DstIsLeft = false;
6709     Anomaly = LastRHSMismatch;
6710     return true;
6711   }
6712 
6713   return false;
6714 }
6715 
6716 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6717   if (VT.getSizeInBits() != 128)
6718     return false;
6719 
6720   unsigned NumElts = VT.getVectorNumElements();
6721 
6722   for (int I = 0, E = NumElts / 2; I != E; I++) {
6723     if (Mask[I] != I)
6724       return false;
6725   }
6726 
6727   int Offset = NumElts / 2;
6728   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6729     if (Mask[I] != I + SplitLHS * Offset)
6730       return false;
6731   }
6732 
6733   return true;
6734 }
6735 
6736 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6737   SDLoc DL(Op);
6738   EVT VT = Op.getValueType();
6739   SDValue V0 = Op.getOperand(0);
6740   SDValue V1 = Op.getOperand(1);
6741   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6742 
6743   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6744       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6745     return SDValue();
6746 
6747   bool SplitV0 = V0.getValueSizeInBits() == 128;
6748 
6749   if (!isConcatMask(Mask, VT, SplitV0))
6750     return SDValue();
6751 
6752   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
6753   if (SplitV0) {
6754     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6755                      DAG.getConstant(0, DL, MVT::i64));
6756   }
6757   if (V1.getValueSizeInBits() == 128) {
6758     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6759                      DAG.getConstant(0, DL, MVT::i64));
6760   }
6761   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6762 }
6763 
6764 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6765 /// the specified operations to build the shuffle.
6766 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6767                                       SDValue RHS, SelectionDAG &DAG,
6768                                       const SDLoc &dl) {
6769   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6770   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6771   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6772 
6773   enum {
6774     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6775     OP_VREV,
6776     OP_VDUP0,
6777     OP_VDUP1,
6778     OP_VDUP2,
6779     OP_VDUP3,
6780     OP_VEXT1,
6781     OP_VEXT2,
6782     OP_VEXT3,
6783     OP_VUZPL, // VUZP, left result
6784     OP_VUZPR, // VUZP, right result
6785     OP_VZIPL, // VZIP, left result
6786     OP_VZIPR, // VZIP, right result
6787     OP_VTRNL, // VTRN, left result
6788     OP_VTRNR  // VTRN, right result
6789   };
6790 
6791   if (OpNum == OP_COPY) {
6792     if (LHSID == (1 * 9 + 2) * 9 + 3)
6793       return LHS;
6794     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6795     return RHS;
6796   }
6797 
6798   SDValue OpLHS, OpRHS;
6799   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6800   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6801   EVT VT = OpLHS.getValueType();
6802 
6803   switch (OpNum) {
6804   default:
6805     llvm_unreachable("Unknown shuffle opcode!");
6806   case OP_VREV:
6807     // VREV divides the vector in half and swaps within the half.
6808     if (VT.getVectorElementType() == MVT::i32 ||
6809         VT.getVectorElementType() == MVT::f32)
6810       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6811     // vrev <4 x i16> -> REV32
6812     if (VT.getVectorElementType() == MVT::i16 ||
6813         VT.getVectorElementType() == MVT::f16)
6814       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6815     // vrev <4 x i8> -> REV16
6816     assert(VT.getVectorElementType() == MVT::i8);
6817     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6818   case OP_VDUP0:
6819   case OP_VDUP1:
6820   case OP_VDUP2:
6821   case OP_VDUP3: {
6822     EVT EltTy = VT.getVectorElementType();
6823     unsigned Opcode;
6824     if (EltTy == MVT::i8)
6825       Opcode = AArch64ISD::DUPLANE8;
6826     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6827       Opcode = AArch64ISD::DUPLANE16;
6828     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6829       Opcode = AArch64ISD::DUPLANE32;
6830     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6831       Opcode = AArch64ISD::DUPLANE64;
6832     else
6833       llvm_unreachable("Invalid vector element type?");
6834 
6835     if (VT.getSizeInBits() == 64)
6836       OpLHS = WidenVector(OpLHS, DAG);
6837     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6838     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6839   }
6840   case OP_VEXT1:
6841   case OP_VEXT2:
6842   case OP_VEXT3: {
6843     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6844     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6845                        DAG.getConstant(Imm, dl, MVT::i32));
6846   }
6847   case OP_VUZPL:
6848     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6849                        OpRHS);
6850   case OP_VUZPR:
6851     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6852                        OpRHS);
6853   case OP_VZIPL:
6854     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6855                        OpRHS);
6856   case OP_VZIPR:
6857     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6858                        OpRHS);
6859   case OP_VTRNL:
6860     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6861                        OpRHS);
6862   case OP_VTRNR:
6863     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6864                        OpRHS);
6865   }
6866 }
6867 
6868 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6869                            SelectionDAG &DAG) {
6870   // Check to see if we can use the TBL instruction.
6871   SDValue V1 = Op.getOperand(0);
6872   SDValue V2 = Op.getOperand(1);
6873   SDLoc DL(Op);
6874 
6875   EVT EltVT = Op.getValueType().getVectorElementType();
6876   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6877 
6878   SmallVector<SDValue, 8> TBLMask;
6879   for (int Val : ShuffleMask) {
6880     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6881       unsigned Offset = Byte + Val * BytesPerElt;
6882       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6883     }
6884   }
6885 
6886   MVT IndexVT = MVT::v8i8;
6887   unsigned IndexLen = 8;
6888   if (Op.getValueSizeInBits() == 128) {
6889     IndexVT = MVT::v16i8;
6890     IndexLen = 16;
6891   }
6892 
6893   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6894   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6895 
6896   SDValue Shuffle;
6897   if (V2.getNode()->isUndef()) {
6898     if (IndexLen == 8)
6899       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6900     Shuffle = DAG.getNode(
6901         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6902         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6903         DAG.getBuildVector(IndexVT, DL,
6904                            makeArrayRef(TBLMask.data(), IndexLen)));
6905   } else {
6906     if (IndexLen == 8) {
6907       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6908       Shuffle = DAG.getNode(
6909           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6910           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6911           DAG.getBuildVector(IndexVT, DL,
6912                              makeArrayRef(TBLMask.data(), IndexLen)));
6913     } else {
6914       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6915       // cannot currently represent the register constraints on the input
6916       // table registers.
6917       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6918       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6919       //                   IndexLen));
6920       Shuffle = DAG.getNode(
6921           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6922           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6923           V2Cst, DAG.getBuildVector(IndexVT, DL,
6924                                     makeArrayRef(TBLMask.data(), IndexLen)));
6925     }
6926   }
6927   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6928 }
6929 
6930 static unsigned getDUPLANEOp(EVT EltType) {
6931   if (EltType == MVT::i8)
6932     return AArch64ISD::DUPLANE8;
6933   if (EltType == MVT::i16 || EltType == MVT::f16)
6934     return AArch64ISD::DUPLANE16;
6935   if (EltType == MVT::i32 || EltType == MVT::f32)
6936     return AArch64ISD::DUPLANE32;
6937   if (EltType == MVT::i64 || EltType == MVT::f64)
6938     return AArch64ISD::DUPLANE64;
6939 
6940   llvm_unreachable("Invalid vector element type?");
6941 }
6942 
6943 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6944                                                    SelectionDAG &DAG) const {
6945   SDLoc dl(Op);
6946   EVT VT = Op.getValueType();
6947 
6948   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6949 
6950   // Convert shuffles that are directly supported on NEON to target-specific
6951   // DAG nodes, instead of keeping them as shuffles and matching them again
6952   // during code selection.  This is more efficient and avoids the possibility
6953   // of inconsistencies between legalization and selection.
6954   ArrayRef<int> ShuffleMask = SVN->getMask();
6955 
6956   SDValue V1 = Op.getOperand(0);
6957   SDValue V2 = Op.getOperand(1);
6958 
6959   if (SVN->isSplat()) {
6960     int Lane = SVN->getSplatIndex();
6961     // If this is undef splat, generate it via "just" vdup, if possible.
6962     if (Lane == -1)
6963       Lane = 0;
6964 
6965     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6966       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6967                          V1.getOperand(0));
6968     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6969     // constant. If so, we can just reference the lane's definition directly.
6970     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6971         !isa<ConstantSDNode>(V1.getOperand(Lane)))
6972       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6973 
6974     // Otherwise, duplicate from the lane of the input vector.
6975     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6976 
6977     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6978     // to make a vector of the same size as this SHUFFLE. We can ignore the
6979     // extract entirely, and canonicalise the concat using WidenVector.
6980     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6981       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6982       V1 = V1.getOperand(0);
6983     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6984       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6985       Lane -= Idx * VT.getVectorNumElements() / 2;
6986       V1 = WidenVector(V1.getOperand(Idx), DAG);
6987     } else if (VT.getSizeInBits() == 64)
6988       V1 = WidenVector(V1, DAG);
6989 
6990     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6991   }
6992 
6993   if (isREVMask(ShuffleMask, VT, 64))
6994     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6995   if (isREVMask(ShuffleMask, VT, 32))
6996     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6997   if (isREVMask(ShuffleMask, VT, 16))
6998     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6999 
7000   bool ReverseEXT = false;
7001   unsigned Imm;
7002   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7003     if (ReverseEXT)
7004       std::swap(V1, V2);
7005     Imm *= getExtFactor(V1);
7006     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7007                        DAG.getConstant(Imm, dl, MVT::i32));
7008   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7009     Imm *= getExtFactor(V1);
7010     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7011                        DAG.getConstant(Imm, dl, MVT::i32));
7012   }
7013 
7014   unsigned WhichResult;
7015   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7016     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7017     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7018   }
7019   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7020     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7021     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7022   }
7023   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7024     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7025     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7026   }
7027 
7028   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7029     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7030     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7031   }
7032   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7033     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7034     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7035   }
7036   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7037     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7038     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7039   }
7040 
7041   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7042     return Concat;
7043 
7044   bool DstIsLeft;
7045   int Anomaly;
7046   int NumInputElements = V1.getValueType().getVectorNumElements();
7047   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7048     SDValue DstVec = DstIsLeft ? V1 : V2;
7049     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7050 
7051     SDValue SrcVec = V1;
7052     int SrcLane = ShuffleMask[Anomaly];
7053     if (SrcLane >= NumInputElements) {
7054       SrcVec = V2;
7055       SrcLane -= VT.getVectorNumElements();
7056     }
7057     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7058 
7059     EVT ScalarVT = VT.getVectorElementType();
7060 
7061     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7062       ScalarVT = MVT::i32;
7063 
7064     return DAG.getNode(
7065         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7066         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7067         DstLaneV);
7068   }
7069 
7070   // If the shuffle is not directly supported and it has 4 elements, use
7071   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7072   unsigned NumElts = VT.getVectorNumElements();
7073   if (NumElts == 4) {
7074     unsigned PFIndexes[4];
7075     for (unsigned i = 0; i != 4; ++i) {
7076       if (ShuffleMask[i] < 0)
7077         PFIndexes[i] = 8;
7078       else
7079         PFIndexes[i] = ShuffleMask[i];
7080     }
7081 
7082     // Compute the index in the perfect shuffle table.
7083     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7084                             PFIndexes[2] * 9 + PFIndexes[3];
7085     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7086     unsigned Cost = (PFEntry >> 30);
7087 
7088     if (Cost <= 4)
7089       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7090   }
7091 
7092   return GenerateTBL(Op, ShuffleMask, DAG);
7093 }
7094 
7095 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7096                                                  SelectionDAG &DAG) const {
7097   SDLoc dl(Op);
7098   EVT VT = Op.getValueType();
7099   EVT ElemVT = VT.getScalarType();
7100 
7101   SDValue SplatVal = Op.getOperand(0);
7102 
7103   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7104   // FPRs don't have this restriction.
7105   switch (ElemVT.getSimpleVT().SimpleTy) {
7106   case MVT::i8:
7107   case MVT::i16:
7108     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7109     break;
7110   case MVT::i64:
7111     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7112     break;
7113   case MVT::i32:
7114     // Fine as is
7115     break;
7116   // TODO: we can support splats of i1s and float types, but haven't added
7117   // patterns yet.
7118   case MVT::i1:
7119   case MVT::f16:
7120   case MVT::f32:
7121   case MVT::f64:
7122   default:
7123     llvm_unreachable("Unsupported SPLAT_VECTOR input operand type");
7124     break;
7125   }
7126 
7127   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7128 }
7129 
7130 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7131                                APInt &UndefBits) {
7132   EVT VT = BVN->getValueType(0);
7133   APInt SplatBits, SplatUndef;
7134   unsigned SplatBitSize;
7135   bool HasAnyUndefs;
7136   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7137     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7138 
7139     for (unsigned i = 0; i < NumSplats; ++i) {
7140       CnstBits <<= SplatBitSize;
7141       UndefBits <<= SplatBitSize;
7142       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7143       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7144     }
7145 
7146     return true;
7147   }
7148 
7149   return false;
7150 }
7151 
7152 // Try 64-bit splatted SIMD immediate.
7153 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7154                                  const APInt &Bits) {
7155   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7156     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7157     EVT VT = Op.getValueType();
7158     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7159 
7160     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7161       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7162 
7163       SDLoc dl(Op);
7164       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7165                                 DAG.getConstant(Value, dl, MVT::i32));
7166       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7167     }
7168   }
7169 
7170   return SDValue();
7171 }
7172 
7173 // Try 32-bit splatted SIMD immediate.
7174 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7175                                   const APInt &Bits,
7176                                   const SDValue *LHS = nullptr) {
7177   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7178     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7179     EVT VT = Op.getValueType();
7180     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7181     bool isAdvSIMDModImm = false;
7182     uint64_t Shift;
7183 
7184     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7185       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7186       Shift = 0;
7187     }
7188     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7189       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7190       Shift = 8;
7191     }
7192     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7193       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7194       Shift = 16;
7195     }
7196     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7197       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7198       Shift = 24;
7199     }
7200 
7201     if (isAdvSIMDModImm) {
7202       SDLoc dl(Op);
7203       SDValue Mov;
7204 
7205       if (LHS)
7206         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7207                           DAG.getConstant(Value, dl, MVT::i32),
7208                           DAG.getConstant(Shift, dl, MVT::i32));
7209       else
7210         Mov = DAG.getNode(NewOp, dl, MovTy,
7211                           DAG.getConstant(Value, dl, MVT::i32),
7212                           DAG.getConstant(Shift, dl, MVT::i32));
7213 
7214       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7215     }
7216   }
7217 
7218   return SDValue();
7219 }
7220 
7221 // Try 16-bit splatted SIMD immediate.
7222 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7223                                   const APInt &Bits,
7224                                   const SDValue *LHS = nullptr) {
7225   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7226     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7227     EVT VT = Op.getValueType();
7228     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7229     bool isAdvSIMDModImm = false;
7230     uint64_t Shift;
7231 
7232     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7233       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7234       Shift = 0;
7235     }
7236     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7237       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7238       Shift = 8;
7239     }
7240 
7241     if (isAdvSIMDModImm) {
7242       SDLoc dl(Op);
7243       SDValue Mov;
7244 
7245       if (LHS)
7246         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7247                           DAG.getConstant(Value, dl, MVT::i32),
7248                           DAG.getConstant(Shift, dl, MVT::i32));
7249       else
7250         Mov = DAG.getNode(NewOp, dl, MovTy,
7251                           DAG.getConstant(Value, dl, MVT::i32),
7252                           DAG.getConstant(Shift, dl, MVT::i32));
7253 
7254       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7255     }
7256   }
7257 
7258   return SDValue();
7259 }
7260 
7261 // Try 32-bit splatted SIMD immediate with shifted ones.
7262 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7263                                     SelectionDAG &DAG, const APInt &Bits) {
7264   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7265     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7266     EVT VT = Op.getValueType();
7267     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7268     bool isAdvSIMDModImm = false;
7269     uint64_t Shift;
7270 
7271     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7272       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7273       Shift = 264;
7274     }
7275     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7276       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7277       Shift = 272;
7278     }
7279 
7280     if (isAdvSIMDModImm) {
7281       SDLoc dl(Op);
7282       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7283                                 DAG.getConstant(Value, dl, MVT::i32),
7284                                 DAG.getConstant(Shift, dl, MVT::i32));
7285       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7286     }
7287   }
7288 
7289   return SDValue();
7290 }
7291 
7292 // Try 8-bit splatted SIMD immediate.
7293 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7294                                  const APInt &Bits) {
7295   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7296     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7297     EVT VT = Op.getValueType();
7298     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7299 
7300     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7301       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7302 
7303       SDLoc dl(Op);
7304       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7305                                 DAG.getConstant(Value, dl, MVT::i32));
7306       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7307     }
7308   }
7309 
7310   return SDValue();
7311 }
7312 
7313 // Try FP splatted SIMD immediate.
7314 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7315                                   const APInt &Bits) {
7316   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7317     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7318     EVT VT = Op.getValueType();
7319     bool isWide = (VT.getSizeInBits() == 128);
7320     MVT MovTy;
7321     bool isAdvSIMDModImm = false;
7322 
7323     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7324       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7325       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7326     }
7327     else if (isWide &&
7328              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7329       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7330       MovTy = MVT::v2f64;
7331     }
7332 
7333     if (isAdvSIMDModImm) {
7334       SDLoc dl(Op);
7335       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7336                                 DAG.getConstant(Value, dl, MVT::i32));
7337       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7338     }
7339   }
7340 
7341   return SDValue();
7342 }
7343 
7344 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7345 // consists of only the same constant int value, returned in reference arg
7346 // ConstVal
7347 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7348                                      uint64_t &ConstVal) {
7349   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7350   if (!Bvec)
7351     return false;
7352   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7353   if (!FirstElt)
7354     return false;
7355   EVT VT = Bvec->getValueType(0);
7356   unsigned NumElts = VT.getVectorNumElements();
7357   for (unsigned i = 1; i < NumElts; ++i)
7358     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7359       return false;
7360   ConstVal = FirstElt->getZExtValue();
7361   return true;
7362 }
7363 
7364 static unsigned getIntrinsicID(const SDNode *N) {
7365   unsigned Opcode = N->getOpcode();
7366   switch (Opcode) {
7367   default:
7368     return Intrinsic::not_intrinsic;
7369   case ISD::INTRINSIC_WO_CHAIN: {
7370     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7371     if (IID < Intrinsic::num_intrinsics)
7372       return IID;
7373     return Intrinsic::not_intrinsic;
7374   }
7375   }
7376 }
7377 
7378 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7379 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7380 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7381 // Also, logical shift right -> sri, with the same structure.
7382 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7383   EVT VT = N->getValueType(0);
7384 
7385   if (!VT.isVector())
7386     return SDValue();
7387 
7388   SDLoc DL(N);
7389 
7390   // Is the first op an AND?
7391   const SDValue And = N->getOperand(0);
7392   if (And.getOpcode() != ISD::AND)
7393     return SDValue();
7394 
7395   // Is the second op an shl or lshr?
7396   SDValue Shift = N->getOperand(1);
7397   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7398   // or AArch64ISD::VLSHR vector, #shift
7399   unsigned ShiftOpc = Shift.getOpcode();
7400   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7401     return SDValue();
7402   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7403 
7404   // Is the shift amount constant?
7405   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7406   if (!C2node)
7407     return SDValue();
7408 
7409   // Is the and mask vector all constant?
7410   uint64_t C1;
7411   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7412     return SDValue();
7413 
7414   // Is C1 == ~C2, taking into account how much one can shift elements of a
7415   // particular size?
7416   uint64_t C2 = C2node->getZExtValue();
7417   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7418   if (C2 > ElemSizeInBits)
7419     return SDValue();
7420   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7421   if ((C1 & ElemMask) != (~C2 & ElemMask))
7422     return SDValue();
7423 
7424   SDValue X = And.getOperand(0);
7425   SDValue Y = Shift.getOperand(0);
7426 
7427   unsigned Intrin =
7428       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7429   SDValue ResultSLI =
7430       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7431                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7432                   Shift.getOperand(1));
7433 
7434   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7435   LLVM_DEBUG(N->dump(&DAG));
7436   LLVM_DEBUG(dbgs() << "into: \n");
7437   LLVM_DEBUG(ResultSLI->dump(&DAG));
7438 
7439   ++NumShiftInserts;
7440   return ResultSLI;
7441 }
7442 
7443 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7444                                              SelectionDAG &DAG) const {
7445   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7446   if (EnableAArch64SlrGeneration) {
7447     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7448       return Res;
7449   }
7450 
7451   EVT VT = Op.getValueType();
7452 
7453   SDValue LHS = Op.getOperand(0);
7454   BuildVectorSDNode *BVN =
7455       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7456   if (!BVN) {
7457     // OR commutes, so try swapping the operands.
7458     LHS = Op.getOperand(1);
7459     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7460   }
7461   if (!BVN)
7462     return Op;
7463 
7464   APInt DefBits(VT.getSizeInBits(), 0);
7465   APInt UndefBits(VT.getSizeInBits(), 0);
7466   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7467     SDValue NewOp;
7468 
7469     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7470                                     DefBits, &LHS)) ||
7471         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7472                                     DefBits, &LHS)))
7473       return NewOp;
7474 
7475     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7476                                     UndefBits, &LHS)) ||
7477         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7478                                     UndefBits, &LHS)))
7479       return NewOp;
7480   }
7481 
7482   // We can always fall back to a non-immediate OR.
7483   return Op;
7484 }
7485 
7486 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7487 // be truncated to fit element width.
7488 static SDValue NormalizeBuildVector(SDValue Op,
7489                                     SelectionDAG &DAG) {
7490   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7491   SDLoc dl(Op);
7492   EVT VT = Op.getValueType();
7493   EVT EltTy= VT.getVectorElementType();
7494 
7495   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7496     return Op;
7497 
7498   SmallVector<SDValue, 16> Ops;
7499   for (SDValue Lane : Op->ops()) {
7500     // For integer vectors, type legalization would have promoted the
7501     // operands already. Otherwise, if Op is a floating-point splat
7502     // (with operands cast to integers), then the only possibilities
7503     // are constants and UNDEFs.
7504     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7505       APInt LowBits(EltTy.getSizeInBits(),
7506                     CstLane->getZExtValue());
7507       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7508     } else if (Lane.getNode()->isUndef()) {
7509       Lane = DAG.getUNDEF(MVT::i32);
7510     } else {
7511       assert(Lane.getValueType() == MVT::i32 &&
7512              "Unexpected BUILD_VECTOR operand type");
7513     }
7514     Ops.push_back(Lane);
7515   }
7516   return DAG.getBuildVector(VT, dl, Ops);
7517 }
7518 
7519 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7520   EVT VT = Op.getValueType();
7521 
7522   APInt DefBits(VT.getSizeInBits(), 0);
7523   APInt UndefBits(VT.getSizeInBits(), 0);
7524   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7525   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7526     SDValue NewOp;
7527     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7528         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7529         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7530         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7531         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7532         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7533       return NewOp;
7534 
7535     DefBits = ~DefBits;
7536     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7537         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7538         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7539       return NewOp;
7540 
7541     DefBits = UndefBits;
7542     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7543         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7544         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7545         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7546         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7547         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7548       return NewOp;
7549 
7550     DefBits = ~UndefBits;
7551     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7552         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7553         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7554       return NewOp;
7555   }
7556 
7557   return SDValue();
7558 }
7559 
7560 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7561                                                  SelectionDAG &DAG) const {
7562   EVT VT = Op.getValueType();
7563 
7564   // Try to build a simple constant vector.
7565   Op = NormalizeBuildVector(Op, DAG);
7566   if (VT.isInteger()) {
7567     // Certain vector constants, used to express things like logical NOT and
7568     // arithmetic NEG, are passed through unmodified.  This allows special
7569     // patterns for these operations to match, which will lower these constants
7570     // to whatever is proven necessary.
7571     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7572     if (BVN->isConstant())
7573       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7574         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7575         APInt Val(BitSize,
7576                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7577         if (Val.isNullValue() || Val.isAllOnesValue())
7578           return Op;
7579       }
7580   }
7581 
7582   if (SDValue V = ConstantBuildVector(Op, DAG))
7583     return V;
7584 
7585   // Scan through the operands to find some interesting properties we can
7586   // exploit:
7587   //   1) If only one value is used, we can use a DUP, or
7588   //   2) if only the low element is not undef, we can just insert that, or
7589   //   3) if only one constant value is used (w/ some non-constant lanes),
7590   //      we can splat the constant value into the whole vector then fill
7591   //      in the non-constant lanes.
7592   //   4) FIXME: If different constant values are used, but we can intelligently
7593   //             select the values we'll be overwriting for the non-constant
7594   //             lanes such that we can directly materialize the vector
7595   //             some other way (MOVI, e.g.), we can be sneaky.
7596   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7597   SDLoc dl(Op);
7598   unsigned NumElts = VT.getVectorNumElements();
7599   bool isOnlyLowElement = true;
7600   bool usesOnlyOneValue = true;
7601   bool usesOnlyOneConstantValue = true;
7602   bool isConstant = true;
7603   bool AllLanesExtractElt = true;
7604   unsigned NumConstantLanes = 0;
7605   SDValue Value;
7606   SDValue ConstantValue;
7607   for (unsigned i = 0; i < NumElts; ++i) {
7608     SDValue V = Op.getOperand(i);
7609     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7610       AllLanesExtractElt = false;
7611     if (V.isUndef())
7612       continue;
7613     if (i > 0)
7614       isOnlyLowElement = false;
7615     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7616       isConstant = false;
7617 
7618     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7619       ++NumConstantLanes;
7620       if (!ConstantValue.getNode())
7621         ConstantValue = V;
7622       else if (ConstantValue != V)
7623         usesOnlyOneConstantValue = false;
7624     }
7625 
7626     if (!Value.getNode())
7627       Value = V;
7628     else if (V != Value)
7629       usesOnlyOneValue = false;
7630   }
7631 
7632   if (!Value.getNode()) {
7633     LLVM_DEBUG(
7634         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7635     return DAG.getUNDEF(VT);
7636   }
7637 
7638   // Convert BUILD_VECTOR where all elements but the lowest are undef into
7639   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7640   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7641   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7642     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7643                          "SCALAR_TO_VECTOR node\n");
7644     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7645   }
7646 
7647   if (AllLanesExtractElt) {
7648     SDNode *Vector = nullptr;
7649     bool Even = false;
7650     bool Odd = false;
7651     // Check whether the extract elements match the Even pattern <0,2,4,...> or
7652     // the Odd pattern <1,3,5,...>.
7653     for (unsigned i = 0; i < NumElts; ++i) {
7654       SDValue V = Op.getOperand(i);
7655       const SDNode *N = V.getNode();
7656       if (!isa<ConstantSDNode>(N->getOperand(1)))
7657         break;
7658       SDValue N0 = N->getOperand(0);
7659 
7660       // All elements are extracted from the same vector.
7661       if (!Vector) {
7662         Vector = N0.getNode();
7663         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7664         // BUILD_VECTOR.
7665         if (VT.getVectorElementType() !=
7666             N0.getValueType().getVectorElementType())
7667           break;
7668       } else if (Vector != N0.getNode()) {
7669         Odd = false;
7670         Even = false;
7671         break;
7672       }
7673 
7674       // Extracted values are either at Even indices <0,2,4,...> or at Odd
7675       // indices <1,3,5,...>.
7676       uint64_t Val = N->getConstantOperandVal(1);
7677       if (Val == 2 * i) {
7678         Even = true;
7679         continue;
7680       }
7681       if (Val - 1 == 2 * i) {
7682         Odd = true;
7683         continue;
7684       }
7685 
7686       // Something does not match: abort.
7687       Odd = false;
7688       Even = false;
7689       break;
7690     }
7691     if (Even || Odd) {
7692       SDValue LHS =
7693           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7694                       DAG.getConstant(0, dl, MVT::i64));
7695       SDValue RHS =
7696           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7697                       DAG.getConstant(NumElts, dl, MVT::i64));
7698 
7699       if (Even && !Odd)
7700         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7701                            RHS);
7702       if (Odd && !Even)
7703         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7704                            RHS);
7705     }
7706   }
7707 
7708   // Use DUP for non-constant splats. For f32 constant splats, reduce to
7709   // i32 and try again.
7710   if (usesOnlyOneValue) {
7711     if (!isConstant) {
7712       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7713           Value.getValueType() != VT) {
7714         LLVM_DEBUG(
7715             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7716         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7717       }
7718 
7719       // This is actually a DUPLANExx operation, which keeps everything vectory.
7720 
7721       SDValue Lane = Value.getOperand(1);
7722       Value = Value.getOperand(0);
7723       if (Value.getValueSizeInBits() == 64) {
7724         LLVM_DEBUG(
7725             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7726                       "widening it\n");
7727         Value = WidenVector(Value, DAG);
7728       }
7729 
7730       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7731       return DAG.getNode(Opcode, dl, VT, Value, Lane);
7732     }
7733 
7734     if (VT.getVectorElementType().isFloatingPoint()) {
7735       SmallVector<SDValue, 8> Ops;
7736       EVT EltTy = VT.getVectorElementType();
7737       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7738               "Unsupported floating-point vector type");
7739       LLVM_DEBUG(
7740           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7741                     "BITCASTS, and try again\n");
7742       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7743       for (unsigned i = 0; i < NumElts; ++i)
7744         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7745       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7746       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7747       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7748                  Val.dump(););
7749       Val = LowerBUILD_VECTOR(Val, DAG);
7750       if (Val.getNode())
7751         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7752     }
7753   }
7754 
7755   // If there was only one constant value used and for more than one lane,
7756   // start by splatting that value, then replace the non-constant lanes. This
7757   // is better than the default, which will perform a separate initialization
7758   // for each lane.
7759   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7760     // Firstly, try to materialize the splat constant.
7761     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7762             Val = ConstantBuildVector(Vec, DAG);
7763     if (!Val) {
7764       // Otherwise, materialize the constant and splat it.
7765       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7766       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7767     }
7768 
7769     // Now insert the non-constant lanes.
7770     for (unsigned i = 0; i < NumElts; ++i) {
7771       SDValue V = Op.getOperand(i);
7772       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7773       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7774         // Note that type legalization likely mucked about with the VT of the
7775         // source operand, so we may have to convert it here before inserting.
7776         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7777     }
7778     return Val;
7779   }
7780 
7781   // This will generate a load from the constant pool.
7782   if (isConstant) {
7783     LLVM_DEBUG(
7784         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7785                   "expansion\n");
7786     return SDValue();
7787   }
7788 
7789   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7790   if (NumElts >= 4) {
7791     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7792       return shuffle;
7793   }
7794 
7795   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7796   // know the default expansion would otherwise fall back on something even
7797   // worse. For a vector with one or two non-undef values, that's
7798   // scalar_to_vector for the elements followed by a shuffle (provided the
7799   // shuffle is valid for the target) and materialization element by element
7800   // on the stack followed by a load for everything else.
7801   if (!isConstant && !usesOnlyOneValue) {
7802     LLVM_DEBUG(
7803         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7804                   "of INSERT_VECTOR_ELT\n");
7805 
7806     SDValue Vec = DAG.getUNDEF(VT);
7807     SDValue Op0 = Op.getOperand(0);
7808     unsigned i = 0;
7809 
7810     // Use SCALAR_TO_VECTOR for lane zero to
7811     // a) Avoid a RMW dependency on the full vector register, and
7812     // b) Allow the register coalescer to fold away the copy if the
7813     //    value is already in an S or D register, and we're forced to emit an
7814     //    INSERT_SUBREG that we can't fold anywhere.
7815     //
7816     // We also allow types like i8 and i16 which are illegal scalar but legal
7817     // vector element types. After type-legalization the inserted value is
7818     // extended (i32) and it is safe to cast them to the vector type by ignoring
7819     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7820     if (!Op0.isUndef()) {
7821       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7822       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7823       ++i;
7824     }
7825     LLVM_DEBUG(if (i < NumElts) dbgs()
7826                    << "Creating nodes for the other vector elements:\n";);
7827     for (; i < NumElts; ++i) {
7828       SDValue V = Op.getOperand(i);
7829       if (V.isUndef())
7830         continue;
7831       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7832       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7833     }
7834     return Vec;
7835   }
7836 
7837   LLVM_DEBUG(
7838       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7839                 "better alternative\n");
7840   return SDValue();
7841 }
7842 
7843 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7844                                                       SelectionDAG &DAG) const {
7845   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7846 
7847   // Check for non-constant or out of range lane.
7848   EVT VT = Op.getOperand(0).getValueType();
7849   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7850   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7851     return SDValue();
7852 
7853 
7854   // Insertion/extraction are legal for V128 types.
7855   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7856       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7857       VT == MVT::v8f16)
7858     return Op;
7859 
7860   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7861       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7862     return SDValue();
7863 
7864   // For V64 types, we perform insertion by expanding the value
7865   // to a V128 type and perform the insertion on that.
7866   SDLoc DL(Op);
7867   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7868   EVT WideTy = WideVec.getValueType();
7869 
7870   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7871                              Op.getOperand(1), Op.getOperand(2));
7872   // Re-narrow the resultant vector.
7873   return NarrowVector(Node, DAG);
7874 }
7875 
7876 SDValue
7877 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7878                                                SelectionDAG &DAG) const {
7879   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7880 
7881   // Check for non-constant or out of range lane.
7882   EVT VT = Op.getOperand(0).getValueType();
7883   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7884   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7885     return SDValue();
7886 
7887 
7888   // Insertion/extraction are legal for V128 types.
7889   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7890       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7891       VT == MVT::v8f16)
7892     return Op;
7893 
7894   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7895       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7896     return SDValue();
7897 
7898   // For V64 types, we perform extraction by expanding the value
7899   // to a V128 type and perform the extraction on that.
7900   SDLoc DL(Op);
7901   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7902   EVT WideTy = WideVec.getValueType();
7903 
7904   EVT ExtrTy = WideTy.getVectorElementType();
7905   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7906     ExtrTy = MVT::i32;
7907 
7908   // For extractions, we just return the result directly.
7909   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7910                      Op.getOperand(1));
7911 }
7912 
7913 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7914                                                       SelectionDAG &DAG) const {
7915   EVT VT = Op.getOperand(0).getValueType();
7916   SDLoc dl(Op);
7917   // Just in case...
7918   if (!VT.isVector())
7919     return SDValue();
7920 
7921   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7922   if (!Cst)
7923     return SDValue();
7924   unsigned Val = Cst->getZExtValue();
7925 
7926   unsigned Size = Op.getValueSizeInBits();
7927 
7928   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7929   if (Val == 0)
7930     return Op;
7931 
7932   // If this is extracting the upper 64-bits of a 128-bit vector, we match
7933   // that directly.
7934   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7935     return Op;
7936 
7937   return SDValue();
7938 }
7939 
7940 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7941   if (VT.getVectorNumElements() == 4 &&
7942       (VT.is128BitVector() || VT.is64BitVector())) {
7943     unsigned PFIndexes[4];
7944     for (unsigned i = 0; i != 4; ++i) {
7945       if (M[i] < 0)
7946         PFIndexes[i] = 8;
7947       else
7948         PFIndexes[i] = M[i];
7949     }
7950 
7951     // Compute the index in the perfect shuffle table.
7952     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7953                             PFIndexes[2] * 9 + PFIndexes[3];
7954     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7955     unsigned Cost = (PFEntry >> 30);
7956 
7957     if (Cost <= 4)
7958       return true;
7959   }
7960 
7961   bool DummyBool;
7962   int DummyInt;
7963   unsigned DummyUnsigned;
7964 
7965   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7966           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7967           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7968           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7969           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7970           isZIPMask(M, VT, DummyUnsigned) ||
7971           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7972           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7973           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7974           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7975           isConcatMask(M, VT, VT.getSizeInBits() == 128));
7976 }
7977 
7978 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7979 /// operand of a vector shift operation, where all the elements of the
7980 /// build_vector must have the same constant integer value.
7981 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7982   // Ignore bit_converts.
7983   while (Op.getOpcode() == ISD::BITCAST)
7984     Op = Op.getOperand(0);
7985   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7986   APInt SplatBits, SplatUndef;
7987   unsigned SplatBitSize;
7988   bool HasAnyUndefs;
7989   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7990                                     HasAnyUndefs, ElementBits) ||
7991       SplatBitSize > ElementBits)
7992     return false;
7993   Cnt = SplatBits.getSExtValue();
7994   return true;
7995 }
7996 
7997 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7998 /// operand of a vector shift left operation.  That value must be in the range:
7999 ///   0 <= Value < ElementBits for a left shift; or
8000 ///   0 <= Value <= ElementBits for a long left shift.
8001 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8002   assert(VT.isVector() && "vector shift count is not a vector type");
8003   int64_t ElementBits = VT.getScalarSizeInBits();
8004   if (!getVShiftImm(Op, ElementBits, Cnt))
8005     return false;
8006   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8007 }
8008 
8009 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8010 /// operand of a vector shift right operation. The value must be in the range:
8011 ///   1 <= Value <= ElementBits for a right shift; or
8012 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8013   assert(VT.isVector() && "vector shift count is not a vector type");
8014   int64_t ElementBits = VT.getScalarSizeInBits();
8015   if (!getVShiftImm(Op, ElementBits, Cnt))
8016     return false;
8017   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8018 }
8019 
8020 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8021                                                       SelectionDAG &DAG) const {
8022   EVT VT = Op.getValueType();
8023   SDLoc DL(Op);
8024   int64_t Cnt;
8025 
8026   if (!Op.getOperand(1).getValueType().isVector())
8027     return Op;
8028   unsigned EltSize = VT.getScalarSizeInBits();
8029 
8030   switch (Op.getOpcode()) {
8031   default:
8032     llvm_unreachable("unexpected shift opcode");
8033 
8034   case ISD::SHL:
8035     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8036       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8037                          DAG.getConstant(Cnt, DL, MVT::i32));
8038     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8039                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8040                                        MVT::i32),
8041                        Op.getOperand(0), Op.getOperand(1));
8042   case ISD::SRA:
8043   case ISD::SRL:
8044     // Right shift immediate
8045     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8046       unsigned Opc =
8047           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8048       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8049                          DAG.getConstant(Cnt, DL, MVT::i32));
8050     }
8051 
8052     // Right shift register.  Note, there is not a shift right register
8053     // instruction, but the shift left register instruction takes a signed
8054     // value, where negative numbers specify a right shift.
8055     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8056                                                 : Intrinsic::aarch64_neon_ushl;
8057     // negate the shift amount
8058     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8059     SDValue NegShiftLeft =
8060         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8061                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8062                     NegShift);
8063     return NegShiftLeft;
8064   }
8065 
8066   return SDValue();
8067 }
8068 
8069 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8070                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
8071                                     const SDLoc &dl, SelectionDAG &DAG) {
8072   EVT SrcVT = LHS.getValueType();
8073   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8074          "function only supposed to emit natural comparisons");
8075 
8076   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8077   APInt CnstBits(VT.getSizeInBits(), 0);
8078   APInt UndefBits(VT.getSizeInBits(), 0);
8079   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8080   bool IsZero = IsCnst && (CnstBits == 0);
8081 
8082   if (SrcVT.getVectorElementType().isFloatingPoint()) {
8083     switch (CC) {
8084     default:
8085       return SDValue();
8086     case AArch64CC::NE: {
8087       SDValue Fcmeq;
8088       if (IsZero)
8089         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8090       else
8091         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8092       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8093     }
8094     case AArch64CC::EQ:
8095       if (IsZero)
8096         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8097       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8098     case AArch64CC::GE:
8099       if (IsZero)
8100         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8101       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8102     case AArch64CC::GT:
8103       if (IsZero)
8104         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8105       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8106     case AArch64CC::LS:
8107       if (IsZero)
8108         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8109       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8110     case AArch64CC::LT:
8111       if (!NoNans)
8112         return SDValue();
8113       // If we ignore NaNs then we can use to the MI implementation.
8114       LLVM_FALLTHROUGH;
8115     case AArch64CC::MI:
8116       if (IsZero)
8117         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8118       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8119     }
8120   }
8121 
8122   switch (CC) {
8123   default:
8124     return SDValue();
8125   case AArch64CC::NE: {
8126     SDValue Cmeq;
8127     if (IsZero)
8128       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8129     else
8130       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8131     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8132   }
8133   case AArch64CC::EQ:
8134     if (IsZero)
8135       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8136     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8137   case AArch64CC::GE:
8138     if (IsZero)
8139       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8140     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8141   case AArch64CC::GT:
8142     if (IsZero)
8143       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8144     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8145   case AArch64CC::LE:
8146     if (IsZero)
8147       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8148     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8149   case AArch64CC::LS:
8150     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8151   case AArch64CC::LO:
8152     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8153   case AArch64CC::LT:
8154     if (IsZero)
8155       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8156     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8157   case AArch64CC::HI:
8158     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8159   case AArch64CC::HS:
8160     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8161   }
8162 }
8163 
8164 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8165                                            SelectionDAG &DAG) const {
8166   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8167   SDValue LHS = Op.getOperand(0);
8168   SDValue RHS = Op.getOperand(1);
8169   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8170   SDLoc dl(Op);
8171 
8172   if (LHS.getValueType().getVectorElementType().isInteger()) {
8173     assert(LHS.getValueType() == RHS.getValueType());
8174     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8175     SDValue Cmp =
8176         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8177     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8178   }
8179 
8180   const bool FullFP16 =
8181     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8182 
8183   // Make v4f16 (only) fcmp operations utilise vector instructions
8184   // v8f16 support will be a litle more complicated
8185   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8186     if (LHS.getValueType().getVectorNumElements() == 4) {
8187       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8188       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8189       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8190       DAG.ReplaceAllUsesWith(Op, NewSetcc);
8191       CmpVT = MVT::v4i32;
8192     } else
8193       return SDValue();
8194   }
8195 
8196   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8197           LHS.getValueType().getVectorElementType() != MVT::f128);
8198 
8199   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8200   // clean.  Some of them require two branches to implement.
8201   AArch64CC::CondCode CC1, CC2;
8202   bool ShouldInvert;
8203   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8204 
8205   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8206   SDValue Cmp =
8207       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8208   if (!Cmp.getNode())
8209     return SDValue();
8210 
8211   if (CC2 != AArch64CC::AL) {
8212     SDValue Cmp2 =
8213         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8214     if (!Cmp2.getNode())
8215       return SDValue();
8216 
8217     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8218   }
8219 
8220   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8221 
8222   if (ShouldInvert)
8223     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8224 
8225   return Cmp;
8226 }
8227 
8228 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8229                                   SelectionDAG &DAG) {
8230   SDValue VecOp = ScalarOp.getOperand(0);
8231   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8232   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8233                      DAG.getConstant(0, DL, MVT::i64));
8234 }
8235 
8236 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8237                                               SelectionDAG &DAG) const {
8238   SDLoc dl(Op);
8239   switch (Op.getOpcode()) {
8240   case ISD::VECREDUCE_ADD:
8241     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8242   case ISD::VECREDUCE_SMAX:
8243     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8244   case ISD::VECREDUCE_SMIN:
8245     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8246   case ISD::VECREDUCE_UMAX:
8247     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8248   case ISD::VECREDUCE_UMIN:
8249     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8250   case ISD::VECREDUCE_FMAX: {
8251     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8252     return DAG.getNode(
8253         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8254         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8255         Op.getOperand(0));
8256   }
8257   case ISD::VECREDUCE_FMIN: {
8258     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8259     return DAG.getNode(
8260         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8261         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8262         Op.getOperand(0));
8263   }
8264   default:
8265     llvm_unreachable("Unhandled reduction");
8266   }
8267 }
8268 
8269 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8270                                                     SelectionDAG &DAG) const {
8271   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8272   if (!Subtarget.hasLSE())
8273     return SDValue();
8274 
8275   // LSE has an atomic load-add instruction, but not a load-sub.
8276   SDLoc dl(Op);
8277   MVT VT = Op.getSimpleValueType();
8278   SDValue RHS = Op.getOperand(2);
8279   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8280   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8281   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8282                        Op.getOperand(0), Op.getOperand(1), RHS,
8283                        AN->getMemOperand());
8284 }
8285 
8286 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8287                                                     SelectionDAG &DAG) const {
8288   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8289   if (!Subtarget.hasLSE())
8290     return SDValue();
8291 
8292   // LSE has an atomic load-clear instruction, but not a load-and.
8293   SDLoc dl(Op);
8294   MVT VT = Op.getSimpleValueType();
8295   SDValue RHS = Op.getOperand(2);
8296   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8297   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8298   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8299                        Op.getOperand(0), Op.getOperand(1), RHS,
8300                        AN->getMemOperand());
8301 }
8302 
8303 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8304     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8305   SDLoc dl(Op);
8306   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8307   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8308 
8309   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8310   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8311   if (Subtarget->hasCustomCallingConv())
8312     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8313 
8314   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8315                      DAG.getConstant(4, dl, MVT::i64));
8316   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8317   Chain =
8318       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8319                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8320                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8321   // To match the actual intent better, we should read the output from X15 here
8322   // again (instead of potentially spilling it to the stack), but rereading Size
8323   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8324   // here.
8325 
8326   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8327                      DAG.getConstant(4, dl, MVT::i64));
8328   return Chain;
8329 }
8330 
8331 SDValue
8332 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8333                                                SelectionDAG &DAG) const {
8334   assert(Subtarget->isTargetWindows() &&
8335          "Only Windows alloca probing supported");
8336   SDLoc dl(Op);
8337   // Get the inputs.
8338   SDNode *Node = Op.getNode();
8339   SDValue Chain = Op.getOperand(0);
8340   SDValue Size = Op.getOperand(1);
8341   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8342   EVT VT = Node->getValueType(0);
8343 
8344   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8345           "no-stack-arg-probe")) {
8346     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8347     Chain = SP.getValue(1);
8348     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8349     if (Align)
8350       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8351                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8352     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8353     SDValue Ops[2] = {SP, Chain};
8354     return DAG.getMergeValues(Ops, dl);
8355   }
8356 
8357   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8358 
8359   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8360 
8361   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8362   Chain = SP.getValue(1);
8363   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8364   if (Align)
8365     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8366                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8367   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8368 
8369   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8370                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8371 
8372   SDValue Ops[2] = {SP, Chain};
8373   return DAG.getMergeValues(Ops, dl);
8374 }
8375 
8376 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8377 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8378 /// specified in the intrinsic calls.
8379 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8380                                                const CallInst &I,
8381                                                MachineFunction &MF,
8382                                                unsigned Intrinsic) const {
8383   auto &DL = I.getModule()->getDataLayout();
8384   switch (Intrinsic) {
8385   case Intrinsic::aarch64_neon_ld2:
8386   case Intrinsic::aarch64_neon_ld3:
8387   case Intrinsic::aarch64_neon_ld4:
8388   case Intrinsic::aarch64_neon_ld1x2:
8389   case Intrinsic::aarch64_neon_ld1x3:
8390   case Intrinsic::aarch64_neon_ld1x4:
8391   case Intrinsic::aarch64_neon_ld2lane:
8392   case Intrinsic::aarch64_neon_ld3lane:
8393   case Intrinsic::aarch64_neon_ld4lane:
8394   case Intrinsic::aarch64_neon_ld2r:
8395   case Intrinsic::aarch64_neon_ld3r:
8396   case Intrinsic::aarch64_neon_ld4r: {
8397     Info.opc = ISD::INTRINSIC_W_CHAIN;
8398     // Conservatively set memVT to the entire set of vectors loaded.
8399     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8400     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8401     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8402     Info.offset = 0;
8403     Info.align.reset();
8404     // volatile loads with NEON intrinsics not supported
8405     Info.flags = MachineMemOperand::MOLoad;
8406     return true;
8407   }
8408   case Intrinsic::aarch64_neon_st2:
8409   case Intrinsic::aarch64_neon_st3:
8410   case Intrinsic::aarch64_neon_st4:
8411   case Intrinsic::aarch64_neon_st1x2:
8412   case Intrinsic::aarch64_neon_st1x3:
8413   case Intrinsic::aarch64_neon_st1x4:
8414   case Intrinsic::aarch64_neon_st2lane:
8415   case Intrinsic::aarch64_neon_st3lane:
8416   case Intrinsic::aarch64_neon_st4lane: {
8417     Info.opc = ISD::INTRINSIC_VOID;
8418     // Conservatively set memVT to the entire set of vectors stored.
8419     unsigned NumElts = 0;
8420     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8421       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8422       if (!ArgTy->isVectorTy())
8423         break;
8424       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8425     }
8426     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8427     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8428     Info.offset = 0;
8429     Info.align.reset();
8430     // volatile stores with NEON intrinsics not supported
8431     Info.flags = MachineMemOperand::MOStore;
8432     return true;
8433   }
8434   case Intrinsic::aarch64_ldaxr:
8435   case Intrinsic::aarch64_ldxr: {
8436     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8437     Info.opc = ISD::INTRINSIC_W_CHAIN;
8438     Info.memVT = MVT::getVT(PtrTy->getElementType());
8439     Info.ptrVal = I.getArgOperand(0);
8440     Info.offset = 0;
8441     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8442     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8443     return true;
8444   }
8445   case Intrinsic::aarch64_stlxr:
8446   case Intrinsic::aarch64_stxr: {
8447     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8448     Info.opc = ISD::INTRINSIC_W_CHAIN;
8449     Info.memVT = MVT::getVT(PtrTy->getElementType());
8450     Info.ptrVal = I.getArgOperand(1);
8451     Info.offset = 0;
8452     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8453     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8454     return true;
8455   }
8456   case Intrinsic::aarch64_ldaxp:
8457   case Intrinsic::aarch64_ldxp:
8458     Info.opc = ISD::INTRINSIC_W_CHAIN;
8459     Info.memVT = MVT::i128;
8460     Info.ptrVal = I.getArgOperand(0);
8461     Info.offset = 0;
8462     Info.align = Align(16);
8463     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8464     return true;
8465   case Intrinsic::aarch64_stlxp:
8466   case Intrinsic::aarch64_stxp:
8467     Info.opc = ISD::INTRINSIC_W_CHAIN;
8468     Info.memVT = MVT::i128;
8469     Info.ptrVal = I.getArgOperand(2);
8470     Info.offset = 0;
8471     Info.align = Align(16);
8472     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8473     return true;
8474   default:
8475     break;
8476   }
8477 
8478   return false;
8479 }
8480 
8481 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8482                                                   ISD::LoadExtType ExtTy,
8483                                                   EVT NewVT) const {
8484   // TODO: This may be worth removing. Check regression tests for diffs.
8485   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8486     return false;
8487 
8488   // If we're reducing the load width in order to avoid having to use an extra
8489   // instruction to do extension then it's probably a good idea.
8490   if (ExtTy != ISD::NON_EXTLOAD)
8491     return true;
8492   // Don't reduce load width if it would prevent us from combining a shift into
8493   // the offset.
8494   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8495   assert(Mem);
8496   const SDValue &Base = Mem->getBasePtr();
8497   if (Base.getOpcode() == ISD::ADD &&
8498       Base.getOperand(1).getOpcode() == ISD::SHL &&
8499       Base.getOperand(1).hasOneUse() &&
8500       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8501     // The shift can be combined if it matches the size of the value being
8502     // loaded (and so reducing the width would make it not match).
8503     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8504     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8505     if (ShiftAmount == Log2_32(LoadBytes))
8506       return false;
8507   }
8508   // We have no reason to disallow reducing the load width, so allow it.
8509   return true;
8510 }
8511 
8512 // Truncations from 64-bit GPR to 32-bit GPR is free.
8513 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8514   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8515     return false;
8516   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8517   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8518   return NumBits1 > NumBits2;
8519 }
8520 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8521   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8522     return false;
8523   unsigned NumBits1 = VT1.getSizeInBits();
8524   unsigned NumBits2 = VT2.getSizeInBits();
8525   return NumBits1 > NumBits2;
8526 }
8527 
8528 /// Check if it is profitable to hoist instruction in then/else to if.
8529 /// Not profitable if I and it's user can form a FMA instruction
8530 /// because we prefer FMSUB/FMADD.
8531 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8532   if (I->getOpcode() != Instruction::FMul)
8533     return true;
8534 
8535   if (!I->hasOneUse())
8536     return true;
8537 
8538   Instruction *User = I->user_back();
8539 
8540   if (User &&
8541       !(User->getOpcode() == Instruction::FSub ||
8542         User->getOpcode() == Instruction::FAdd))
8543     return true;
8544 
8545   const TargetOptions &Options = getTargetMachine().Options;
8546   const DataLayout &DL = I->getModule()->getDataLayout();
8547   EVT VT = getValueType(DL, User->getOperand(0)->getType());
8548 
8549   return !(isFMAFasterThanFMulAndFAdd(VT) &&
8550            isOperationLegalOrCustom(ISD::FMA, VT) &&
8551            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8552             Options.UnsafeFPMath));
8553 }
8554 
8555 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8556 // 64-bit GPR.
8557 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8558   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8559     return false;
8560   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8561   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8562   return NumBits1 == 32 && NumBits2 == 64;
8563 }
8564 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8565   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8566     return false;
8567   unsigned NumBits1 = VT1.getSizeInBits();
8568   unsigned NumBits2 = VT2.getSizeInBits();
8569   return NumBits1 == 32 && NumBits2 == 64;
8570 }
8571 
8572 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8573   EVT VT1 = Val.getValueType();
8574   if (isZExtFree(VT1, VT2)) {
8575     return true;
8576   }
8577 
8578   if (Val.getOpcode() != ISD::LOAD)
8579     return false;
8580 
8581   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8582   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8583           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8584           VT1.getSizeInBits() <= 32);
8585 }
8586 
8587 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8588   if (isa<FPExtInst>(Ext))
8589     return false;
8590 
8591   // Vector types are not free.
8592   if (Ext->getType()->isVectorTy())
8593     return false;
8594 
8595   for (const Use &U : Ext->uses()) {
8596     // The extension is free if we can fold it with a left shift in an
8597     // addressing mode or an arithmetic operation: add, sub, and cmp.
8598 
8599     // Is there a shift?
8600     const Instruction *Instr = cast<Instruction>(U.getUser());
8601 
8602     // Is this a constant shift?
8603     switch (Instr->getOpcode()) {
8604     case Instruction::Shl:
8605       if (!isa<ConstantInt>(Instr->getOperand(1)))
8606         return false;
8607       break;
8608     case Instruction::GetElementPtr: {
8609       gep_type_iterator GTI = gep_type_begin(Instr);
8610       auto &DL = Ext->getModule()->getDataLayout();
8611       std::advance(GTI, U.getOperandNo()-1);
8612       Type *IdxTy = GTI.getIndexedType();
8613       // This extension will end up with a shift because of the scaling factor.
8614       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8615       // Get the shift amount based on the scaling factor:
8616       // log2(sizeof(IdxTy)) - log2(8).
8617       uint64_t ShiftAmt =
8618         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
8619       // Is the constant foldable in the shift of the addressing mode?
8620       // I.e., shift amount is between 1 and 4 inclusive.
8621       if (ShiftAmt == 0 || ShiftAmt > 4)
8622         return false;
8623       break;
8624     }
8625     case Instruction::Trunc:
8626       // Check if this is a noop.
8627       // trunc(sext ty1 to ty2) to ty1.
8628       if (Instr->getType() == Ext->getOperand(0)->getType())
8629         continue;
8630       LLVM_FALLTHROUGH;
8631     default:
8632       return false;
8633     }
8634 
8635     // At this point we can use the bfm family, so this extension is free
8636     // for that use.
8637   }
8638   return true;
8639 }
8640 
8641 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8642 /// or upper half of the vector elements.
8643 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8644   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8645     auto *FullVT = cast<VectorType>(FullV->getType());
8646     auto *HalfVT = cast<VectorType>(HalfV->getType());
8647     return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8648   };
8649 
8650   auto extractHalf = [](Value *FullV, Value *HalfV) {
8651     auto *FullVT = cast<VectorType>(FullV->getType());
8652     auto *HalfVT = cast<VectorType>(HalfV->getType());
8653     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8654   };
8655 
8656   Constant *M1, *M2;
8657   Value *S1Op1, *S2Op1;
8658   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8659       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8660     return false;
8661 
8662   // Check that the operands are half as wide as the result and we extract
8663   // half of the elements of the input vectors.
8664   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8665       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8666     return false;
8667 
8668   // Check the mask extracts either the lower or upper half of vector
8669   // elements.
8670   int M1Start = -1;
8671   int M2Start = -1;
8672   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8673   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8674       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8675       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8676     return false;
8677 
8678   return true;
8679 }
8680 
8681 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8682 /// of the vector elements.
8683 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8684   auto areExtDoubled = [](Instruction *Ext) {
8685     return Ext->getType()->getScalarSizeInBits() ==
8686            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8687   };
8688 
8689   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8690       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8691       !areExtDoubled(cast<Instruction>(Ext1)) ||
8692       !areExtDoubled(cast<Instruction>(Ext2)))
8693     return false;
8694 
8695   return true;
8696 }
8697 
8698 /// Check if sinking \p I's operands to I's basic block is profitable, because
8699 /// the operands can be folded into a target instruction, e.g.
8700 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8701 bool AArch64TargetLowering::shouldSinkOperands(
8702     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8703   if (!I->getType()->isVectorTy())
8704     return false;
8705 
8706   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8707     switch (II->getIntrinsicID()) {
8708     case Intrinsic::aarch64_neon_umull:
8709       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8710         return false;
8711       Ops.push_back(&II->getOperandUse(0));
8712       Ops.push_back(&II->getOperandUse(1));
8713       return true;
8714     default:
8715       return false;
8716     }
8717   }
8718 
8719   switch (I->getOpcode()) {
8720   case Instruction::Sub:
8721   case Instruction::Add: {
8722     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8723       return false;
8724 
8725     // If the exts' operands extract either the lower or upper elements, we
8726     // can sink them too.
8727     auto Ext1 = cast<Instruction>(I->getOperand(0));
8728     auto Ext2 = cast<Instruction>(I->getOperand(1));
8729     if (areExtractShuffleVectors(Ext1, Ext2)) {
8730       Ops.push_back(&Ext1->getOperandUse(0));
8731       Ops.push_back(&Ext2->getOperandUse(0));
8732     }
8733 
8734     Ops.push_back(&I->getOperandUse(0));
8735     Ops.push_back(&I->getOperandUse(1));
8736 
8737     return true;
8738   }
8739   default:
8740     return false;
8741   }
8742   return false;
8743 }
8744 
8745 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8746                                           unsigned &RequiredAligment) const {
8747   if (!LoadedType.isSimple() ||
8748       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8749     return false;
8750   // Cyclone supports unaligned accesses.
8751   RequiredAligment = 0;
8752   unsigned NumBits = LoadedType.getSizeInBits();
8753   return NumBits == 32 || NumBits == 64;
8754 }
8755 
8756 /// A helper function for determining the number of interleaved accesses we
8757 /// will generate when lowering accesses of the given type.
8758 unsigned
8759 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8760                                                  const DataLayout &DL) const {
8761   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8762 }
8763 
8764 MachineMemOperand::Flags
8765 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8766   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8767       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8768     return MOStridedAccess;
8769   return MachineMemOperand::MONone;
8770 }
8771 
8772 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8773     VectorType *VecTy, const DataLayout &DL) const {
8774 
8775   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8776   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8777 
8778   // Ensure the number of vector elements is greater than 1.
8779   if (VecTy->getNumElements() < 2)
8780     return false;
8781 
8782   // Ensure the element type is legal.
8783   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8784     return false;
8785 
8786   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8787   // 128 will be split into multiple interleaved accesses.
8788   return VecSize == 64 || VecSize % 128 == 0;
8789 }
8790 
8791 /// Lower an interleaved load into a ldN intrinsic.
8792 ///
8793 /// E.g. Lower an interleaved load (Factor = 2):
8794 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8795 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
8796 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
8797 ///
8798 ///      Into:
8799 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8800 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8801 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8802 bool AArch64TargetLowering::lowerInterleavedLoad(
8803     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8804     ArrayRef<unsigned> Indices, unsigned Factor) const {
8805   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8806          "Invalid interleave factor");
8807   assert(!Shuffles.empty() && "Empty shufflevector input");
8808   assert(Shuffles.size() == Indices.size() &&
8809          "Unmatched number of shufflevectors and indices");
8810 
8811   const DataLayout &DL = LI->getModule()->getDataLayout();
8812 
8813   VectorType *VecTy = Shuffles[0]->getType();
8814 
8815   // Skip if we do not have NEON and skip illegal vector types. We can
8816   // "legalize" wide vector types into multiple interleaved accesses as long as
8817   // the vector types are divisible by 128.
8818   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8819     return false;
8820 
8821   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8822 
8823   // A pointer vector can not be the return type of the ldN intrinsics. Need to
8824   // load integer vectors first and then convert to pointer vectors.
8825   Type *EltTy = VecTy->getVectorElementType();
8826   if (EltTy->isPointerTy())
8827     VecTy =
8828         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8829 
8830   IRBuilder<> Builder(LI);
8831 
8832   // The base address of the load.
8833   Value *BaseAddr = LI->getPointerOperand();
8834 
8835   if (NumLoads > 1) {
8836     // If we're going to generate more than one load, reset the sub-vector type
8837     // to something legal.
8838     VecTy = VectorType::get(VecTy->getVectorElementType(),
8839                             VecTy->getVectorNumElements() / NumLoads);
8840 
8841     // We will compute the pointer operand of each load from the original base
8842     // address using GEPs. Cast the base address to a pointer to the scalar
8843     // element type.
8844     BaseAddr = Builder.CreateBitCast(
8845         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8846                       LI->getPointerAddressSpace()));
8847   }
8848 
8849   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8850   Type *Tys[2] = {VecTy, PtrTy};
8851   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8852                                             Intrinsic::aarch64_neon_ld3,
8853                                             Intrinsic::aarch64_neon_ld4};
8854   Function *LdNFunc =
8855       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8856 
8857   // Holds sub-vectors extracted from the load intrinsic return values. The
8858   // sub-vectors are associated with the shufflevector instructions they will
8859   // replace.
8860   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8861 
8862   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8863 
8864     // If we're generating more than one load, compute the base address of
8865     // subsequent loads as an offset from the previous.
8866     if (LoadCount > 0)
8867       BaseAddr =
8868           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8869                                      VecTy->getVectorNumElements() * Factor);
8870 
8871     CallInst *LdN = Builder.CreateCall(
8872         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8873 
8874     // Extract and store the sub-vectors returned by the load intrinsic.
8875     for (unsigned i = 0; i < Shuffles.size(); i++) {
8876       ShuffleVectorInst *SVI = Shuffles[i];
8877       unsigned Index = Indices[i];
8878 
8879       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8880 
8881       // Convert the integer vector to pointer vector if the element is pointer.
8882       if (EltTy->isPointerTy())
8883         SubVec = Builder.CreateIntToPtr(
8884             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8885                                     VecTy->getVectorNumElements()));
8886       SubVecs[SVI].push_back(SubVec);
8887     }
8888   }
8889 
8890   // Replace uses of the shufflevector instructions with the sub-vectors
8891   // returned by the load intrinsic. If a shufflevector instruction is
8892   // associated with more than one sub-vector, those sub-vectors will be
8893   // concatenated into a single wide vector.
8894   for (ShuffleVectorInst *SVI : Shuffles) {
8895     auto &SubVec = SubVecs[SVI];
8896     auto *WideVec =
8897         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8898     SVI->replaceAllUsesWith(WideVec);
8899   }
8900 
8901   return true;
8902 }
8903 
8904 /// Lower an interleaved store into a stN intrinsic.
8905 ///
8906 /// E.g. Lower an interleaved store (Factor = 3):
8907 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8908 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8909 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8910 ///
8911 ///      Into:
8912 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8913 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8914 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8915 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8916 ///
8917 /// Note that the new shufflevectors will be removed and we'll only generate one
8918 /// st3 instruction in CodeGen.
8919 ///
8920 /// Example for a more general valid mask (Factor 3). Lower:
8921 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8922 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8923 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8924 ///
8925 ///      Into:
8926 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8927 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8928 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8929 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8930 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8931                                                   ShuffleVectorInst *SVI,
8932                                                   unsigned Factor) const {
8933   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8934          "Invalid interleave factor");
8935 
8936   VectorType *VecTy = SVI->getType();
8937   assert(VecTy->getVectorNumElements() % Factor == 0 &&
8938          "Invalid interleaved store");
8939 
8940   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8941   Type *EltTy = VecTy->getVectorElementType();
8942   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8943 
8944   const DataLayout &DL = SI->getModule()->getDataLayout();
8945 
8946   // Skip if we do not have NEON and skip illegal vector types. We can
8947   // "legalize" wide vector types into multiple interleaved accesses as long as
8948   // the vector types are divisible by 128.
8949   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8950     return false;
8951 
8952   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8953 
8954   Value *Op0 = SVI->getOperand(0);
8955   Value *Op1 = SVI->getOperand(1);
8956   IRBuilder<> Builder(SI);
8957 
8958   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8959   // vectors to integer vectors.
8960   if (EltTy->isPointerTy()) {
8961     Type *IntTy = DL.getIntPtrType(EltTy);
8962     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8963 
8964     // Convert to the corresponding integer vector.
8965     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8966     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8967     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8968 
8969     SubVecTy = VectorType::get(IntTy, LaneLen);
8970   }
8971 
8972   // The base address of the store.
8973   Value *BaseAddr = SI->getPointerOperand();
8974 
8975   if (NumStores > 1) {
8976     // If we're going to generate more than one store, reset the lane length
8977     // and sub-vector type to something legal.
8978     LaneLen /= NumStores;
8979     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8980 
8981     // We will compute the pointer operand of each store from the original base
8982     // address using GEPs. Cast the base address to a pointer to the scalar
8983     // element type.
8984     BaseAddr = Builder.CreateBitCast(
8985         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8986                       SI->getPointerAddressSpace()));
8987   }
8988 
8989   auto Mask = SVI->getShuffleMask();
8990 
8991   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8992   Type *Tys[2] = {SubVecTy, PtrTy};
8993   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8994                                              Intrinsic::aarch64_neon_st3,
8995                                              Intrinsic::aarch64_neon_st4};
8996   Function *StNFunc =
8997       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8998 
8999   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9000 
9001     SmallVector<Value *, 5> Ops;
9002 
9003     // Split the shufflevector operands into sub vectors for the new stN call.
9004     for (unsigned i = 0; i < Factor; i++) {
9005       unsigned IdxI = StoreCount * LaneLen * Factor + i;
9006       if (Mask[IdxI] >= 0) {
9007         Ops.push_back(Builder.CreateShuffleVector(
9008             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9009       } else {
9010         unsigned StartMask = 0;
9011         for (unsigned j = 1; j < LaneLen; j++) {
9012           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9013           if (Mask[IdxJ * Factor + IdxI] >= 0) {
9014             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9015             break;
9016           }
9017         }
9018         // Note: Filling undef gaps with random elements is ok, since
9019         // those elements were being written anyway (with undefs).
9020         // In the case of all undefs we're defaulting to using elems from 0
9021         // Note: StartMask cannot be negative, it's checked in
9022         // isReInterleaveMask
9023         Ops.push_back(Builder.CreateShuffleVector(
9024             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9025       }
9026     }
9027 
9028     // If we generating more than one store, we compute the base address of
9029     // subsequent stores as an offset from the previous.
9030     if (StoreCount > 0)
9031       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
9032                                             BaseAddr, LaneLen * Factor);
9033 
9034     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9035     Builder.CreateCall(StNFunc, Ops);
9036   }
9037   return true;
9038 }
9039 
9040 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9041                        unsigned AlignCheck) {
9042   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9043           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9044 }
9045 
9046 EVT AArch64TargetLowering::getOptimalMemOpType(
9047     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9048     bool ZeroMemset, bool MemcpyStrSrc,
9049     const AttributeList &FuncAttributes) const {
9050   bool CanImplicitFloat =
9051       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9052   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9053   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9054   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9055   // taken one instruction to materialize the v2i64 zero and one store (with
9056   // restrictive addressing mode). Just do i64 stores.
9057   bool IsSmallMemset = IsMemset && Size < 32;
9058   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9059     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9060       return true;
9061     bool Fast;
9062     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9063                                           &Fast) &&
9064            Fast;
9065   };
9066 
9067   if (CanUseNEON && IsMemset && !IsSmallMemset &&
9068       AlignmentIsAcceptable(MVT::v2i64, 16))
9069     return MVT::v2i64;
9070   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9071     return MVT::f128;
9072   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9073     return MVT::i64;
9074   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9075     return MVT::i32;
9076   return MVT::Other;
9077 }
9078 
9079 LLT AArch64TargetLowering::getOptimalMemOpLLT(
9080     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9081     bool ZeroMemset, bool MemcpyStrSrc,
9082     const AttributeList &FuncAttributes) const {
9083   bool CanImplicitFloat =
9084       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9085   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9086   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9087   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9088   // taken one instruction to materialize the v2i64 zero and one store (with
9089   // restrictive addressing mode). Just do i64 stores.
9090   bool IsSmallMemset = IsMemset && Size < 32;
9091   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9092     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9093       return true;
9094     bool Fast;
9095     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9096                                           &Fast) &&
9097            Fast;
9098   };
9099 
9100   if (CanUseNEON && IsMemset && !IsSmallMemset &&
9101       AlignmentIsAcceptable(MVT::v2i64, 16))
9102     return LLT::vector(2, 64);
9103   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9104     return LLT::scalar(128);
9105   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9106     return LLT::scalar(64);
9107   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9108     return LLT::scalar(32);
9109   return LLT();
9110 }
9111 
9112 // 12-bit optionally shifted immediates are legal for adds.
9113 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9114   if (Immed == std::numeric_limits<int64_t>::min()) {
9115     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9116                       << ": avoid UB for INT64_MIN\n");
9117     return false;
9118   }
9119   // Same encoding for add/sub, just flip the sign.
9120   Immed = std::abs(Immed);
9121   bool IsLegal = ((Immed >> 12) == 0 ||
9122                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9123   LLVM_DEBUG(dbgs() << "Is " << Immed
9124                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9125   return IsLegal;
9126 }
9127 
9128 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9129 // immediates is the same as for an add or a sub.
9130 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9131   return isLegalAddImmediate(Immed);
9132 }
9133 
9134 /// isLegalAddressingMode - Return true if the addressing mode represented
9135 /// by AM is legal for this target, for a load/store of the specified type.
9136 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9137                                                   const AddrMode &AM, Type *Ty,
9138                                                   unsigned AS, Instruction *I) const {
9139   // AArch64 has five basic addressing modes:
9140   //  reg
9141   //  reg + 9-bit signed offset
9142   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
9143   //  reg1 + reg2
9144   //  reg + SIZE_IN_BYTES * reg
9145 
9146   // No global is ever allowed as a base.
9147   if (AM.BaseGV)
9148     return false;
9149 
9150   // No reg+reg+imm addressing.
9151   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9152     return false;
9153 
9154   // check reg + imm case:
9155   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9156   uint64_t NumBytes = 0;
9157   if (Ty->isSized()) {
9158     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9159     NumBytes = NumBits / 8;
9160     if (!isPowerOf2_64(NumBits))
9161       NumBytes = 0;
9162   }
9163 
9164   if (!AM.Scale) {
9165     int64_t Offset = AM.BaseOffs;
9166 
9167     // 9-bit signed offset
9168     if (isInt<9>(Offset))
9169       return true;
9170 
9171     // 12-bit unsigned offset
9172     unsigned shift = Log2_64(NumBytes);
9173     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9174         // Must be a multiple of NumBytes (NumBytes is a power of 2)
9175         (Offset >> shift) << shift == Offset)
9176       return true;
9177     return false;
9178   }
9179 
9180   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9181 
9182   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9183 }
9184 
9185 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9186   // Consider splitting large offset of struct or array.
9187   return true;
9188 }
9189 
9190 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9191                                                 const AddrMode &AM, Type *Ty,
9192                                                 unsigned AS) const {
9193   // Scaling factors are not free at all.
9194   // Operands                     | Rt Latency
9195   // -------------------------------------------
9196   // Rt, [Xn, Xm]                 | 4
9197   // -------------------------------------------
9198   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
9199   // Rt, [Xn, Wm, <extend> #imm]  |
9200   if (isLegalAddressingMode(DL, AM, Ty, AS))
9201     // Scale represents reg2 * scale, thus account for 1 if
9202     // it is not equal to 0 or 1.
9203     return AM.Scale != 0 && AM.Scale != 1;
9204   return -1;
9205 }
9206 
9207 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9208   VT = VT.getScalarType();
9209 
9210   if (!VT.isSimple())
9211     return false;
9212 
9213   switch (VT.getSimpleVT().SimpleTy) {
9214   case MVT::f32:
9215   case MVT::f64:
9216     return true;
9217   default:
9218     break;
9219   }
9220 
9221   return false;
9222 }
9223 
9224 const MCPhysReg *
9225 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9226   // LR is a callee-save register, but we must treat it as clobbered by any call
9227   // site. Hence we include LR in the scratch registers, which are in turn added
9228   // as implicit-defs for stackmaps and patchpoints.
9229   static const MCPhysReg ScratchRegs[] = {
9230     AArch64::X16, AArch64::X17, AArch64::LR, 0
9231   };
9232   return ScratchRegs;
9233 }
9234 
9235 bool
9236 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9237                                                      CombineLevel Level) const {
9238   N = N->getOperand(0).getNode();
9239   EVT VT = N->getValueType(0);
9240     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9241     // it with shift to let it be lowered to UBFX.
9242   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9243       isa<ConstantSDNode>(N->getOperand(1))) {
9244     uint64_t TruncMask = N->getConstantOperandVal(1);
9245     if (isMask_64(TruncMask) &&
9246       N->getOperand(0).getOpcode() == ISD::SRL &&
9247       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9248       return false;
9249   }
9250   return true;
9251 }
9252 
9253 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9254                                                               Type *Ty) const {
9255   assert(Ty->isIntegerTy());
9256 
9257   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9258   if (BitSize == 0)
9259     return false;
9260 
9261   int64_t Val = Imm.getSExtValue();
9262   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9263     return true;
9264 
9265   if ((int64_t)Val < 0)
9266     Val = ~Val;
9267   if (BitSize == 32)
9268     Val &= (1LL << 32) - 1;
9269 
9270   unsigned LZ = countLeadingZeros((uint64_t)Val);
9271   unsigned Shift = (63 - LZ) / 16;
9272   // MOVZ is free so return true for one or fewer MOVK.
9273   return Shift < 3;
9274 }
9275 
9276 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9277                                                     unsigned Index) const {
9278   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9279     return false;
9280 
9281   return (Index == 0 || Index == ResVT.getVectorNumElements());
9282 }
9283 
9284 /// Turn vector tests of the signbit in the form of:
9285 ///   xor (sra X, elt_size(X)-1), -1
9286 /// into:
9287 ///   cmge X, X, #0
9288 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9289                                          const AArch64Subtarget *Subtarget) {
9290   EVT VT = N->getValueType(0);
9291   if (!Subtarget->hasNEON() || !VT.isVector())
9292     return SDValue();
9293 
9294   // There must be a shift right algebraic before the xor, and the xor must be a
9295   // 'not' operation.
9296   SDValue Shift = N->getOperand(0);
9297   SDValue Ones = N->getOperand(1);
9298   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9299       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9300     return SDValue();
9301 
9302   // The shift should be smearing the sign bit across each vector element.
9303   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9304   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9305   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9306     return SDValue();
9307 
9308   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9309 }
9310 
9311 // Generate SUBS and CSEL for integer abs.
9312 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9313   EVT VT = N->getValueType(0);
9314 
9315   SDValue N0 = N->getOperand(0);
9316   SDValue N1 = N->getOperand(1);
9317   SDLoc DL(N);
9318 
9319   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9320   // and change it to SUB and CSEL.
9321   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9322       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9323       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9324     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9325       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9326         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9327                                   N0.getOperand(0));
9328         // Generate SUBS & CSEL.
9329         SDValue Cmp =
9330             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9331                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9332         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9333                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9334                            SDValue(Cmp.getNode(), 1));
9335       }
9336   return SDValue();
9337 }
9338 
9339 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9340                                  TargetLowering::DAGCombinerInfo &DCI,
9341                                  const AArch64Subtarget *Subtarget) {
9342   if (DCI.isBeforeLegalizeOps())
9343     return SDValue();
9344 
9345   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9346     return Cmp;
9347 
9348   return performIntegerAbsCombine(N, DAG);
9349 }
9350 
9351 SDValue
9352 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9353                                      SelectionDAG &DAG,
9354                                      SmallVectorImpl<SDNode *> &Created) const {
9355   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9356   if (isIntDivCheap(N->getValueType(0), Attr))
9357     return SDValue(N,0); // Lower SDIV as SDIV
9358 
9359   // fold (sdiv X, pow2)
9360   EVT VT = N->getValueType(0);
9361   if ((VT != MVT::i32 && VT != MVT::i64) ||
9362       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9363     return SDValue();
9364 
9365   SDLoc DL(N);
9366   SDValue N0 = N->getOperand(0);
9367   unsigned Lg2 = Divisor.countTrailingZeros();
9368   SDValue Zero = DAG.getConstant(0, DL, VT);
9369   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9370 
9371   // Add (N0 < 0) ? Pow2 - 1 : 0;
9372   SDValue CCVal;
9373   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9374   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9375   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9376 
9377   Created.push_back(Cmp.getNode());
9378   Created.push_back(Add.getNode());
9379   Created.push_back(CSel.getNode());
9380 
9381   // Divide by pow2.
9382   SDValue SRA =
9383       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9384 
9385   // If we're dividing by a positive value, we're done.  Otherwise, we must
9386   // negate the result.
9387   if (Divisor.isNonNegative())
9388     return SRA;
9389 
9390   Created.push_back(SRA.getNode());
9391   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9392 }
9393 
9394 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9395                                  TargetLowering::DAGCombinerInfo &DCI,
9396                                  const AArch64Subtarget *Subtarget) {
9397   if (DCI.isBeforeLegalizeOps())
9398     return SDValue();
9399 
9400   // The below optimizations require a constant RHS.
9401   if (!isa<ConstantSDNode>(N->getOperand(1)))
9402     return SDValue();
9403 
9404   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9405   const APInt &ConstValue = C->getAPIntValue();
9406 
9407   // Multiplication of a power of two plus/minus one can be done more
9408   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9409   // future CPUs have a cheaper MADD instruction, this may need to be
9410   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9411   // 64-bit is 5 cycles, so this is always a win.
9412   // More aggressively, some multiplications N0 * C can be lowered to
9413   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9414   // e.g. 6=3*2=(2+1)*2.
9415   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9416   // which equals to (1+2)*16-(1+2).
9417   SDValue N0 = N->getOperand(0);
9418   // TrailingZeroes is used to test if the mul can be lowered to
9419   // shift+add+shift.
9420   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9421   if (TrailingZeroes) {
9422     // Conservatively do not lower to shift+add+shift if the mul might be
9423     // folded into smul or umul.
9424     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9425                             isZeroExtended(N0.getNode(), DAG)))
9426       return SDValue();
9427     // Conservatively do not lower to shift+add+shift if the mul might be
9428     // folded into madd or msub.
9429     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9430                            N->use_begin()->getOpcode() == ISD::SUB))
9431       return SDValue();
9432   }
9433   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9434   // and shift+add+shift.
9435   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9436 
9437   unsigned ShiftAmt, AddSubOpc;
9438   // Is the shifted value the LHS operand of the add/sub?
9439   bool ShiftValUseIsN0 = true;
9440   // Do we need to negate the result?
9441   bool NegateResult = false;
9442 
9443   if (ConstValue.isNonNegative()) {
9444     // (mul x, 2^N + 1) => (add (shl x, N), x)
9445     // (mul x, 2^N - 1) => (sub (shl x, N), x)
9446     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9447     APInt SCVMinus1 = ShiftedConstValue - 1;
9448     APInt CVPlus1 = ConstValue + 1;
9449     if (SCVMinus1.isPowerOf2()) {
9450       ShiftAmt = SCVMinus1.logBase2();
9451       AddSubOpc = ISD::ADD;
9452     } else if (CVPlus1.isPowerOf2()) {
9453       ShiftAmt = CVPlus1.logBase2();
9454       AddSubOpc = ISD::SUB;
9455     } else
9456       return SDValue();
9457   } else {
9458     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9459     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9460     APInt CVNegPlus1 = -ConstValue + 1;
9461     APInt CVNegMinus1 = -ConstValue - 1;
9462     if (CVNegPlus1.isPowerOf2()) {
9463       ShiftAmt = CVNegPlus1.logBase2();
9464       AddSubOpc = ISD::SUB;
9465       ShiftValUseIsN0 = false;
9466     } else if (CVNegMinus1.isPowerOf2()) {
9467       ShiftAmt = CVNegMinus1.logBase2();
9468       AddSubOpc = ISD::ADD;
9469       NegateResult = true;
9470     } else
9471       return SDValue();
9472   }
9473 
9474   SDLoc DL(N);
9475   EVT VT = N->getValueType(0);
9476   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9477                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
9478 
9479   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9480   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9481   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9482   assert(!(NegateResult && TrailingZeroes) &&
9483          "NegateResult and TrailingZeroes cannot both be true for now.");
9484   // Negate the result.
9485   if (NegateResult)
9486     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9487   // Shift the result.
9488   if (TrailingZeroes)
9489     return DAG.getNode(ISD::SHL, DL, VT, Res,
9490                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9491   return Res;
9492 }
9493 
9494 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9495                                                          SelectionDAG &DAG) {
9496   // Take advantage of vector comparisons producing 0 or -1 in each lane to
9497   // optimize away operation when it's from a constant.
9498   //
9499   // The general transformation is:
9500   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9501   //       AND(VECTOR_CMP(x,y), constant2)
9502   //    constant2 = UNARYOP(constant)
9503 
9504   // Early exit if this isn't a vector operation, the operand of the
9505   // unary operation isn't a bitwise AND, or if the sizes of the operations
9506   // aren't the same.
9507   EVT VT = N->getValueType(0);
9508   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9509       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9510       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9511     return SDValue();
9512 
9513   // Now check that the other operand of the AND is a constant. We could
9514   // make the transformation for non-constant splats as well, but it's unclear
9515   // that would be a benefit as it would not eliminate any operations, just
9516   // perform one more step in scalar code before moving to the vector unit.
9517   if (BuildVectorSDNode *BV =
9518           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9519     // Bail out if the vector isn't a constant.
9520     if (!BV->isConstant())
9521       return SDValue();
9522 
9523     // Everything checks out. Build up the new and improved node.
9524     SDLoc DL(N);
9525     EVT IntVT = BV->getValueType(0);
9526     // Create a new constant of the appropriate type for the transformed
9527     // DAG.
9528     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9529     // The AND node needs bitcasts to/from an integer vector type around it.
9530     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9531     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9532                                  N->getOperand(0)->getOperand(0), MaskConst);
9533     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9534     return Res;
9535   }
9536 
9537   return SDValue();
9538 }
9539 
9540 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9541                                      const AArch64Subtarget *Subtarget) {
9542   // First try to optimize away the conversion when it's conditionally from
9543   // a constant. Vectors only.
9544   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9545     return Res;
9546 
9547   EVT VT = N->getValueType(0);
9548   if (VT != MVT::f32 && VT != MVT::f64)
9549     return SDValue();
9550 
9551   // Only optimize when the source and destination types have the same width.
9552   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9553     return SDValue();
9554 
9555   // If the result of an integer load is only used by an integer-to-float
9556   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9557   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9558   SDValue N0 = N->getOperand(0);
9559   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9560       // Do not change the width of a volatile load.
9561       !cast<LoadSDNode>(N0)->isVolatile()) {
9562     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9563     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9564                                LN0->getPointerInfo(), LN0->getAlignment(),
9565                                LN0->getMemOperand()->getFlags());
9566 
9567     // Make sure successors of the original load stay after it by updating them
9568     // to use the new Chain.
9569     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9570 
9571     unsigned Opcode =
9572         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9573     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9574   }
9575 
9576   return SDValue();
9577 }
9578 
9579 /// Fold a floating-point multiply by power of two into floating-point to
9580 /// fixed-point conversion.
9581 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9582                                      TargetLowering::DAGCombinerInfo &DCI,
9583                                      const AArch64Subtarget *Subtarget) {
9584   if (!Subtarget->hasNEON())
9585     return SDValue();
9586 
9587   if (!N->getValueType(0).isSimple())
9588     return SDValue();
9589 
9590   SDValue Op = N->getOperand(0);
9591   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9592       Op.getOpcode() != ISD::FMUL)
9593     return SDValue();
9594 
9595   SDValue ConstVec = Op->getOperand(1);
9596   if (!isa<BuildVectorSDNode>(ConstVec))
9597     return SDValue();
9598 
9599   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9600   uint32_t FloatBits = FloatTy.getSizeInBits();
9601   if (FloatBits != 32 && FloatBits != 64)
9602     return SDValue();
9603 
9604   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9605   uint32_t IntBits = IntTy.getSizeInBits();
9606   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9607     return SDValue();
9608 
9609   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9610   if (IntBits > FloatBits)
9611     return SDValue();
9612 
9613   BitVector UndefElements;
9614   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9615   int32_t Bits = IntBits == 64 ? 64 : 32;
9616   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9617   if (C == -1 || C == 0 || C > Bits)
9618     return SDValue();
9619 
9620   MVT ResTy;
9621   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9622   switch (NumLanes) {
9623   default:
9624     return SDValue();
9625   case 2:
9626     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9627     break;
9628   case 4:
9629     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9630     break;
9631   }
9632 
9633   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9634     return SDValue();
9635 
9636   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9637          "Illegal vector type after legalization");
9638 
9639   SDLoc DL(N);
9640   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9641   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9642                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
9643   SDValue FixConv =
9644       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9645                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9646                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9647   // We can handle smaller integers by generating an extra trunc.
9648   if (IntBits < FloatBits)
9649     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9650 
9651   return FixConv;
9652 }
9653 
9654 /// Fold a floating-point divide by power of two into fixed-point to
9655 /// floating-point conversion.
9656 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9657                                   TargetLowering::DAGCombinerInfo &DCI,
9658                                   const AArch64Subtarget *Subtarget) {
9659   if (!Subtarget->hasNEON())
9660     return SDValue();
9661 
9662   SDValue Op = N->getOperand(0);
9663   unsigned Opc = Op->getOpcode();
9664   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9665       !Op.getOperand(0).getValueType().isSimple() ||
9666       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9667     return SDValue();
9668 
9669   SDValue ConstVec = N->getOperand(1);
9670   if (!isa<BuildVectorSDNode>(ConstVec))
9671     return SDValue();
9672 
9673   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9674   int32_t IntBits = IntTy.getSizeInBits();
9675   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9676     return SDValue();
9677 
9678   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9679   int32_t FloatBits = FloatTy.getSizeInBits();
9680   if (FloatBits != 32 && FloatBits != 64)
9681     return SDValue();
9682 
9683   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9684   if (IntBits > FloatBits)
9685     return SDValue();
9686 
9687   BitVector UndefElements;
9688   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9689   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9690   if (C == -1 || C == 0 || C > FloatBits)
9691     return SDValue();
9692 
9693   MVT ResTy;
9694   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9695   switch (NumLanes) {
9696   default:
9697     return SDValue();
9698   case 2:
9699     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9700     break;
9701   case 4:
9702     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9703     break;
9704   }
9705 
9706   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9707     return SDValue();
9708 
9709   SDLoc DL(N);
9710   SDValue ConvInput = Op.getOperand(0);
9711   bool IsSigned = Opc == ISD::SINT_TO_FP;
9712   if (IntBits < FloatBits)
9713     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9714                             ResTy, ConvInput);
9715 
9716   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9717                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
9718   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9719                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9720                      DAG.getConstant(C, DL, MVT::i32));
9721 }
9722 
9723 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9724 /// searches for and classifies those shifts.
9725 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9726                          bool &FromHi) {
9727   if (N.getOpcode() == ISD::SHL)
9728     FromHi = false;
9729   else if (N.getOpcode() == ISD::SRL)
9730     FromHi = true;
9731   else
9732     return false;
9733 
9734   if (!isa<ConstantSDNode>(N.getOperand(1)))
9735     return false;
9736 
9737   ShiftAmount = N->getConstantOperandVal(1);
9738   Src = N->getOperand(0);
9739   return true;
9740 }
9741 
9742 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9743 /// registers viewed as a high/low pair. This function looks for the pattern:
9744 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9745 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9746 /// aren't independent.
9747 static SDValue tryCombineToEXTR(SDNode *N,
9748                                 TargetLowering::DAGCombinerInfo &DCI) {
9749   SelectionDAG &DAG = DCI.DAG;
9750   SDLoc DL(N);
9751   EVT VT = N->getValueType(0);
9752 
9753   assert(N->getOpcode() == ISD::OR && "Unexpected root");
9754 
9755   if (VT != MVT::i32 && VT != MVT::i64)
9756     return SDValue();
9757 
9758   SDValue LHS;
9759   uint32_t ShiftLHS = 0;
9760   bool LHSFromHi = false;
9761   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9762     return SDValue();
9763 
9764   SDValue RHS;
9765   uint32_t ShiftRHS = 0;
9766   bool RHSFromHi = false;
9767   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9768     return SDValue();
9769 
9770   // If they're both trying to come from the high part of the register, they're
9771   // not really an EXTR.
9772   if (LHSFromHi == RHSFromHi)
9773     return SDValue();
9774 
9775   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9776     return SDValue();
9777 
9778   if (LHSFromHi) {
9779     std::swap(LHS, RHS);
9780     std::swap(ShiftLHS, ShiftRHS);
9781   }
9782 
9783   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9784                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
9785 }
9786 
9787 static SDValue tryCombineToBSL(SDNode *N,
9788                                 TargetLowering::DAGCombinerInfo &DCI) {
9789   EVT VT = N->getValueType(0);
9790   SelectionDAG &DAG = DCI.DAG;
9791   SDLoc DL(N);
9792 
9793   if (!VT.isVector())
9794     return SDValue();
9795 
9796   SDValue N0 = N->getOperand(0);
9797   if (N0.getOpcode() != ISD::AND)
9798     return SDValue();
9799 
9800   SDValue N1 = N->getOperand(1);
9801   if (N1.getOpcode() != ISD::AND)
9802     return SDValue();
9803 
9804   // We only have to look for constant vectors here since the general, variable
9805   // case can be handled in TableGen.
9806   unsigned Bits = VT.getScalarSizeInBits();
9807   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9808   for (int i = 1; i >= 0; --i)
9809     for (int j = 1; j >= 0; --j) {
9810       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9811       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9812       if (!BVN0 || !BVN1)
9813         continue;
9814 
9815       bool FoundMatch = true;
9816       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9817         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9818         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9819         if (!CN0 || !CN1 ||
9820             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9821           FoundMatch = false;
9822           break;
9823         }
9824       }
9825 
9826       if (FoundMatch)
9827         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9828                            N0->getOperand(1 - i), N1->getOperand(1 - j));
9829     }
9830 
9831   return SDValue();
9832 }
9833 
9834 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9835                                 const AArch64Subtarget *Subtarget) {
9836   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9837   SelectionDAG &DAG = DCI.DAG;
9838   EVT VT = N->getValueType(0);
9839 
9840   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9841     return SDValue();
9842 
9843   if (SDValue Res = tryCombineToEXTR(N, DCI))
9844     return Res;
9845 
9846   if (SDValue Res = tryCombineToBSL(N, DCI))
9847     return Res;
9848 
9849   return SDValue();
9850 }
9851 
9852 static SDValue performANDCombine(SDNode *N,
9853                                  TargetLowering::DAGCombinerInfo &DCI) {
9854   SelectionDAG &DAG = DCI.DAG;
9855   SDValue LHS = N->getOperand(0);
9856   EVT VT = N->getValueType(0);
9857   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9858     return SDValue();
9859 
9860   BuildVectorSDNode *BVN =
9861       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9862   if (!BVN)
9863     return SDValue();
9864 
9865   // AND does not accept an immediate, so check if we can use a BIC immediate
9866   // instruction instead. We do this here instead of using a (and x, (mvni imm))
9867   // pattern in isel, because some immediates may be lowered to the preferred
9868   // (and x, (movi imm)) form, even though an mvni representation also exists.
9869   APInt DefBits(VT.getSizeInBits(), 0);
9870   APInt UndefBits(VT.getSizeInBits(), 0);
9871   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9872     SDValue NewOp;
9873 
9874     DefBits = ~DefBits;
9875     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9876                                     DefBits, &LHS)) ||
9877         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9878                                     DefBits, &LHS)))
9879       return NewOp;
9880 
9881     UndefBits = ~UndefBits;
9882     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9883                                     UndefBits, &LHS)) ||
9884         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9885                                     UndefBits, &LHS)))
9886       return NewOp;
9887   }
9888 
9889   return SDValue();
9890 }
9891 
9892 static SDValue performSRLCombine(SDNode *N,
9893                                  TargetLowering::DAGCombinerInfo &DCI) {
9894   SelectionDAG &DAG = DCI.DAG;
9895   EVT VT = N->getValueType(0);
9896   if (VT != MVT::i32 && VT != MVT::i64)
9897     return SDValue();
9898 
9899   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9900   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9901   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9902   SDValue N0 = N->getOperand(0);
9903   if (N0.getOpcode() == ISD::BSWAP) {
9904     SDLoc DL(N);
9905     SDValue N1 = N->getOperand(1);
9906     SDValue N00 = N0.getOperand(0);
9907     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9908       uint64_t ShiftAmt = C->getZExtValue();
9909       if (VT == MVT::i32 && ShiftAmt == 16 &&
9910           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9911         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9912       if (VT == MVT::i64 && ShiftAmt == 32 &&
9913           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9914         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9915     }
9916   }
9917   return SDValue();
9918 }
9919 
9920 static SDValue performBitcastCombine(SDNode *N,
9921                                      TargetLowering::DAGCombinerInfo &DCI,
9922                                      SelectionDAG &DAG) {
9923   // Wait 'til after everything is legalized to try this. That way we have
9924   // legal vector types and such.
9925   if (DCI.isBeforeLegalizeOps())
9926     return SDValue();
9927 
9928   // Remove extraneous bitcasts around an extract_subvector.
9929   // For example,
9930   //    (v4i16 (bitconvert
9931   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9932   //  becomes
9933   //    (extract_subvector ((v8i16 ...), (i64 4)))
9934 
9935   // Only interested in 64-bit vectors as the ultimate result.
9936   EVT VT = N->getValueType(0);
9937   if (!VT.isVector())
9938     return SDValue();
9939   if (VT.getSimpleVT().getSizeInBits() != 64)
9940     return SDValue();
9941   // Is the operand an extract_subvector starting at the beginning or halfway
9942   // point of the vector? A low half may also come through as an
9943   // EXTRACT_SUBREG, so look for that, too.
9944   SDValue Op0 = N->getOperand(0);
9945   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9946       !(Op0->isMachineOpcode() &&
9947         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9948     return SDValue();
9949   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9950   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9951     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9952       return SDValue();
9953   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9954     if (idx != AArch64::dsub)
9955       return SDValue();
9956     // The dsub reference is equivalent to a lane zero subvector reference.
9957     idx = 0;
9958   }
9959   // Look through the bitcast of the input to the extract.
9960   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9961     return SDValue();
9962   SDValue Source = Op0->getOperand(0)->getOperand(0);
9963   // If the source type has twice the number of elements as our destination
9964   // type, we know this is an extract of the high or low half of the vector.
9965   EVT SVT = Source->getValueType(0);
9966   if (!SVT.isVector() ||
9967       SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9968     return SDValue();
9969 
9970   LLVM_DEBUG(
9971       dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9972 
9973   // Create the simplified form to just extract the low or high half of the
9974   // vector directly rather than bothering with the bitcasts.
9975   SDLoc dl(N);
9976   unsigned NumElements = VT.getVectorNumElements();
9977   if (idx) {
9978     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9979     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9980   } else {
9981     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9982     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9983                                       Source, SubReg),
9984                    0);
9985   }
9986 }
9987 
9988 static SDValue performConcatVectorsCombine(SDNode *N,
9989                                            TargetLowering::DAGCombinerInfo &DCI,
9990                                            SelectionDAG &DAG) {
9991   SDLoc dl(N);
9992   EVT VT = N->getValueType(0);
9993   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9994 
9995   // Optimize concat_vectors of truncated vectors, where the intermediate
9996   // type is illegal, to avoid said illegality,  e.g.,
9997   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9998   //                          (v2i16 (truncate (v2i64)))))
9999   // ->
10000   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10001   //                                    (v4i32 (bitcast (v2i64))),
10002   //                                    <0, 2, 4, 6>)))
10003   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10004   // on both input and result type, so we might generate worse code.
10005   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10006   if (N->getNumOperands() == 2 &&
10007       N0->getOpcode() == ISD::TRUNCATE &&
10008       N1->getOpcode() == ISD::TRUNCATE) {
10009     SDValue N00 = N0->getOperand(0);
10010     SDValue N10 = N1->getOperand(0);
10011     EVT N00VT = N00.getValueType();
10012 
10013     if (N00VT == N10.getValueType() &&
10014         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10015         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10016       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10017       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10018       for (size_t i = 0; i < Mask.size(); ++i)
10019         Mask[i] = i * 2;
10020       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10021                          DAG.getVectorShuffle(
10022                              MidVT, dl,
10023                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10024                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10025     }
10026   }
10027 
10028   // Wait 'til after everything is legalized to try this. That way we have
10029   // legal vector types and such.
10030   if (DCI.isBeforeLegalizeOps())
10031     return SDValue();
10032 
10033   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10034   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10035   // canonicalise to that.
10036   if (N0 == N1 && VT.getVectorNumElements() == 2) {
10037     assert(VT.getScalarSizeInBits() == 64);
10038     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10039                        DAG.getConstant(0, dl, MVT::i64));
10040   }
10041 
10042   // Canonicalise concat_vectors so that the right-hand vector has as few
10043   // bit-casts as possible before its real operation. The primary matching
10044   // destination for these operations will be the narrowing "2" instructions,
10045   // which depend on the operation being performed on this right-hand vector.
10046   // For example,
10047   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
10048   // becomes
10049   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10050 
10051   if (N1->getOpcode() != ISD::BITCAST)
10052     return SDValue();
10053   SDValue RHS = N1->getOperand(0);
10054   MVT RHSTy = RHS.getValueType().getSimpleVT();
10055   // If the RHS is not a vector, this is not the pattern we're looking for.
10056   if (!RHSTy.isVector())
10057     return SDValue();
10058 
10059   LLVM_DEBUG(
10060       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10061 
10062   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10063                                   RHSTy.getVectorNumElements() * 2);
10064   return DAG.getNode(ISD::BITCAST, dl, VT,
10065                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10066                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10067                                  RHS));
10068 }
10069 
10070 static SDValue tryCombineFixedPointConvert(SDNode *N,
10071                                            TargetLowering::DAGCombinerInfo &DCI,
10072                                            SelectionDAG &DAG) {
10073   // Wait until after everything is legalized to try this. That way we have
10074   // legal vector types and such.
10075   if (DCI.isBeforeLegalizeOps())
10076     return SDValue();
10077   // Transform a scalar conversion of a value from a lane extract into a
10078   // lane extract of a vector conversion. E.g., from foo1 to foo2:
10079   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10080   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10081   //
10082   // The second form interacts better with instruction selection and the
10083   // register allocator to avoid cross-class register copies that aren't
10084   // coalescable due to a lane reference.
10085 
10086   // Check the operand and see if it originates from a lane extract.
10087   SDValue Op1 = N->getOperand(1);
10088   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10089     // Yep, no additional predication needed. Perform the transform.
10090     SDValue IID = N->getOperand(0);
10091     SDValue Shift = N->getOperand(2);
10092     SDValue Vec = Op1.getOperand(0);
10093     SDValue Lane = Op1.getOperand(1);
10094     EVT ResTy = N->getValueType(0);
10095     EVT VecResTy;
10096     SDLoc DL(N);
10097 
10098     // The vector width should be 128 bits by the time we get here, even
10099     // if it started as 64 bits (the extract_vector handling will have
10100     // done so).
10101     assert(Vec.getValueSizeInBits() == 128 &&
10102            "unexpected vector size on extract_vector_elt!");
10103     if (Vec.getValueType() == MVT::v4i32)
10104       VecResTy = MVT::v4f32;
10105     else if (Vec.getValueType() == MVT::v2i64)
10106       VecResTy = MVT::v2f64;
10107     else
10108       llvm_unreachable("unexpected vector type!");
10109 
10110     SDValue Convert =
10111         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10112     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10113   }
10114   return SDValue();
10115 }
10116 
10117 // AArch64 high-vector "long" operations are formed by performing the non-high
10118 // version on an extract_subvector of each operand which gets the high half:
10119 //
10120 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10121 //
10122 // However, there are cases which don't have an extract_high explicitly, but
10123 // have another operation that can be made compatible with one for free. For
10124 // example:
10125 //
10126 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
10127 //
10128 // This routine does the actual conversion of such DUPs, once outer routines
10129 // have determined that everything else is in order.
10130 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10131 // similarly here.
10132 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10133   switch (N.getOpcode()) {
10134   case AArch64ISD::DUP:
10135   case AArch64ISD::DUPLANE8:
10136   case AArch64ISD::DUPLANE16:
10137   case AArch64ISD::DUPLANE32:
10138   case AArch64ISD::DUPLANE64:
10139   case AArch64ISD::MOVI:
10140   case AArch64ISD::MOVIshift:
10141   case AArch64ISD::MOVIedit:
10142   case AArch64ISD::MOVImsl:
10143   case AArch64ISD::MVNIshift:
10144   case AArch64ISD::MVNImsl:
10145     break;
10146   default:
10147     // FMOV could be supported, but isn't very useful, as it would only occur
10148     // if you passed a bitcast' floating point immediate to an eligible long
10149     // integer op (addl, smull, ...).
10150     return SDValue();
10151   }
10152 
10153   MVT NarrowTy = N.getSimpleValueType();
10154   if (!NarrowTy.is64BitVector())
10155     return SDValue();
10156 
10157   MVT ElementTy = NarrowTy.getVectorElementType();
10158   unsigned NumElems = NarrowTy.getVectorNumElements();
10159   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10160 
10161   SDLoc dl(N);
10162   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10163                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10164                      DAG.getConstant(NumElems, dl, MVT::i64));
10165 }
10166 
10167 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10168   if (N.getOpcode() == ISD::BITCAST)
10169     N = N.getOperand(0);
10170   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10171     return false;
10172   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10173          N.getOperand(0).getValueType().getVectorNumElements() / 2;
10174 }
10175 
10176 /// Helper structure to keep track of ISD::SET_CC operands.
10177 struct GenericSetCCInfo {
10178   const SDValue *Opnd0;
10179   const SDValue *Opnd1;
10180   ISD::CondCode CC;
10181 };
10182 
10183 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10184 struct AArch64SetCCInfo {
10185   const SDValue *Cmp;
10186   AArch64CC::CondCode CC;
10187 };
10188 
10189 /// Helper structure to keep track of SetCC information.
10190 union SetCCInfo {
10191   GenericSetCCInfo Generic;
10192   AArch64SetCCInfo AArch64;
10193 };
10194 
10195 /// Helper structure to be able to read SetCC information.  If set to
10196 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10197 /// GenericSetCCInfo.
10198 struct SetCCInfoAndKind {
10199   SetCCInfo Info;
10200   bool IsAArch64;
10201 };
10202 
10203 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10204 /// an
10205 /// AArch64 lowered one.
10206 /// \p SetCCInfo is filled accordingly.
10207 /// \post SetCCInfo is meanginfull only when this function returns true.
10208 /// \return True when Op is a kind of SET_CC operation.
10209 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10210   // If this is a setcc, this is straight forward.
10211   if (Op.getOpcode() == ISD::SETCC) {
10212     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10213     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10214     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10215     SetCCInfo.IsAArch64 = false;
10216     return true;
10217   }
10218   // Otherwise, check if this is a matching csel instruction.
10219   // In other words:
10220   // - csel 1, 0, cc
10221   // - csel 0, 1, !cc
10222   if (Op.getOpcode() != AArch64ISD::CSEL)
10223     return false;
10224   // Set the information about the operands.
10225   // TODO: we want the operands of the Cmp not the csel
10226   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10227   SetCCInfo.IsAArch64 = true;
10228   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10229       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10230 
10231   // Check that the operands matches the constraints:
10232   // (1) Both operands must be constants.
10233   // (2) One must be 1 and the other must be 0.
10234   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10235   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10236 
10237   // Check (1).
10238   if (!TValue || !FValue)
10239     return false;
10240 
10241   // Check (2).
10242   if (!TValue->isOne()) {
10243     // Update the comparison when we are interested in !cc.
10244     std::swap(TValue, FValue);
10245     SetCCInfo.Info.AArch64.CC =
10246         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10247   }
10248   return TValue->isOne() && FValue->isNullValue();
10249 }
10250 
10251 // Returns true if Op is setcc or zext of setcc.
10252 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10253   if (isSetCC(Op, Info))
10254     return true;
10255   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10256     isSetCC(Op->getOperand(0), Info));
10257 }
10258 
10259 // The folding we want to perform is:
10260 // (add x, [zext] (setcc cc ...) )
10261 //   -->
10262 // (csel x, (add x, 1), !cc ...)
10263 //
10264 // The latter will get matched to a CSINC instruction.
10265 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10266   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10267   SDValue LHS = Op->getOperand(0);
10268   SDValue RHS = Op->getOperand(1);
10269   SetCCInfoAndKind InfoAndKind;
10270 
10271   // If neither operand is a SET_CC, give up.
10272   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10273     std::swap(LHS, RHS);
10274     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10275       return SDValue();
10276   }
10277 
10278   // FIXME: This could be generatized to work for FP comparisons.
10279   EVT CmpVT = InfoAndKind.IsAArch64
10280                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10281                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10282   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10283     return SDValue();
10284 
10285   SDValue CCVal;
10286   SDValue Cmp;
10287   SDLoc dl(Op);
10288   if (InfoAndKind.IsAArch64) {
10289     CCVal = DAG.getConstant(
10290         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10291         MVT::i32);
10292     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10293   } else
10294     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10295                       *InfoAndKind.Info.Generic.Opnd1,
10296                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10297                       CCVal, DAG, dl);
10298 
10299   EVT VT = Op->getValueType(0);
10300   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10301   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10302 }
10303 
10304 // The basic add/sub long vector instructions have variants with "2" on the end
10305 // which act on the high-half of their inputs. They are normally matched by
10306 // patterns like:
10307 //
10308 // (add (zeroext (extract_high LHS)),
10309 //      (zeroext (extract_high RHS)))
10310 // -> uaddl2 vD, vN, vM
10311 //
10312 // However, if one of the extracts is something like a duplicate, this
10313 // instruction can still be used profitably. This function puts the DAG into a
10314 // more appropriate form for those patterns to trigger.
10315 static SDValue performAddSubLongCombine(SDNode *N,
10316                                         TargetLowering::DAGCombinerInfo &DCI,
10317                                         SelectionDAG &DAG) {
10318   if (DCI.isBeforeLegalizeOps())
10319     return SDValue();
10320 
10321   MVT VT = N->getSimpleValueType(0);
10322   if (!VT.is128BitVector()) {
10323     if (N->getOpcode() == ISD::ADD)
10324       return performSetccAddFolding(N, DAG);
10325     return SDValue();
10326   }
10327 
10328   // Make sure both branches are extended in the same way.
10329   SDValue LHS = N->getOperand(0);
10330   SDValue RHS = N->getOperand(1);
10331   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10332        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10333       LHS.getOpcode() != RHS.getOpcode())
10334     return SDValue();
10335 
10336   unsigned ExtType = LHS.getOpcode();
10337 
10338   // It's not worth doing if at least one of the inputs isn't already an
10339   // extract, but we don't know which it'll be so we have to try both.
10340   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10341     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10342     if (!RHS.getNode())
10343       return SDValue();
10344 
10345     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10346   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10347     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10348     if (!LHS.getNode())
10349       return SDValue();
10350 
10351     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10352   }
10353 
10354   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10355 }
10356 
10357 // Massage DAGs which we can use the high-half "long" operations on into
10358 // something isel will recognize better. E.g.
10359 //
10360 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10361 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10362 //                     (extract_high (v2i64 (dup128 scalar)))))
10363 //
10364 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10365                                        TargetLowering::DAGCombinerInfo &DCI,
10366                                        SelectionDAG &DAG) {
10367   if (DCI.isBeforeLegalizeOps())
10368     return SDValue();
10369 
10370   SDValue LHS = N->getOperand(1);
10371   SDValue RHS = N->getOperand(2);
10372   assert(LHS.getValueType().is64BitVector() &&
10373          RHS.getValueType().is64BitVector() &&
10374          "unexpected shape for long operation");
10375 
10376   // Either node could be a DUP, but it's not worth doing both of them (you'd
10377   // just as well use the non-high version) so look for a corresponding extract
10378   // operation on the other "wing".
10379   if (isEssentiallyExtractHighSubvector(LHS)) {
10380     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10381     if (!RHS.getNode())
10382       return SDValue();
10383   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10384     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10385     if (!LHS.getNode())
10386       return SDValue();
10387   }
10388 
10389   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10390                      N->getOperand(0), LHS, RHS);
10391 }
10392 
10393 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10394   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10395   unsigned ElemBits = ElemTy.getSizeInBits();
10396 
10397   int64_t ShiftAmount;
10398   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10399     APInt SplatValue, SplatUndef;
10400     unsigned SplatBitSize;
10401     bool HasAnyUndefs;
10402     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10403                               HasAnyUndefs, ElemBits) ||
10404         SplatBitSize != ElemBits)
10405       return SDValue();
10406 
10407     ShiftAmount = SplatValue.getSExtValue();
10408   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10409     ShiftAmount = CVN->getSExtValue();
10410   } else
10411     return SDValue();
10412 
10413   unsigned Opcode;
10414   bool IsRightShift;
10415   switch (IID) {
10416   default:
10417     llvm_unreachable("Unknown shift intrinsic");
10418   case Intrinsic::aarch64_neon_sqshl:
10419     Opcode = AArch64ISD::SQSHL_I;
10420     IsRightShift = false;
10421     break;
10422   case Intrinsic::aarch64_neon_uqshl:
10423     Opcode = AArch64ISD::UQSHL_I;
10424     IsRightShift = false;
10425     break;
10426   case Intrinsic::aarch64_neon_srshl:
10427     Opcode = AArch64ISD::SRSHR_I;
10428     IsRightShift = true;
10429     break;
10430   case Intrinsic::aarch64_neon_urshl:
10431     Opcode = AArch64ISD::URSHR_I;
10432     IsRightShift = true;
10433     break;
10434   case Intrinsic::aarch64_neon_sqshlu:
10435     Opcode = AArch64ISD::SQSHLU_I;
10436     IsRightShift = false;
10437     break;
10438   case Intrinsic::aarch64_neon_sshl:
10439   case Intrinsic::aarch64_neon_ushl:
10440     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
10441     // left shift for positive shift amounts. Below, we only replace the current
10442     // node with VSHL, if this condition is met.
10443     Opcode = AArch64ISD::VSHL;
10444     IsRightShift = false;
10445     break;
10446   }
10447 
10448   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10449     SDLoc dl(N);
10450     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10451                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10452   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10453     SDLoc dl(N);
10454     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10455                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
10456   }
10457 
10458   return SDValue();
10459 }
10460 
10461 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10462 // the intrinsics must be legal and take an i32, this means there's almost
10463 // certainly going to be a zext in the DAG which we can eliminate.
10464 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10465   SDValue AndN = N->getOperand(2);
10466   if (AndN.getOpcode() != ISD::AND)
10467     return SDValue();
10468 
10469   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10470   if (!CMask || CMask->getZExtValue() != Mask)
10471     return SDValue();
10472 
10473   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10474                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10475 }
10476 
10477 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10478                                            SelectionDAG &DAG) {
10479   SDLoc dl(N);
10480   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10481                      DAG.getNode(Opc, dl,
10482                                  N->getOperand(1).getSimpleValueType(),
10483                                  N->getOperand(1)),
10484                      DAG.getConstant(0, dl, MVT::i64));
10485 }
10486 
10487 static SDValue performIntrinsicCombine(SDNode *N,
10488                                        TargetLowering::DAGCombinerInfo &DCI,
10489                                        const AArch64Subtarget *Subtarget) {
10490   SelectionDAG &DAG = DCI.DAG;
10491   unsigned IID = getIntrinsicID(N);
10492   switch (IID) {
10493   default:
10494     break;
10495   case Intrinsic::aarch64_neon_vcvtfxs2fp:
10496   case Intrinsic::aarch64_neon_vcvtfxu2fp:
10497     return tryCombineFixedPointConvert(N, DCI, DAG);
10498   case Intrinsic::aarch64_neon_saddv:
10499     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10500   case Intrinsic::aarch64_neon_uaddv:
10501     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10502   case Intrinsic::aarch64_neon_sminv:
10503     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10504   case Intrinsic::aarch64_neon_uminv:
10505     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10506   case Intrinsic::aarch64_neon_smaxv:
10507     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10508   case Intrinsic::aarch64_neon_umaxv:
10509     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10510   case Intrinsic::aarch64_neon_fmax:
10511     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10512                        N->getOperand(1), N->getOperand(2));
10513   case Intrinsic::aarch64_neon_fmin:
10514     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10515                        N->getOperand(1), N->getOperand(2));
10516   case Intrinsic::aarch64_neon_fmaxnm:
10517     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10518                        N->getOperand(1), N->getOperand(2));
10519   case Intrinsic::aarch64_neon_fminnm:
10520     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10521                        N->getOperand(1), N->getOperand(2));
10522   case Intrinsic::aarch64_neon_smull:
10523   case Intrinsic::aarch64_neon_umull:
10524   case Intrinsic::aarch64_neon_pmull:
10525   case Intrinsic::aarch64_neon_sqdmull:
10526     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10527   case Intrinsic::aarch64_neon_sqshl:
10528   case Intrinsic::aarch64_neon_uqshl:
10529   case Intrinsic::aarch64_neon_sqshlu:
10530   case Intrinsic::aarch64_neon_srshl:
10531   case Intrinsic::aarch64_neon_urshl:
10532   case Intrinsic::aarch64_neon_sshl:
10533   case Intrinsic::aarch64_neon_ushl:
10534     return tryCombineShiftImm(IID, N, DAG);
10535   case Intrinsic::aarch64_crc32b:
10536   case Intrinsic::aarch64_crc32cb:
10537     return tryCombineCRC32(0xff, N, DAG);
10538   case Intrinsic::aarch64_crc32h:
10539   case Intrinsic::aarch64_crc32ch:
10540     return tryCombineCRC32(0xffff, N, DAG);
10541   }
10542   return SDValue();
10543 }
10544 
10545 static SDValue performExtendCombine(SDNode *N,
10546                                     TargetLowering::DAGCombinerInfo &DCI,
10547                                     SelectionDAG &DAG) {
10548   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10549   // we can convert that DUP into another extract_high (of a bigger DUP), which
10550   // helps the backend to decide that an sabdl2 would be useful, saving a real
10551   // extract_high operation.
10552   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
10553       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
10554     SDNode *ABDNode = N->getOperand(0).getNode();
10555     unsigned IID = getIntrinsicID(ABDNode);
10556     if (IID == Intrinsic::aarch64_neon_sabd ||
10557         IID == Intrinsic::aarch64_neon_uabd) {
10558       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10559       if (!NewABD.getNode())
10560         return SDValue();
10561 
10562       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10563                          NewABD);
10564     }
10565   }
10566 
10567   // This is effectively a custom type legalization for AArch64.
10568   //
10569   // Type legalization will split an extend of a small, legal, type to a larger
10570   // illegal type by first splitting the destination type, often creating
10571   // illegal source types, which then get legalized in isel-confusing ways,
10572   // leading to really terrible codegen. E.g.,
10573   //   %result = v8i32 sext v8i8 %value
10574   // becomes
10575   //   %losrc = extract_subreg %value, ...
10576   //   %hisrc = extract_subreg %value, ...
10577   //   %lo = v4i32 sext v4i8 %losrc
10578   //   %hi = v4i32 sext v4i8 %hisrc
10579   // Things go rapidly downhill from there.
10580   //
10581   // For AArch64, the [sz]ext vector instructions can only go up one element
10582   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10583   // take two instructions.
10584   //
10585   // This implies that the most efficient way to do the extend from v8i8
10586   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10587   // the normal splitting to happen for the v8i16->v8i32.
10588 
10589   // This is pre-legalization to catch some cases where the default
10590   // type legalization will create ill-tempered code.
10591   if (!DCI.isBeforeLegalizeOps())
10592     return SDValue();
10593 
10594   // We're only interested in cleaning things up for non-legal vector types
10595   // here. If both the source and destination are legal, things will just
10596   // work naturally without any fiddling.
10597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10598   EVT ResVT = N->getValueType(0);
10599   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10600     return SDValue();
10601   // If the vector type isn't a simple VT, it's beyond the scope of what
10602   // we're  worried about here. Let legalization do its thing and hope for
10603   // the best.
10604   SDValue Src = N->getOperand(0);
10605   EVT SrcVT = Src->getValueType(0);
10606   if (!ResVT.isSimple() || !SrcVT.isSimple())
10607     return SDValue();
10608 
10609   // If the source VT is a 64-bit vector, we can play games and get the
10610   // better results we want.
10611   if (SrcVT.getSizeInBits() != 64)
10612     return SDValue();
10613 
10614   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
10615   unsigned ElementCount = SrcVT.getVectorNumElements();
10616   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10617   SDLoc DL(N);
10618   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10619 
10620   // Now split the rest of the operation into two halves, each with a 64
10621   // bit source.
10622   EVT LoVT, HiVT;
10623   SDValue Lo, Hi;
10624   unsigned NumElements = ResVT.getVectorNumElements();
10625   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10626   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10627                                  ResVT.getVectorElementType(), NumElements / 2);
10628 
10629   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10630                                LoVT.getVectorNumElements());
10631   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10632                    DAG.getConstant(0, DL, MVT::i64));
10633   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10634                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10635   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10636   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10637 
10638   // Now combine the parts back together so we still have a single result
10639   // like the combiner expects.
10640   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10641 }
10642 
10643 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10644                                SDValue SplatVal, unsigned NumVecElts) {
10645   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
10646   unsigned OrigAlignment = St.getAlignment();
10647   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10648 
10649   // Create scalar stores. This is at least as good as the code sequence for a
10650   // split unaligned store which is a dup.s, ext.b, and two stores.
10651   // Most of the time the three stores should be replaced by store pair
10652   // instructions (stp).
10653   SDLoc DL(&St);
10654   SDValue BasePtr = St.getBasePtr();
10655   uint64_t BaseOffset = 0;
10656 
10657   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10658   SDValue NewST1 =
10659       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10660                    OrigAlignment, St.getMemOperand()->getFlags());
10661 
10662   // As this in ISel, we will not merge this add which may degrade results.
10663   if (BasePtr->getOpcode() == ISD::ADD &&
10664       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10665     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10666     BasePtr = BasePtr->getOperand(0);
10667   }
10668 
10669   unsigned Offset = EltOffset;
10670   while (--NumVecElts) {
10671     unsigned Alignment = MinAlign(OrigAlignment, Offset);
10672     SDValue OffsetPtr =
10673         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10674                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10675     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10676                           PtrInfo.getWithOffset(Offset), Alignment,
10677                           St.getMemOperand()->getFlags());
10678     Offset += EltOffset;
10679   }
10680   return NewST1;
10681 }
10682 
10683 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
10684 /// load store optimizer pass will merge them to store pair stores.  This should
10685 /// be better than a movi to create the vector zero followed by a vector store
10686 /// if the zero constant is not re-used, since one instructions and one register
10687 /// live range will be removed.
10688 ///
10689 /// For example, the final generated code should be:
10690 ///
10691 ///   stp xzr, xzr, [x0]
10692 ///
10693 /// instead of:
10694 ///
10695 ///   movi v0.2d, #0
10696 ///   str q0, [x0]
10697 ///
10698 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10699   SDValue StVal = St.getValue();
10700   EVT VT = StVal.getValueType();
10701 
10702   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10703   // 2, 3 or 4 i32 elements.
10704   int NumVecElts = VT.getVectorNumElements();
10705   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10706          VT.getVectorElementType().getSizeInBits() == 64) ||
10707         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10708          VT.getVectorElementType().getSizeInBits() == 32)))
10709     return SDValue();
10710 
10711   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10712     return SDValue();
10713 
10714   // If the zero constant has more than one use then the vector store could be
10715   // better since the constant mov will be amortized and stp q instructions
10716   // should be able to be formed.
10717   if (!StVal.hasOneUse())
10718     return SDValue();
10719 
10720   // If the store is truncating then it's going down to i16 or smaller, which
10721   // means it can be implemented in a single store anyway.
10722   if (St.isTruncatingStore())
10723     return SDValue();
10724 
10725   // If the immediate offset of the address operand is too large for the stp
10726   // instruction, then bail out.
10727   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10728     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10729     if (Offset < -512 || Offset > 504)
10730       return SDValue();
10731   }
10732 
10733   for (int I = 0; I < NumVecElts; ++I) {
10734     SDValue EltVal = StVal.getOperand(I);
10735     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10736       return SDValue();
10737   }
10738 
10739   // Use a CopyFromReg WZR/XZR here to prevent
10740   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10741   SDLoc DL(&St);
10742   unsigned ZeroReg;
10743   EVT ZeroVT;
10744   if (VT.getVectorElementType().getSizeInBits() == 32) {
10745     ZeroReg = AArch64::WZR;
10746     ZeroVT = MVT::i32;
10747   } else {
10748     ZeroReg = AArch64::XZR;
10749     ZeroVT = MVT::i64;
10750   }
10751   SDValue SplatVal =
10752       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10753   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10754 }
10755 
10756 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10757 /// value. The load store optimizer pass will merge them to store pair stores.
10758 /// This has better performance than a splat of the scalar followed by a split
10759 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10760 /// followed by an ext.b and two stores.
10761 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10762   SDValue StVal = St.getValue();
10763   EVT VT = StVal.getValueType();
10764 
10765   // Don't replace floating point stores, they possibly won't be transformed to
10766   // stp because of the store pair suppress pass.
10767   if (VT.isFloatingPoint())
10768     return SDValue();
10769 
10770   // We can express a splat as store pair(s) for 2 or 4 elements.
10771   unsigned NumVecElts = VT.getVectorNumElements();
10772   if (NumVecElts != 4 && NumVecElts != 2)
10773     return SDValue();
10774 
10775   // If the store is truncating then it's going down to i16 or smaller, which
10776   // means it can be implemented in a single store anyway.
10777   if (St.isTruncatingStore())
10778     return SDValue();
10779 
10780   // Check that this is a splat.
10781   // Make sure that each of the relevant vector element locations are inserted
10782   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10783   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10784   SDValue SplatVal;
10785   for (unsigned I = 0; I < NumVecElts; ++I) {
10786     // Check for insert vector elements.
10787     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10788       return SDValue();
10789 
10790     // Check that same value is inserted at each vector element.
10791     if (I == 0)
10792       SplatVal = StVal.getOperand(1);
10793     else if (StVal.getOperand(1) != SplatVal)
10794       return SDValue();
10795 
10796     // Check insert element index.
10797     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10798     if (!CIndex)
10799       return SDValue();
10800     uint64_t IndexVal = CIndex->getZExtValue();
10801     if (IndexVal >= NumVecElts)
10802       return SDValue();
10803     IndexNotInserted.reset(IndexVal);
10804 
10805     StVal = StVal.getOperand(0);
10806   }
10807   // Check that all vector element locations were inserted to.
10808   if (IndexNotInserted.any())
10809       return SDValue();
10810 
10811   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10812 }
10813 
10814 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10815                            SelectionDAG &DAG,
10816                            const AArch64Subtarget *Subtarget) {
10817 
10818   StoreSDNode *S = cast<StoreSDNode>(N);
10819   if (S->isVolatile() || S->isIndexed())
10820     return SDValue();
10821 
10822   SDValue StVal = S->getValue();
10823   EVT VT = StVal.getValueType();
10824   if (!VT.isVector())
10825     return SDValue();
10826 
10827   // If we get a splat of zeros, convert this vector store to a store of
10828   // scalars. They will be merged into store pairs of xzr thereby removing one
10829   // instruction and one register.
10830   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10831     return ReplacedZeroSplat;
10832 
10833   // FIXME: The logic for deciding if an unaligned store should be split should
10834   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10835   // a call to that function here.
10836 
10837   if (!Subtarget->isMisaligned128StoreSlow())
10838     return SDValue();
10839 
10840   // Don't split at -Oz.
10841   if (DAG.getMachineFunction().getFunction().hasMinSize())
10842     return SDValue();
10843 
10844   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10845   // those up regresses performance on micro-benchmarks and olden/bh.
10846   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10847     return SDValue();
10848 
10849   // Split unaligned 16B stores. They are terrible for performance.
10850   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10851   // extensions can use this to mark that it does not want splitting to happen
10852   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10853   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10854   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10855       S->getAlignment() <= 2)
10856     return SDValue();
10857 
10858   // If we get a splat of a scalar convert this vector store to a store of
10859   // scalars. They will be merged into store pairs thereby removing two
10860   // instructions.
10861   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10862     return ReplacedSplat;
10863 
10864   SDLoc DL(S);
10865 
10866   // Split VT into two.
10867   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
10868   unsigned NumElts = HalfVT.getVectorNumElements();
10869   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10870                                    DAG.getConstant(0, DL, MVT::i64));
10871   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10872                                    DAG.getConstant(NumElts, DL, MVT::i64));
10873   SDValue BasePtr = S->getBasePtr();
10874   SDValue NewST1 =
10875       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10876                    S->getAlignment(), S->getMemOperand()->getFlags());
10877   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10878                                   DAG.getConstant(8, DL, MVT::i64));
10879   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10880                       S->getPointerInfo(), S->getAlignment(),
10881                       S->getMemOperand()->getFlags());
10882 }
10883 
10884 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10885 /// post-increment LD1R.
10886 static SDValue performPostLD1Combine(SDNode *N,
10887                                      TargetLowering::DAGCombinerInfo &DCI,
10888                                      bool IsLaneOp) {
10889   if (DCI.isBeforeLegalizeOps())
10890     return SDValue();
10891 
10892   SelectionDAG &DAG = DCI.DAG;
10893   EVT VT = N->getValueType(0);
10894 
10895   unsigned LoadIdx = IsLaneOp ? 1 : 0;
10896   SDNode *LD = N->getOperand(LoadIdx).getNode();
10897   // If it is not LOAD, can not do such combine.
10898   if (LD->getOpcode() != ISD::LOAD)
10899     return SDValue();
10900 
10901   // The vector lane must be a constant in the LD1LANE opcode.
10902   SDValue Lane;
10903   if (IsLaneOp) {
10904     Lane = N->getOperand(2);
10905     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10906     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10907       return SDValue();
10908   }
10909 
10910   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10911   EVT MemVT = LoadSDN->getMemoryVT();
10912   // Check if memory operand is the same type as the vector element.
10913   if (MemVT != VT.getVectorElementType())
10914     return SDValue();
10915 
10916   // Check if there are other uses. If so, do not combine as it will introduce
10917   // an extra load.
10918   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10919        ++UI) {
10920     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10921       continue;
10922     if (*UI != N)
10923       return SDValue();
10924   }
10925 
10926   SDValue Addr = LD->getOperand(1);
10927   SDValue Vector = N->getOperand(0);
10928   // Search for a use of the address operand that is an increment.
10929   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10930        Addr.getNode()->use_end(); UI != UE; ++UI) {
10931     SDNode *User = *UI;
10932     if (User->getOpcode() != ISD::ADD
10933         || UI.getUse().getResNo() != Addr.getResNo())
10934       continue;
10935 
10936     // If the increment is a constant, it must match the memory ref size.
10937     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10938     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10939       uint32_t IncVal = CInc->getZExtValue();
10940       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10941       if (IncVal != NumBytes)
10942         continue;
10943       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10944     }
10945 
10946     // To avoid cycle construction make sure that neither the load nor the add
10947     // are predecessors to each other or the Vector.
10948     SmallPtrSet<const SDNode *, 32> Visited;
10949     SmallVector<const SDNode *, 16> Worklist;
10950     Visited.insert(Addr.getNode());
10951     Worklist.push_back(User);
10952     Worklist.push_back(LD);
10953     Worklist.push_back(Vector.getNode());
10954     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10955         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10956       continue;
10957 
10958     SmallVector<SDValue, 8> Ops;
10959     Ops.push_back(LD->getOperand(0));  // Chain
10960     if (IsLaneOp) {
10961       Ops.push_back(Vector);           // The vector to be inserted
10962       Ops.push_back(Lane);             // The lane to be inserted in the vector
10963     }
10964     Ops.push_back(Addr);
10965     Ops.push_back(Inc);
10966 
10967     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10968     SDVTList SDTys = DAG.getVTList(Tys);
10969     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10970     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10971                                            MemVT,
10972                                            LoadSDN->getMemOperand());
10973 
10974     // Update the uses.
10975     SDValue NewResults[] = {
10976         SDValue(LD, 0),            // The result of load
10977         SDValue(UpdN.getNode(), 2) // Chain
10978     };
10979     DCI.CombineTo(LD, NewResults);
10980     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
10981     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
10982 
10983     break;
10984   }
10985   return SDValue();
10986 }
10987 
10988 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10989 /// address translation.
10990 static bool performTBISimplification(SDValue Addr,
10991                                      TargetLowering::DAGCombinerInfo &DCI,
10992                                      SelectionDAG &DAG) {
10993   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10994   KnownBits Known;
10995   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10996                                         !DCI.isBeforeLegalizeOps());
10997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10998   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10999     DCI.CommitTargetLoweringOpt(TLO);
11000     return true;
11001   }
11002   return false;
11003 }
11004 
11005 static SDValue performSTORECombine(SDNode *N,
11006                                    TargetLowering::DAGCombinerInfo &DCI,
11007                                    SelectionDAG &DAG,
11008                                    const AArch64Subtarget *Subtarget) {
11009   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11010     return Split;
11011 
11012   if (Subtarget->supportsAddressTopByteIgnored() &&
11013       performTBISimplification(N->getOperand(2), DCI, DAG))
11014     return SDValue(N, 0);
11015 
11016   return SDValue();
11017 }
11018 
11019 
11020 /// Target-specific DAG combine function for NEON load/store intrinsics
11021 /// to merge base address updates.
11022 static SDValue performNEONPostLDSTCombine(SDNode *N,
11023                                           TargetLowering::DAGCombinerInfo &DCI,
11024                                           SelectionDAG &DAG) {
11025   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11026     return SDValue();
11027 
11028   unsigned AddrOpIdx = N->getNumOperands() - 1;
11029   SDValue Addr = N->getOperand(AddrOpIdx);
11030 
11031   // Search for a use of the address operand that is an increment.
11032   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11033        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11034     SDNode *User = *UI;
11035     if (User->getOpcode() != ISD::ADD ||
11036         UI.getUse().getResNo() != Addr.getResNo())
11037       continue;
11038 
11039     // Check that the add is independent of the load/store.  Otherwise, folding
11040     // it would create a cycle.
11041     SmallPtrSet<const SDNode *, 32> Visited;
11042     SmallVector<const SDNode *, 16> Worklist;
11043     Visited.insert(Addr.getNode());
11044     Worklist.push_back(N);
11045     Worklist.push_back(User);
11046     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11047         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11048       continue;
11049 
11050     // Find the new opcode for the updating load/store.
11051     bool IsStore = false;
11052     bool IsLaneOp = false;
11053     bool IsDupOp = false;
11054     unsigned NewOpc = 0;
11055     unsigned NumVecs = 0;
11056     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11057     switch (IntNo) {
11058     default: llvm_unreachable("unexpected intrinsic for Neon base update");
11059     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
11060       NumVecs = 2; break;
11061     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
11062       NumVecs = 3; break;
11063     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
11064       NumVecs = 4; break;
11065     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
11066       NumVecs = 2; IsStore = true; break;
11067     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
11068       NumVecs = 3; IsStore = true; break;
11069     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
11070       NumVecs = 4; IsStore = true; break;
11071     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
11072       NumVecs = 2; break;
11073     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
11074       NumVecs = 3; break;
11075     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
11076       NumVecs = 4; break;
11077     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
11078       NumVecs = 2; IsStore = true; break;
11079     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
11080       NumVecs = 3; IsStore = true; break;
11081     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
11082       NumVecs = 4; IsStore = true; break;
11083     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
11084       NumVecs = 2; IsDupOp = true; break;
11085     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
11086       NumVecs = 3; IsDupOp = true; break;
11087     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
11088       NumVecs = 4; IsDupOp = true; break;
11089     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
11090       NumVecs = 2; IsLaneOp = true; break;
11091     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
11092       NumVecs = 3; IsLaneOp = true; break;
11093     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
11094       NumVecs = 4; IsLaneOp = true; break;
11095     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
11096       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
11097     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
11098       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
11099     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
11100       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
11101     }
11102 
11103     EVT VecTy;
11104     if (IsStore)
11105       VecTy = N->getOperand(2).getValueType();
11106     else
11107       VecTy = N->getValueType(0);
11108 
11109     // If the increment is a constant, it must match the memory ref size.
11110     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11111     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11112       uint32_t IncVal = CInc->getZExtValue();
11113       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11114       if (IsLaneOp || IsDupOp)
11115         NumBytes /= VecTy.getVectorNumElements();
11116       if (IncVal != NumBytes)
11117         continue;
11118       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11119     }
11120     SmallVector<SDValue, 8> Ops;
11121     Ops.push_back(N->getOperand(0)); // Incoming chain
11122     // Load lane and store have vector list as input.
11123     if (IsLaneOp || IsStore)
11124       for (unsigned i = 2; i < AddrOpIdx; ++i)
11125         Ops.push_back(N->getOperand(i));
11126     Ops.push_back(Addr); // Base register
11127     Ops.push_back(Inc);
11128 
11129     // Return Types.
11130     EVT Tys[6];
11131     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11132     unsigned n;
11133     for (n = 0; n < NumResultVecs; ++n)
11134       Tys[n] = VecTy;
11135     Tys[n++] = MVT::i64;  // Type of write back register
11136     Tys[n] = MVT::Other;  // Type of the chain
11137     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
11138 
11139     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11140     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11141                                            MemInt->getMemoryVT(),
11142                                            MemInt->getMemOperand());
11143 
11144     // Update the uses.
11145     std::vector<SDValue> NewResults;
11146     for (unsigned i = 0; i < NumResultVecs; ++i) {
11147       NewResults.push_back(SDValue(UpdN.getNode(), i));
11148     }
11149     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11150     DCI.CombineTo(N, NewResults);
11151     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11152 
11153     break;
11154   }
11155   return SDValue();
11156 }
11157 
11158 // Checks to see if the value is the prescribed width and returns information
11159 // about its extension mode.
11160 static
11161 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11162   ExtType = ISD::NON_EXTLOAD;
11163   switch(V.getNode()->getOpcode()) {
11164   default:
11165     return false;
11166   case ISD::LOAD: {
11167     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11168     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11169        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11170       ExtType = LoadNode->getExtensionType();
11171       return true;
11172     }
11173     return false;
11174   }
11175   case ISD::AssertSext: {
11176     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11177     if ((TypeNode->getVT() == MVT::i8 && width == 8)
11178        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11179       ExtType = ISD::SEXTLOAD;
11180       return true;
11181     }
11182     return false;
11183   }
11184   case ISD::AssertZext: {
11185     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11186     if ((TypeNode->getVT() == MVT::i8 && width == 8)
11187        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11188       ExtType = ISD::ZEXTLOAD;
11189       return true;
11190     }
11191     return false;
11192   }
11193   case ISD::Constant:
11194   case ISD::TargetConstant: {
11195     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11196            1LL << (width - 1);
11197   }
11198   }
11199 
11200   return true;
11201 }
11202 
11203 // This function does a whole lot of voodoo to determine if the tests are
11204 // equivalent without and with a mask. Essentially what happens is that given a
11205 // DAG resembling:
11206 //
11207 //  +-------------+ +-------------+ +-------------+ +-------------+
11208 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
11209 //  +-------------+ +-------------+ +-------------+ +-------------+
11210 //           |           |           |               |
11211 //           V           V           |    +----------+
11212 //          +-------------+  +----+  |    |
11213 //          |     ADD     |  |0xff|  |    |
11214 //          +-------------+  +----+  |    |
11215 //                  |           |    |    |
11216 //                  V           V    |    |
11217 //                 +-------------+   |    |
11218 //                 |     AND     |   |    |
11219 //                 +-------------+   |    |
11220 //                      |            |    |
11221 //                      +-----+      |    |
11222 //                            |      |    |
11223 //                            V      V    V
11224 //                           +-------------+
11225 //                           |     CMP     |
11226 //                           +-------------+
11227 //
11228 // The AND node may be safely removed for some combinations of inputs. In
11229 // particular we need to take into account the extension type of the Input,
11230 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
11231 // width of the input (this can work for any width inputs, the above graph is
11232 // specific to 8 bits.
11233 //
11234 // The specific equations were worked out by generating output tables for each
11235 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11236 // problem was simplified by working with 4 bit inputs, which means we only
11237 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11238 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11239 // patterns present in both extensions (0,7). For every distinct set of
11240 // AddConstant and CompConstants bit patterns we can consider the masked and
11241 // unmasked versions to be equivalent if the result of this function is true for
11242 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11243 //
11244 //   sub      w8, w0, w1
11245 //   and      w10, w8, #0x0f
11246 //   cmp      w8, w2
11247 //   cset     w9, AArch64CC
11248 //   cmp      w10, w2
11249 //   cset     w11, AArch64CC
11250 //   cmp      w9, w11
11251 //   cset     w0, eq
11252 //   ret
11253 //
11254 // Since the above function shows when the outputs are equivalent it defines
11255 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11256 // would be expensive to run during compiles. The equations below were written
11257 // in a test harness that confirmed they gave equivalent outputs to the above
11258 // for all inputs function, so they can be used determine if the removal is
11259 // legal instead.
11260 //
11261 // isEquivalentMaskless() is the code for testing if the AND can be removed
11262 // factored out of the DAG recognition as the DAG can take several forms.
11263 
11264 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11265                                  ISD::LoadExtType ExtType, int AddConstant,
11266                                  int CompConstant) {
11267   // By being careful about our equations and only writing the in term
11268   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11269   // make them generally applicable to all bit widths.
11270   int MaxUInt = (1 << width);
11271 
11272   // For the purposes of these comparisons sign extending the type is
11273   // equivalent to zero extending the add and displacing it by half the integer
11274   // width. Provided we are careful and make sure our equations are valid over
11275   // the whole range we can just adjust the input and avoid writing equations
11276   // for sign extended inputs.
11277   if (ExtType == ISD::SEXTLOAD)
11278     AddConstant -= (1 << (width-1));
11279 
11280   switch(CC) {
11281   case AArch64CC::LE:
11282   case AArch64CC::GT:
11283     if ((AddConstant == 0) ||
11284         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11285         (AddConstant >= 0 && CompConstant < 0) ||
11286         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11287       return true;
11288     break;
11289   case AArch64CC::LT:
11290   case AArch64CC::GE:
11291     if ((AddConstant == 0) ||
11292         (AddConstant >= 0 && CompConstant <= 0) ||
11293         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11294       return true;
11295     break;
11296   case AArch64CC::HI:
11297   case AArch64CC::LS:
11298     if ((AddConstant >= 0 && CompConstant < 0) ||
11299        (AddConstant <= 0 && CompConstant >= -1 &&
11300         CompConstant < AddConstant + MaxUInt))
11301       return true;
11302    break;
11303   case AArch64CC::PL:
11304   case AArch64CC::MI:
11305     if ((AddConstant == 0) ||
11306         (AddConstant > 0 && CompConstant <= 0) ||
11307         (AddConstant < 0 && CompConstant <= AddConstant))
11308       return true;
11309     break;
11310   case AArch64CC::LO:
11311   case AArch64CC::HS:
11312     if ((AddConstant >= 0 && CompConstant <= 0) ||
11313         (AddConstant <= 0 && CompConstant >= 0 &&
11314          CompConstant <= AddConstant + MaxUInt))
11315       return true;
11316     break;
11317   case AArch64CC::EQ:
11318   case AArch64CC::NE:
11319     if ((AddConstant > 0 && CompConstant < 0) ||
11320         (AddConstant < 0 && CompConstant >= 0 &&
11321          CompConstant < AddConstant + MaxUInt) ||
11322         (AddConstant >= 0 && CompConstant >= 0 &&
11323          CompConstant >= AddConstant) ||
11324         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11325       return true;
11326     break;
11327   case AArch64CC::VS:
11328   case AArch64CC::VC:
11329   case AArch64CC::AL:
11330   case AArch64CC::NV:
11331     return true;
11332   case AArch64CC::Invalid:
11333     break;
11334   }
11335 
11336   return false;
11337 }
11338 
11339 static
11340 SDValue performCONDCombine(SDNode *N,
11341                            TargetLowering::DAGCombinerInfo &DCI,
11342                            SelectionDAG &DAG, unsigned CCIndex,
11343                            unsigned CmpIndex) {
11344   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11345   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11346   unsigned CondOpcode = SubsNode->getOpcode();
11347 
11348   if (CondOpcode != AArch64ISD::SUBS)
11349     return SDValue();
11350 
11351   // There is a SUBS feeding this condition. Is it fed by a mask we can
11352   // use?
11353 
11354   SDNode *AndNode = SubsNode->getOperand(0).getNode();
11355   unsigned MaskBits = 0;
11356 
11357   if (AndNode->getOpcode() != ISD::AND)
11358     return SDValue();
11359 
11360   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11361     uint32_t CNV = CN->getZExtValue();
11362     if (CNV == 255)
11363       MaskBits = 8;
11364     else if (CNV == 65535)
11365       MaskBits = 16;
11366   }
11367 
11368   if (!MaskBits)
11369     return SDValue();
11370 
11371   SDValue AddValue = AndNode->getOperand(0);
11372 
11373   if (AddValue.getOpcode() != ISD::ADD)
11374     return SDValue();
11375 
11376   // The basic dag structure is correct, grab the inputs and validate them.
11377 
11378   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11379   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11380   SDValue SubsInputValue = SubsNode->getOperand(1);
11381 
11382   // The mask is present and the provenance of all the values is a smaller type,
11383   // lets see if the mask is superfluous.
11384 
11385   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11386       !isa<ConstantSDNode>(SubsInputValue.getNode()))
11387     return SDValue();
11388 
11389   ISD::LoadExtType ExtType;
11390 
11391   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11392       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11393       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11394     return SDValue();
11395 
11396   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11397                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11398                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11399     return SDValue();
11400 
11401   // The AND is not necessary, remove it.
11402 
11403   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11404                                SubsNode->getValueType(1));
11405   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11406 
11407   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11408   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11409 
11410   return SDValue(N, 0);
11411 }
11412 
11413 // Optimize compare with zero and branch.
11414 static SDValue performBRCONDCombine(SDNode *N,
11415                                     TargetLowering::DAGCombinerInfo &DCI,
11416                                     SelectionDAG &DAG) {
11417   MachineFunction &MF = DAG.getMachineFunction();
11418   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11419   // will not be produced, as they are conditional branch instructions that do
11420   // not set flags.
11421   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11422     return SDValue();
11423 
11424   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11425     N = NV.getNode();
11426   SDValue Chain = N->getOperand(0);
11427   SDValue Dest = N->getOperand(1);
11428   SDValue CCVal = N->getOperand(2);
11429   SDValue Cmp = N->getOperand(3);
11430 
11431   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11432   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11433   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11434     return SDValue();
11435 
11436   unsigned CmpOpc = Cmp.getOpcode();
11437   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11438     return SDValue();
11439 
11440   // Only attempt folding if there is only one use of the flag and no use of the
11441   // value.
11442   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11443     return SDValue();
11444 
11445   SDValue LHS = Cmp.getOperand(0);
11446   SDValue RHS = Cmp.getOperand(1);
11447 
11448   assert(LHS.getValueType() == RHS.getValueType() &&
11449          "Expected the value type to be the same for both operands!");
11450   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11451     return SDValue();
11452 
11453   if (isNullConstant(LHS))
11454     std::swap(LHS, RHS);
11455 
11456   if (!isNullConstant(RHS))
11457     return SDValue();
11458 
11459   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11460       LHS.getOpcode() == ISD::SRL)
11461     return SDValue();
11462 
11463   // Fold the compare into the branch instruction.
11464   SDValue BR;
11465   if (CC == AArch64CC::EQ)
11466     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11467   else
11468     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11469 
11470   // Do not add new nodes to DAG combiner worklist.
11471   DCI.CombineTo(N, BR, false);
11472 
11473   return SDValue();
11474 }
11475 
11476 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
11477 // as well as whether the test should be inverted.  This code is required to
11478 // catch these cases (as opposed to standard dag combines) because
11479 // AArch64ISD::TBZ is matched during legalization.
11480 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11481                                  SelectionDAG &DAG) {
11482 
11483   if (!Op->hasOneUse())
11484     return Op;
11485 
11486   // We don't handle undef/constant-fold cases below, as they should have
11487   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11488   // etc.)
11489 
11490   // (tbz (trunc x), b) -> (tbz x, b)
11491   // This case is just here to enable more of the below cases to be caught.
11492   if (Op->getOpcode() == ISD::TRUNCATE &&
11493       Bit < Op->getValueType(0).getSizeInBits()) {
11494     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11495   }
11496 
11497   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11498   if (Op->getOpcode() == ISD::ANY_EXTEND &&
11499       Bit < Op->getOperand(0).getValueSizeInBits()) {
11500     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11501   }
11502 
11503   if (Op->getNumOperands() != 2)
11504     return Op;
11505 
11506   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11507   if (!C)
11508     return Op;
11509 
11510   switch (Op->getOpcode()) {
11511   default:
11512     return Op;
11513 
11514   // (tbz (and x, m), b) -> (tbz x, b)
11515   case ISD::AND:
11516     if ((C->getZExtValue() >> Bit) & 1)
11517       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11518     return Op;
11519 
11520   // (tbz (shl x, c), b) -> (tbz x, b-c)
11521   case ISD::SHL:
11522     if (C->getZExtValue() <= Bit &&
11523         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11524       Bit = Bit - C->getZExtValue();
11525       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11526     }
11527     return Op;
11528 
11529   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11530   case ISD::SRA:
11531     Bit = Bit + C->getZExtValue();
11532     if (Bit >= Op->getValueType(0).getSizeInBits())
11533       Bit = Op->getValueType(0).getSizeInBits() - 1;
11534     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11535 
11536   // (tbz (srl x, c), b) -> (tbz x, b+c)
11537   case ISD::SRL:
11538     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11539       Bit = Bit + C->getZExtValue();
11540       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11541     }
11542     return Op;
11543 
11544   // (tbz (xor x, -1), b) -> (tbnz x, b)
11545   case ISD::XOR:
11546     if ((C->getZExtValue() >> Bit) & 1)
11547       Invert = !Invert;
11548     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11549   }
11550 }
11551 
11552 // Optimize test single bit zero/non-zero and branch.
11553 static SDValue performTBZCombine(SDNode *N,
11554                                  TargetLowering::DAGCombinerInfo &DCI,
11555                                  SelectionDAG &DAG) {
11556   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11557   bool Invert = false;
11558   SDValue TestSrc = N->getOperand(1);
11559   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11560 
11561   if (TestSrc == NewTestSrc)
11562     return SDValue();
11563 
11564   unsigned NewOpc = N->getOpcode();
11565   if (Invert) {
11566     if (NewOpc == AArch64ISD::TBZ)
11567       NewOpc = AArch64ISD::TBNZ;
11568     else {
11569       assert(NewOpc == AArch64ISD::TBNZ);
11570       NewOpc = AArch64ISD::TBZ;
11571     }
11572   }
11573 
11574   SDLoc DL(N);
11575   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11576                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11577 }
11578 
11579 // vselect (v1i1 setcc) ->
11580 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
11581 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11582 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11583 // such VSELECT.
11584 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11585   SDValue N0 = N->getOperand(0);
11586   EVT CCVT = N0.getValueType();
11587 
11588   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11589       CCVT.getVectorElementType() != MVT::i1)
11590     return SDValue();
11591 
11592   EVT ResVT = N->getValueType(0);
11593   EVT CmpVT = N0.getOperand(0).getValueType();
11594   // Only combine when the result type is of the same size as the compared
11595   // operands.
11596   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11597     return SDValue();
11598 
11599   SDValue IfTrue = N->getOperand(1);
11600   SDValue IfFalse = N->getOperand(2);
11601   SDValue SetCC =
11602       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11603                    N0.getOperand(0), N0.getOperand(1),
11604                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
11605   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11606                      IfTrue, IfFalse);
11607 }
11608 
11609 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11610 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11611 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11612 /// with a vector one followed by a DUP shuffle on the result.
11613 static SDValue performSelectCombine(SDNode *N,
11614                                     TargetLowering::DAGCombinerInfo &DCI) {
11615   SelectionDAG &DAG = DCI.DAG;
11616   SDValue N0 = N->getOperand(0);
11617   EVT ResVT = N->getValueType(0);
11618 
11619   if (N0.getOpcode() != ISD::SETCC)
11620     return SDValue();
11621 
11622   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11623   // scalar SetCCResultType. We also don't expect vectors, because we assume
11624   // that selects fed by vector SETCCs are canonicalized to VSELECT.
11625   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11626          "Scalar-SETCC feeding SELECT has unexpected result type!");
11627 
11628   // If NumMaskElts == 0, the comparison is larger than select result. The
11629   // largest real NEON comparison is 64-bits per lane, which means the result is
11630   // at most 32-bits and an illegal vector. Just bail out for now.
11631   EVT SrcVT = N0.getOperand(0).getValueType();
11632 
11633   // Don't try to do this optimization when the setcc itself has i1 operands.
11634   // There are no legal vectors of i1, so this would be pointless.
11635   if (SrcVT == MVT::i1)
11636     return SDValue();
11637 
11638   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
11639   if (!ResVT.isVector() || NumMaskElts == 0)
11640     return SDValue();
11641 
11642   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
11643   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11644 
11645   // Also bail out if the vector CCVT isn't the same size as ResVT.
11646   // This can happen if the SETCC operand size doesn't divide the ResVT size
11647   // (e.g., f64 vs v3f32).
11648   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11649     return SDValue();
11650 
11651   // Make sure we didn't create illegal types, if we're not supposed to.
11652   assert(DCI.isBeforeLegalize() ||
11653          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11654 
11655   // First perform a vector comparison, where lane 0 is the one we're interested
11656   // in.
11657   SDLoc DL(N0);
11658   SDValue LHS =
11659       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11660   SDValue RHS =
11661       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11662   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11663 
11664   // Now duplicate the comparison mask we want across all other lanes.
11665   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11666   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11667   Mask = DAG.getNode(ISD::BITCAST, DL,
11668                      ResVT.changeVectorElementTypeToInteger(), Mask);
11669 
11670   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11671 }
11672 
11673 /// Get rid of unnecessary NVCASTs (that don't change the type).
11674 static SDValue performNVCASTCombine(SDNode *N) {
11675   if (N->getValueType(0) == N->getOperand(0).getValueType())
11676     return N->getOperand(0);
11677 
11678   return SDValue();
11679 }
11680 
11681 // If all users of the globaladdr are of the form (globaladdr + constant), find
11682 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11683 // globaladdr as (globaladdr + constant) - constant.
11684 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11685                                            const AArch64Subtarget *Subtarget,
11686                                            const TargetMachine &TM) {
11687   auto *GN = cast<GlobalAddressSDNode>(N);
11688   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11689       AArch64II::MO_NO_FLAG)
11690     return SDValue();
11691 
11692   uint64_t MinOffset = -1ull;
11693   for (SDNode *N : GN->uses()) {
11694     if (N->getOpcode() != ISD::ADD)
11695       return SDValue();
11696     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11697     if (!C)
11698       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11699     if (!C)
11700       return SDValue();
11701     MinOffset = std::min(MinOffset, C->getZExtValue());
11702   }
11703   uint64_t Offset = MinOffset + GN->getOffset();
11704 
11705   // Require that the new offset is larger than the existing one. Otherwise, we
11706   // can end up oscillating between two possible DAGs, for example,
11707   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11708   if (Offset <= uint64_t(GN->getOffset()))
11709     return SDValue();
11710 
11711   // Check whether folding this offset is legal. It must not go out of bounds of
11712   // the referenced object to avoid violating the code model, and must be
11713   // smaller than 2^21 because this is the largest offset expressible in all
11714   // object formats.
11715   //
11716   // This check also prevents us from folding negative offsets, which will end
11717   // up being treated in the same way as large positive ones. They could also
11718   // cause code model violations, and aren't really common enough to matter.
11719   if (Offset >= (1 << 21))
11720     return SDValue();
11721 
11722   const GlobalValue *GV = GN->getGlobal();
11723   Type *T = GV->getValueType();
11724   if (!T->isSized() ||
11725       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11726     return SDValue();
11727 
11728   SDLoc DL(GN);
11729   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11730   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11731                      DAG.getConstant(MinOffset, DL, MVT::i64));
11732 }
11733 
11734 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11735                                                  DAGCombinerInfo &DCI) const {
11736   SelectionDAG &DAG = DCI.DAG;
11737   switch (N->getOpcode()) {
11738   default:
11739     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11740     break;
11741   case ISD::ADD:
11742   case ISD::SUB:
11743     return performAddSubLongCombine(N, DCI, DAG);
11744   case ISD::XOR:
11745     return performXorCombine(N, DAG, DCI, Subtarget);
11746   case ISD::MUL:
11747     return performMulCombine(N, DAG, DCI, Subtarget);
11748   case ISD::SINT_TO_FP:
11749   case ISD::UINT_TO_FP:
11750     return performIntToFpCombine(N, DAG, Subtarget);
11751   case ISD::FP_TO_SINT:
11752   case ISD::FP_TO_UINT:
11753     return performFpToIntCombine(N, DAG, DCI, Subtarget);
11754   case ISD::FDIV:
11755     return performFDivCombine(N, DAG, DCI, Subtarget);
11756   case ISD::OR:
11757     return performORCombine(N, DCI, Subtarget);
11758   case ISD::AND:
11759     return performANDCombine(N, DCI);
11760   case ISD::SRL:
11761     return performSRLCombine(N, DCI);
11762   case ISD::INTRINSIC_WO_CHAIN:
11763     return performIntrinsicCombine(N, DCI, Subtarget);
11764   case ISD::ANY_EXTEND:
11765   case ISD::ZERO_EXTEND:
11766   case ISD::SIGN_EXTEND:
11767     return performExtendCombine(N, DCI, DAG);
11768   case ISD::BITCAST:
11769     return performBitcastCombine(N, DCI, DAG);
11770   case ISD::CONCAT_VECTORS:
11771     return performConcatVectorsCombine(N, DCI, DAG);
11772   case ISD::SELECT:
11773     return performSelectCombine(N, DCI);
11774   case ISD::VSELECT:
11775     return performVSelectCombine(N, DCI.DAG);
11776   case ISD::LOAD:
11777     if (performTBISimplification(N->getOperand(1), DCI, DAG))
11778       return SDValue(N, 0);
11779     break;
11780   case ISD::STORE:
11781     return performSTORECombine(N, DCI, DAG, Subtarget);
11782   case AArch64ISD::BRCOND:
11783     return performBRCONDCombine(N, DCI, DAG);
11784   case AArch64ISD::TBNZ:
11785   case AArch64ISD::TBZ:
11786     return performTBZCombine(N, DCI, DAG);
11787   case AArch64ISD::CSEL:
11788     return performCONDCombine(N, DCI, DAG, 2, 3);
11789   case AArch64ISD::DUP:
11790     return performPostLD1Combine(N, DCI, false);
11791   case AArch64ISD::NVCAST:
11792     return performNVCASTCombine(N);
11793   case ISD::INSERT_VECTOR_ELT:
11794     return performPostLD1Combine(N, DCI, true);
11795   case ISD::INTRINSIC_VOID:
11796   case ISD::INTRINSIC_W_CHAIN:
11797     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11798     case Intrinsic::aarch64_neon_ld2:
11799     case Intrinsic::aarch64_neon_ld3:
11800     case Intrinsic::aarch64_neon_ld4:
11801     case Intrinsic::aarch64_neon_ld1x2:
11802     case Intrinsic::aarch64_neon_ld1x3:
11803     case Intrinsic::aarch64_neon_ld1x4:
11804     case Intrinsic::aarch64_neon_ld2lane:
11805     case Intrinsic::aarch64_neon_ld3lane:
11806     case Intrinsic::aarch64_neon_ld4lane:
11807     case Intrinsic::aarch64_neon_ld2r:
11808     case Intrinsic::aarch64_neon_ld3r:
11809     case Intrinsic::aarch64_neon_ld4r:
11810     case Intrinsic::aarch64_neon_st2:
11811     case Intrinsic::aarch64_neon_st3:
11812     case Intrinsic::aarch64_neon_st4:
11813     case Intrinsic::aarch64_neon_st1x2:
11814     case Intrinsic::aarch64_neon_st1x3:
11815     case Intrinsic::aarch64_neon_st1x4:
11816     case Intrinsic::aarch64_neon_st2lane:
11817     case Intrinsic::aarch64_neon_st3lane:
11818     case Intrinsic::aarch64_neon_st4lane:
11819       return performNEONPostLDSTCombine(N, DCI, DAG);
11820     default:
11821       break;
11822     }
11823     break;
11824   case ISD::GlobalAddress:
11825     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11826   }
11827   return SDValue();
11828 }
11829 
11830 // Check if the return value is used as only a return value, as otherwise
11831 // we can't perform a tail-call. In particular, we need to check for
11832 // target ISD nodes that are returns and any other "odd" constructs
11833 // that the generic analysis code won't necessarily catch.
11834 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11835                                                SDValue &Chain) const {
11836   if (N->getNumValues() != 1)
11837     return false;
11838   if (!N->hasNUsesOfValue(1, 0))
11839     return false;
11840 
11841   SDValue TCChain = Chain;
11842   SDNode *Copy = *N->use_begin();
11843   if (Copy->getOpcode() == ISD::CopyToReg) {
11844     // If the copy has a glue operand, we conservatively assume it isn't safe to
11845     // perform a tail call.
11846     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11847         MVT::Glue)
11848       return false;
11849     TCChain = Copy->getOperand(0);
11850   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11851     return false;
11852 
11853   bool HasRet = false;
11854   for (SDNode *Node : Copy->uses()) {
11855     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11856       return false;
11857     HasRet = true;
11858   }
11859 
11860   if (!HasRet)
11861     return false;
11862 
11863   Chain = TCChain;
11864   return true;
11865 }
11866 
11867 // Return whether the an instruction can potentially be optimized to a tail
11868 // call. This will cause the optimizers to attempt to move, or duplicate,
11869 // return instructions to help enable tail call optimizations for this
11870 // instruction.
11871 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11872   return CI->isTailCall();
11873 }
11874 
11875 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11876                                                    SDValue &Offset,
11877                                                    ISD::MemIndexedMode &AM,
11878                                                    bool &IsInc,
11879                                                    SelectionDAG &DAG) const {
11880   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11881     return false;
11882 
11883   Base = Op->getOperand(0);
11884   // All of the indexed addressing mode instructions take a signed
11885   // 9 bit immediate offset.
11886   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11887     int64_t RHSC = RHS->getSExtValue();
11888     if (Op->getOpcode() == ISD::SUB)
11889       RHSC = -(uint64_t)RHSC;
11890     if (!isInt<9>(RHSC))
11891       return false;
11892     IsInc = (Op->getOpcode() == ISD::ADD);
11893     Offset = Op->getOperand(1);
11894     return true;
11895   }
11896   return false;
11897 }
11898 
11899 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11900                                                       SDValue &Offset,
11901                                                       ISD::MemIndexedMode &AM,
11902                                                       SelectionDAG &DAG) const {
11903   EVT VT;
11904   SDValue Ptr;
11905   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11906     VT = LD->getMemoryVT();
11907     Ptr = LD->getBasePtr();
11908   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11909     VT = ST->getMemoryVT();
11910     Ptr = ST->getBasePtr();
11911   } else
11912     return false;
11913 
11914   bool IsInc;
11915   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11916     return false;
11917   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11918   return true;
11919 }
11920 
11921 bool AArch64TargetLowering::getPostIndexedAddressParts(
11922     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11923     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11924   EVT VT;
11925   SDValue Ptr;
11926   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11927     VT = LD->getMemoryVT();
11928     Ptr = LD->getBasePtr();
11929   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11930     VT = ST->getMemoryVT();
11931     Ptr = ST->getBasePtr();
11932   } else
11933     return false;
11934 
11935   bool IsInc;
11936   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11937     return false;
11938   // Post-indexing updates the base, so it's not a valid transform
11939   // if that's not the same as the load's pointer.
11940   if (Ptr != Base)
11941     return false;
11942   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11943   return true;
11944 }
11945 
11946 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11947                                   SelectionDAG &DAG) {
11948   SDLoc DL(N);
11949   SDValue Op = N->getOperand(0);
11950 
11951   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11952     return;
11953 
11954   Op = SDValue(
11955       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11956                          DAG.getUNDEF(MVT::i32), Op,
11957                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11958       0);
11959   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11960   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11961 }
11962 
11963 static void ReplaceReductionResults(SDNode *N,
11964                                     SmallVectorImpl<SDValue> &Results,
11965                                     SelectionDAG &DAG, unsigned InterOp,
11966                                     unsigned AcrossOp) {
11967   EVT LoVT, HiVT;
11968   SDValue Lo, Hi;
11969   SDLoc dl(N);
11970   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11971   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11972   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11973   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11974   Results.push_back(SplitVal);
11975 }
11976 
11977 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11978   SDLoc DL(N);
11979   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11980   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11981                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11982                                        DAG.getConstant(64, DL, MVT::i64)));
11983   return std::make_pair(Lo, Hi);
11984 }
11985 
11986 // Create an even/odd pair of X registers holding integer value V.
11987 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11988   SDLoc dl(V.getNode());
11989   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11990   SDValue VHi = DAG.getAnyExtOrTrunc(
11991       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11992       dl, MVT::i64);
11993   if (DAG.getDataLayout().isBigEndian())
11994     std::swap (VLo, VHi);
11995   SDValue RegClass =
11996       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11997   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11998   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11999   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
12000   return SDValue(
12001       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
12002 }
12003 
12004 static void ReplaceCMP_SWAP_128Results(SDNode *N,
12005                                        SmallVectorImpl<SDValue> &Results,
12006                                        SelectionDAG &DAG,
12007                                        const AArch64Subtarget *Subtarget) {
12008   assert(N->getValueType(0) == MVT::i128 &&
12009          "AtomicCmpSwap on types less than 128 should be legal");
12010 
12011   if (Subtarget->hasLSE()) {
12012     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
12013     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
12014     SDValue Ops[] = {
12015         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
12016         createGPRPairNode(DAG, N->getOperand(3)), // Store value
12017         N->getOperand(1), // Ptr
12018         N->getOperand(0), // Chain in
12019     };
12020 
12021     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12022 
12023     unsigned Opcode;
12024     switch (MemOp->getOrdering()) {
12025     case AtomicOrdering::Monotonic:
12026       Opcode = AArch64::CASPX;
12027       break;
12028     case AtomicOrdering::Acquire:
12029       Opcode = AArch64::CASPAX;
12030       break;
12031     case AtomicOrdering::Release:
12032       Opcode = AArch64::CASPLX;
12033       break;
12034     case AtomicOrdering::AcquireRelease:
12035     case AtomicOrdering::SequentiallyConsistent:
12036       Opcode = AArch64::CASPALX;
12037       break;
12038     default:
12039       llvm_unreachable("Unexpected ordering!");
12040     }
12041 
12042     MachineSDNode *CmpSwap = DAG.getMachineNode(
12043         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
12044     DAG.setNodeMemRefs(CmpSwap, {MemOp});
12045 
12046     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
12047     if (DAG.getDataLayout().isBigEndian())
12048       std::swap(SubReg1, SubReg2);
12049     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
12050                                                  SDValue(CmpSwap, 0)));
12051     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
12052                                                  SDValue(CmpSwap, 0)));
12053     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
12054     return;
12055   }
12056 
12057   auto Desired = splitInt128(N->getOperand(2), DAG);
12058   auto New = splitInt128(N->getOperand(3), DAG);
12059   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
12060                    New.first,        New.second,    N->getOperand(0)};
12061   SDNode *CmpSwap = DAG.getMachineNode(
12062       AArch64::CMP_SWAP_128, SDLoc(N),
12063       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
12064 
12065   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12066   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
12067 
12068   Results.push_back(SDValue(CmpSwap, 0));
12069   Results.push_back(SDValue(CmpSwap, 1));
12070   Results.push_back(SDValue(CmpSwap, 3));
12071 }
12072 
12073 void AArch64TargetLowering::ReplaceNodeResults(
12074     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
12075   switch (N->getOpcode()) {
12076   default:
12077     llvm_unreachable("Don't know how to custom expand this");
12078   case ISD::BITCAST:
12079     ReplaceBITCASTResults(N, Results, DAG);
12080     return;
12081   case ISD::VECREDUCE_ADD:
12082   case ISD::VECREDUCE_SMAX:
12083   case ISD::VECREDUCE_SMIN:
12084   case ISD::VECREDUCE_UMAX:
12085   case ISD::VECREDUCE_UMIN:
12086     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
12087     return;
12088 
12089   case AArch64ISD::SADDV:
12090     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
12091     return;
12092   case AArch64ISD::UADDV:
12093     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
12094     return;
12095   case AArch64ISD::SMINV:
12096     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
12097     return;
12098   case AArch64ISD::UMINV:
12099     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
12100     return;
12101   case AArch64ISD::SMAXV:
12102     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
12103     return;
12104   case AArch64ISD::UMAXV:
12105     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
12106     return;
12107   case ISD::FP_TO_UINT:
12108   case ISD::FP_TO_SINT:
12109     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
12110     // Let normal code take care of it by not adding anything to Results.
12111     return;
12112   case ISD::ATOMIC_CMP_SWAP:
12113     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
12114     return;
12115   }
12116 }
12117 
12118 bool AArch64TargetLowering::useLoadStackGuardNode() const {
12119   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
12120     return TargetLowering::useLoadStackGuardNode();
12121   return true;
12122 }
12123 
12124 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
12125   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12126   // reciprocal if there are three or more FDIVs.
12127   return 3;
12128 }
12129 
12130 TargetLoweringBase::LegalizeTypeAction
12131 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
12132   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
12133   // v4i16, v2i32 instead of to promote.
12134   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
12135       VT == MVT::v1f32)
12136     return TypeWidenVector;
12137 
12138   return TargetLoweringBase::getPreferredVectorAction(VT);
12139 }
12140 
12141 // Loads and stores less than 128-bits are already atomic; ones above that
12142 // are doomed anyway, so defer to the default libcall and blame the OS when
12143 // things go wrong.
12144 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12145   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12146   return Size == 128;
12147 }
12148 
12149 // Loads and stores less than 128-bits are already atomic; ones above that
12150 // are doomed anyway, so defer to the default libcall and blame the OS when
12151 // things go wrong.
12152 TargetLowering::AtomicExpansionKind
12153 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12154   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12155   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
12156 }
12157 
12158 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
12159 TargetLowering::AtomicExpansionKind
12160 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12161   if (AI->isFloatingPointOperation())
12162     return AtomicExpansionKind::CmpXChg;
12163 
12164   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12165   if (Size > 128) return AtomicExpansionKind::None;
12166   // Nand not supported in LSE.
12167   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
12168   // Leave 128 bits to LLSC.
12169   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
12170 }
12171 
12172 TargetLowering::AtomicExpansionKind
12173 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
12174     AtomicCmpXchgInst *AI) const {
12175   // If subtarget has LSE, leave cmpxchg intact for codegen.
12176   if (Subtarget->hasLSE())
12177     return AtomicExpansionKind::None;
12178   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12179   // implement cmpxchg without spilling. If the address being exchanged is also
12180   // on the stack and close enough to the spill slot, this can lead to a
12181   // situation where the monitor always gets cleared and the atomic operation
12182   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12183   if (getTargetMachine().getOptLevel() == 0)
12184     return AtomicExpansionKind::None;
12185   return AtomicExpansionKind::LLSC;
12186 }
12187 
12188 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12189                                              AtomicOrdering Ord) const {
12190   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12191   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12192   bool IsAcquire = isAcquireOrStronger(Ord);
12193 
12194   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
12195   // intrinsic must return {i64, i64} and we have to recombine them into a
12196   // single i128 here.
12197   if (ValTy->getPrimitiveSizeInBits() == 128) {
12198     Intrinsic::ID Int =
12199         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
12200     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
12201 
12202     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12203     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
12204 
12205     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12206     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12207     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12208     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12209     return Builder.CreateOr(
12210         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
12211   }
12212 
12213   Type *Tys[] = { Addr->getType() };
12214   Intrinsic::ID Int =
12215       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
12216   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
12217 
12218   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
12219 
12220   const DataLayout &DL = M->getDataLayout();
12221   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
12222   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
12223 
12224   return Builder.CreateBitCast(Trunc, EltTy);
12225 }
12226 
12227 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12228     IRBuilder<> &Builder) const {
12229   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12230   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
12231 }
12232 
12233 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
12234                                                    Value *Val, Value *Addr,
12235                                                    AtomicOrdering Ord) const {
12236   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12237   bool IsRelease = isReleaseOrStronger(Ord);
12238 
12239   // Since the intrinsics must have legal type, the i128 intrinsics take two
12240   // parameters: "i64, i64". We must marshal Val into the appropriate form
12241   // before the call.
12242   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
12243     Intrinsic::ID Int =
12244         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
12245     Function *Stxr = Intrinsic::getDeclaration(M, Int);
12246     Type *Int64Ty = Type::getInt64Ty(M->getContext());
12247 
12248     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
12249     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
12250     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12251     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
12252   }
12253 
12254   Intrinsic::ID Int =
12255       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12256   Type *Tys[] = { Addr->getType() };
12257   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12258 
12259   const DataLayout &DL = M->getDataLayout();
12260   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12261   Val = Builder.CreateBitCast(Val, IntValTy);
12262 
12263   return Builder.CreateCall(Stxr,
12264                             {Builder.CreateZExtOrBitCast(
12265                                  Val, Stxr->getFunctionType()->getParamType(0)),
12266                              Addr});
12267 }
12268 
12269 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12270     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12271   return Ty->isArrayTy();
12272 }
12273 
12274 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12275                                                             EVT) const {
12276   return false;
12277 }
12278 
12279 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
12280   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12281   Function *ThreadPointerFunc =
12282       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
12283   return IRB.CreatePointerCast(
12284       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12285                              Offset),
12286       IRB.getInt8PtrTy()->getPointerTo(0));
12287 }
12288 
12289 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12290   // Android provides a fixed TLS slot for the stack cookie. See the definition
12291   // of TLS_SLOT_STACK_GUARD in
12292   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12293   if (Subtarget->isTargetAndroid())
12294     return UseTlsOffset(IRB, 0x28);
12295 
12296   // Fuchsia is similar.
12297   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
12298   if (Subtarget->isTargetFuchsia())
12299     return UseTlsOffset(IRB, -0x10);
12300 
12301   return TargetLowering::getIRStackGuard(IRB);
12302 }
12303 
12304 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12305   // MSVC CRT provides functionalities for stack protection.
12306   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12307     // MSVC CRT has a global variable holding security cookie.
12308     M.getOrInsertGlobal("__security_cookie",
12309                         Type::getInt8PtrTy(M.getContext()));
12310 
12311     // MSVC CRT has a function to validate security cookie.
12312     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12313         "__security_check_cookie", Type::getVoidTy(M.getContext()),
12314         Type::getInt8PtrTy(M.getContext()));
12315     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12316       F->setCallingConv(CallingConv::Win64);
12317       F->addAttribute(1, Attribute::AttrKind::InReg);
12318     }
12319     return;
12320   }
12321   TargetLowering::insertSSPDeclarations(M);
12322 }
12323 
12324 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12325   // MSVC CRT has a global variable holding security cookie.
12326   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12327     return M.getGlobalVariable("__security_cookie");
12328   return TargetLowering::getSDagStackGuard(M);
12329 }
12330 
12331 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
12332   // MSVC CRT has a function to validate security cookie.
12333   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12334     return M.getFunction("__security_check_cookie");
12335   return TargetLowering::getSSPStackGuardCheck(M);
12336 }
12337 
12338 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
12339   // Android provides a fixed TLS slot for the SafeStack pointer. See the
12340   // definition of TLS_SLOT_SAFESTACK in
12341   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12342   if (Subtarget->isTargetAndroid())
12343     return UseTlsOffset(IRB, 0x48);
12344 
12345   // Fuchsia is similar.
12346   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12347   if (Subtarget->isTargetFuchsia())
12348     return UseTlsOffset(IRB, -0x8);
12349 
12350   return TargetLowering::getSafeStackPointerLocation(IRB);
12351 }
12352 
12353 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12354     const Instruction &AndI) const {
12355   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12356   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
12357   // may be beneficial to sink in other cases, but we would have to check that
12358   // the cmp would not get folded into the br to form a cbz for these to be
12359   // beneficial.
12360   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12361   if (!Mask)
12362     return false;
12363   return Mask->getValue().isPowerOf2();
12364 }
12365 
12366 bool AArch64TargetLowering::
12367     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12368         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12369         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12370         SelectionDAG &DAG) const {
12371   // Does baseline recommend not to perform the fold by default?
12372   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12373           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12374     return false;
12375   // Else, if this is a vector shift, prefer 'shl'.
12376   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12377 }
12378 
12379 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
12380                                               SDNode *N) const {
12381   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
12382       !Subtarget->isTargetWindows())
12383     return false;
12384   return true;
12385 }
12386 
12387 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12388   // Update IsSplitCSR in AArch64unctionInfo.
12389   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12390   AFI->setIsSplitCSR(true);
12391 }
12392 
12393 void AArch64TargetLowering::insertCopiesSplitCSR(
12394     MachineBasicBlock *Entry,
12395     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12396   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12397   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12398   if (!IStart)
12399     return;
12400 
12401   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12402   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12403   MachineBasicBlock::iterator MBBI = Entry->begin();
12404   for (const MCPhysReg *I = IStart; *I; ++I) {
12405     const TargetRegisterClass *RC = nullptr;
12406     if (AArch64::GPR64RegClass.contains(*I))
12407       RC = &AArch64::GPR64RegClass;
12408     else if (AArch64::FPR64RegClass.contains(*I))
12409       RC = &AArch64::FPR64RegClass;
12410     else
12411       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12412 
12413     Register NewVR = MRI->createVirtualRegister(RC);
12414     // Create copy from CSR to a virtual register.
12415     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12416     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12417     // nounwind. If we want to generalize this later, we may need to emit
12418     // CFI pseudo-instructions.
12419     assert(Entry->getParent()->getFunction().hasFnAttribute(
12420                Attribute::NoUnwind) &&
12421            "Function should be nounwind in insertCopiesSplitCSR!");
12422     Entry->addLiveIn(*I);
12423     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12424         .addReg(*I);
12425 
12426     // Insert the copy-back instructions right before the terminator.
12427     for (auto *Exit : Exits)
12428       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12429               TII->get(TargetOpcode::COPY), *I)
12430           .addReg(NewVR);
12431   }
12432 }
12433 
12434 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
12435   // Integer division on AArch64 is expensive. However, when aggressively
12436   // optimizing for code size, we prefer to use a div instruction, as it is
12437   // usually smaller than the alternative sequence.
12438   // The exception to this is vector division. Since AArch64 doesn't have vector
12439   // integer division, leaving the division as-is is a loss even in terms of
12440   // size, because it will have to be scalarized, while the alternative code
12441   // sequence can be performed in vector form.
12442   bool OptSize =
12443       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
12444   return OptSize && !VT.isVector();
12445 }
12446 
12447 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12448   // We want inc-of-add for scalars and sub-of-not for vectors.
12449   return VT.isScalarInteger();
12450 }
12451 
12452 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12453   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12454 }
12455 
12456 unsigned
12457 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
12458   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
12459     return getPointerTy(DL).getSizeInBits();
12460 
12461   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12462 }
12463 
12464 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12465   MF.getFrameInfo().computeMaxCallFrameSize(MF);
12466   TargetLoweringBase::finalizeLowering(MF);
12467 }
12468 
12469 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12470 bool AArch64TargetLowering::needsFixedCatchObjects() const {
12471   return false;
12472 }
12473