1 //===- ARMISelLowering.cpp - ARM 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 defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/IntrinsicsARM.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MachineValueType.h"
101 #include "llvm/Support/MathExtras.h"
102 #include "llvm/Support/raw_ostream.h"
103 #include "llvm/Target/TargetMachine.h"
104 #include "llvm/Target/TargetOptions.h"
105 #include <algorithm>
106 #include <cassert>
107 #include <cstdint>
108 #include <cstdlib>
109 #include <iterator>
110 #include <limits>
111 #include <string>
112 #include <tuple>
113 #include <utility>
114 #include <vector>
115 
116 using namespace llvm;
117 using namespace llvm::PatternMatch;
118 
119 #define DEBUG_TYPE "arm-isel"
120 
121 STATISTIC(NumTailCalls, "Number of tail calls");
122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124 STATISTIC(NumConstpoolPromoted,
125   "Number of constants with their storage promoted into constant pools");
126 
127 static cl::opt<bool>
128 ARMInterworking("arm-interworking", cl::Hidden,
129   cl::desc("Enable / disable ARM interworking (for debugging only)"),
130   cl::init(true));
131 
132 static cl::opt<bool> EnableConstpoolPromotion(
133     "arm-promote-constant", cl::Hidden,
134     cl::desc("Enable / disable promotion of unnamed_addr constants into "
135              "constant pools"),
136     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
138     "arm-promote-constant-max-size", cl::Hidden,
139     cl::desc("Maximum size of constant to promote into a constant pool"),
140     cl::init(64));
141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
142     "arm-promote-constant-max-total", cl::Hidden,
143     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144     cl::init(128));
145 
146 cl::opt<unsigned>
147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148   cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149   cl::init(2));
150 
151 // The APCS parameter registers.
152 static const MCPhysReg GPRArgRegs[] = {
153   ARM::R0, ARM::R1, ARM::R2, ARM::R3
154 };
155 
156 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
157                                        MVT PromotedBitwiseVT) {
158   if (VT != PromotedLdStVT) {
159     setOperationAction(ISD::LOAD, VT, Promote);
160     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
161 
162     setOperationAction(ISD::STORE, VT, Promote);
163     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
164   }
165 
166   MVT ElemTy = VT.getVectorElementType();
167   if (ElemTy != MVT::f64)
168     setOperationAction(ISD::SETCC, VT, Custom);
169   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
170   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
171   if (ElemTy == MVT::i32) {
172     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
173     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
174     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
175     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
176   } else {
177     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
178     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
179     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
180     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
181   }
182   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
183   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
184   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
185   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
186   setOperationAction(ISD::SELECT,            VT, Expand);
187   setOperationAction(ISD::SELECT_CC,         VT, Expand);
188   setOperationAction(ISD::VSELECT,           VT, Expand);
189   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
190   if (VT.isInteger()) {
191     setOperationAction(ISD::SHL, VT, Custom);
192     setOperationAction(ISD::SRA, VT, Custom);
193     setOperationAction(ISD::SRL, VT, Custom);
194   }
195 
196   // Promote all bit-wise operations.
197   if (VT.isInteger() && VT != PromotedBitwiseVT) {
198     setOperationAction(ISD::AND, VT, Promote);
199     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
200     setOperationAction(ISD::OR,  VT, Promote);
201     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
202     setOperationAction(ISD::XOR, VT, Promote);
203     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
204   }
205 
206   // Neon does not support vector divide/remainder operations.
207   setOperationAction(ISD::SDIV, VT, Expand);
208   setOperationAction(ISD::UDIV, VT, Expand);
209   setOperationAction(ISD::FDIV, VT, Expand);
210   setOperationAction(ISD::SREM, VT, Expand);
211   setOperationAction(ISD::UREM, VT, Expand);
212   setOperationAction(ISD::FREM, VT, Expand);
213   setOperationAction(ISD::SDIVREM, VT, Expand);
214   setOperationAction(ISD::UDIVREM, VT, Expand);
215 
216   if (!VT.isFloatingPoint() &&
217       VT != MVT::v2i64 && VT != MVT::v1i64)
218     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
219       setOperationAction(Opcode, VT, Legal);
220   if (!VT.isFloatingPoint())
221     for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
222       setOperationAction(Opcode, VT, Legal);
223 }
224 
225 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
226   addRegisterClass(VT, &ARM::DPRRegClass);
227   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
228 }
229 
230 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
231   addRegisterClass(VT, &ARM::DPairRegClass);
232   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
233 }
234 
235 void ARMTargetLowering::setAllExpand(MVT VT) {
236   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
237     setOperationAction(Opc, VT, Expand);
238 
239   // We support these really simple operations even on types where all
240   // the actual arithmetic has to be broken down into simpler
241   // operations or turned into library calls.
242   setOperationAction(ISD::BITCAST, VT, Legal);
243   setOperationAction(ISD::LOAD, VT, Legal);
244   setOperationAction(ISD::STORE, VT, Legal);
245   setOperationAction(ISD::UNDEF, VT, Legal);
246 }
247 
248 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
249                                        LegalizeAction Action) {
250   setLoadExtAction(ISD::EXTLOAD,  From, To, Action);
251   setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
252   setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
253 }
254 
255 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
256   const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
257 
258   for (auto VT : IntTypes) {
259     addRegisterClass(VT, &ARM::MQPRRegClass);
260     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
261     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
262     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
263     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
264     setOperationAction(ISD::SHL, VT, Custom);
265     setOperationAction(ISD::SRA, VT, Custom);
266     setOperationAction(ISD::SRL, VT, Custom);
267     setOperationAction(ISD::SMIN, VT, Legal);
268     setOperationAction(ISD::SMAX, VT, Legal);
269     setOperationAction(ISD::UMIN, VT, Legal);
270     setOperationAction(ISD::UMAX, VT, Legal);
271     setOperationAction(ISD::ABS, VT, Legal);
272     setOperationAction(ISD::SETCC, VT, Custom);
273     setOperationAction(ISD::MLOAD, VT, Custom);
274     setOperationAction(ISD::MSTORE, VT, Legal);
275     setOperationAction(ISD::CTLZ, VT, Legal);
276     setOperationAction(ISD::CTTZ, VT, Custom);
277     setOperationAction(ISD::BITREVERSE, VT, Legal);
278     setOperationAction(ISD::BSWAP, VT, Legal);
279     setOperationAction(ISD::SADDSAT, VT, Legal);
280     setOperationAction(ISD::UADDSAT, VT, Legal);
281     setOperationAction(ISD::SSUBSAT, VT, Legal);
282     setOperationAction(ISD::USUBSAT, VT, Legal);
283 
284     // No native support for these.
285     setOperationAction(ISD::UDIV, VT, Expand);
286     setOperationAction(ISD::SDIV, VT, Expand);
287     setOperationAction(ISD::UREM, VT, Expand);
288     setOperationAction(ISD::SREM, VT, Expand);
289     setOperationAction(ISD::UDIVREM, VT, Expand);
290     setOperationAction(ISD::SDIVREM, VT, Expand);
291     setOperationAction(ISD::CTPOP, VT, Expand);
292     setOperationAction(ISD::SELECT, VT, Expand);
293     setOperationAction(ISD::SELECT_CC, VT, Expand);
294 
295     // Vector reductions
296     setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
297     setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
298     setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
299     setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
300     setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
301     setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
302     setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
303     setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
304     setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
305 
306     if (!HasMVEFP) {
307       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
308       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
309       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
310       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
311     }
312 
313     // Pre and Post inc are supported on loads and stores
314     for (unsigned im = (unsigned)ISD::PRE_INC;
315          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
316       setIndexedLoadAction(im, VT, Legal);
317       setIndexedStoreAction(im, VT, Legal);
318       setIndexedMaskedLoadAction(im, VT, Legal);
319       setIndexedMaskedStoreAction(im, VT, Legal);
320     }
321   }
322 
323   const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
324   for (auto VT : FloatTypes) {
325     addRegisterClass(VT, &ARM::MQPRRegClass);
326     if (!HasMVEFP)
327       setAllExpand(VT);
328 
329     // These are legal or custom whether we have MVE.fp or not
330     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
331     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
332     setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
333     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
334     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
335     setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
336     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
337     setOperationAction(ISD::SETCC, VT, Custom);
338     setOperationAction(ISD::MLOAD, VT, Custom);
339     setOperationAction(ISD::MSTORE, VT, Legal);
340     setOperationAction(ISD::SELECT, VT, Expand);
341     setOperationAction(ISD::SELECT_CC, VT, Expand);
342 
343     // Pre and Post inc are supported on loads and stores
344     for (unsigned im = (unsigned)ISD::PRE_INC;
345          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
346       setIndexedLoadAction(im, VT, Legal);
347       setIndexedStoreAction(im, VT, Legal);
348       setIndexedMaskedLoadAction(im, VT, Legal);
349       setIndexedMaskedStoreAction(im, VT, Legal);
350     }
351 
352     if (HasMVEFP) {
353       setOperationAction(ISD::FMINNUM, VT, Legal);
354       setOperationAction(ISD::FMAXNUM, VT, Legal);
355       setOperationAction(ISD::FROUND, VT, Legal);
356       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
357       setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
358       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
359       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
360 
361       // No native support for these.
362       setOperationAction(ISD::FDIV, VT, Expand);
363       setOperationAction(ISD::FREM, VT, Expand);
364       setOperationAction(ISD::FSQRT, VT, Expand);
365       setOperationAction(ISD::FSIN, VT, Expand);
366       setOperationAction(ISD::FCOS, VT, Expand);
367       setOperationAction(ISD::FPOW, VT, Expand);
368       setOperationAction(ISD::FLOG, VT, Expand);
369       setOperationAction(ISD::FLOG2, VT, Expand);
370       setOperationAction(ISD::FLOG10, VT, Expand);
371       setOperationAction(ISD::FEXP, VT, Expand);
372       setOperationAction(ISD::FEXP2, VT, Expand);
373       setOperationAction(ISD::FNEARBYINT, VT, Expand);
374     }
375   }
376 
377   // Custom Expand smaller than legal vector reductions to prevent false zero
378   // items being added.
379   setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
380   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
381   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
382   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
383   setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
384   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
385   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
386   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
387 
388   // We 'support' these types up to bitcast/load/store level, regardless of
389   // MVE integer-only / float support. Only doing FP data processing on the FP
390   // vector types is inhibited at integer-only level.
391   const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
392   for (auto VT : LongTypes) {
393     addRegisterClass(VT, &ARM::MQPRRegClass);
394     setAllExpand(VT);
395     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
397     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
398   }
399   // We can do bitwise operations on v2i64 vectors
400   setOperationAction(ISD::AND, MVT::v2i64, Legal);
401   setOperationAction(ISD::OR, MVT::v2i64, Legal);
402   setOperationAction(ISD::XOR, MVT::v2i64, Legal);
403 
404   // It is legal to extload from v4i8 to v4i16 or v4i32.
405   addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
406   addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
407   addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
408 
409   // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
410   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
411   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
412   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
413   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
414   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
415 
416   // Some truncating stores are legal too.
417   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
418   setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
419   setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
420 
421   // Pre and Post inc on these are legal, given the correct extends
422   for (unsigned im = (unsigned)ISD::PRE_INC;
423        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
424     for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
425       setIndexedLoadAction(im, VT, Legal);
426       setIndexedStoreAction(im, VT, Legal);
427       setIndexedMaskedLoadAction(im, VT, Legal);
428       setIndexedMaskedStoreAction(im, VT, Legal);
429     }
430   }
431 
432   // Predicate types
433   const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
434   for (auto VT : pTypes) {
435     addRegisterClass(VT, &ARM::VCCRRegClass);
436     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
437     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
438     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
439     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
440     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
441     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
442     setOperationAction(ISD::SETCC, VT, Custom);
443     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
444     setOperationAction(ISD::LOAD, VT, Custom);
445     setOperationAction(ISD::STORE, VT, Custom);
446     setOperationAction(ISD::TRUNCATE, VT, Custom);
447   }
448 }
449 
450 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
451                                      const ARMSubtarget &STI)
452     : TargetLowering(TM), Subtarget(&STI) {
453   RegInfo = Subtarget->getRegisterInfo();
454   Itins = Subtarget->getInstrItineraryData();
455 
456   setBooleanContents(ZeroOrOneBooleanContent);
457   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
458 
459   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
460       !Subtarget->isTargetWatchOS()) {
461     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
462     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
463       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
464                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
465                                        : CallingConv::ARM_AAPCS);
466   }
467 
468   if (Subtarget->isTargetMachO()) {
469     // Uses VFP for Thumb libfuncs if available.
470     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
471         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
472       static const struct {
473         const RTLIB::Libcall Op;
474         const char * const Name;
475         const ISD::CondCode Cond;
476       } LibraryCalls[] = {
477         // Single-precision floating-point arithmetic.
478         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
479         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
480         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
481         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
482 
483         // Double-precision floating-point arithmetic.
484         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
485         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
486         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
487         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
488 
489         // Single-precision comparisons.
490         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
491         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
492         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
493         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
494         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
495         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
496         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
497 
498         // Double-precision comparisons.
499         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
500         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
501         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
502         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
503         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
504         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
505         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
506 
507         // Floating-point to integer conversions.
508         // i64 conversions are done via library routines even when generating VFP
509         // instructions, so use the same ones.
510         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
511         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
512         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
513         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
514 
515         // Conversions between floating types.
516         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
517         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
518 
519         // Integer to floating-point conversions.
520         // i64 conversions are done via library routines even when generating VFP
521         // instructions, so use the same ones.
522         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
523         // e.g., __floatunsidf vs. __floatunssidfvfp.
524         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
525         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
526         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
527         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
528       };
529 
530       for (const auto &LC : LibraryCalls) {
531         setLibcallName(LC.Op, LC.Name);
532         if (LC.Cond != ISD::SETCC_INVALID)
533           setCmpLibcallCC(LC.Op, LC.Cond);
534       }
535     }
536   }
537 
538   // These libcalls are not available in 32-bit.
539   setLibcallName(RTLIB::SHL_I128, nullptr);
540   setLibcallName(RTLIB::SRL_I128, nullptr);
541   setLibcallName(RTLIB::SRA_I128, nullptr);
542 
543   // RTLIB
544   if (Subtarget->isAAPCS_ABI() &&
545       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
546        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
547     static const struct {
548       const RTLIB::Libcall Op;
549       const char * const Name;
550       const CallingConv::ID CC;
551       const ISD::CondCode Cond;
552     } LibraryCalls[] = {
553       // Double-precision floating-point arithmetic helper functions
554       // RTABI chapter 4.1.2, Table 2
555       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
556       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
559 
560       // Double-precision floating-point comparison helper functions
561       // RTABI chapter 4.1.2, Table 3
562       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
563       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
564       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
565       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
566       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
567       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
568       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
569 
570       // Single-precision floating-point arithmetic helper functions
571       // RTABI chapter 4.1.2, Table 4
572       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
573       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
575       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
576 
577       // Single-precision floating-point comparison helper functions
578       // RTABI chapter 4.1.2, Table 5
579       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
580       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
581       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
582       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
583       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
584       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
585       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
586 
587       // Floating-point to integer conversions.
588       // RTABI chapter 4.1.2, Table 6
589       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
594       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
595       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
596       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
597 
598       // Conversions between floating types.
599       // RTABI chapter 4.1.2, Table 7
600       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
601       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603 
604       // Integer to floating-point conversions.
605       // RTABI chapter 4.1.2, Table 8
606       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
607       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
608       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
611       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
612       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
614 
615       // Long long helper functions
616       // RTABI chapter 4.2, Table 9
617       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
618       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
619       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
620       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
621 
622       // Integer division functions
623       // RTABI chapter 4.3.1
624       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
628       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
629       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
630       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
631       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
632     };
633 
634     for (const auto &LC : LibraryCalls) {
635       setLibcallName(LC.Op, LC.Name);
636       setLibcallCallingConv(LC.Op, LC.CC);
637       if (LC.Cond != ISD::SETCC_INVALID)
638         setCmpLibcallCC(LC.Op, LC.Cond);
639     }
640 
641     // EABI dependent RTLIB
642     if (TM.Options.EABIVersion == EABI::EABI4 ||
643         TM.Options.EABIVersion == EABI::EABI5) {
644       static const struct {
645         const RTLIB::Libcall Op;
646         const char *const Name;
647         const CallingConv::ID CC;
648         const ISD::CondCode Cond;
649       } MemOpsLibraryCalls[] = {
650         // Memory operations
651         // RTABI chapter 4.3.4
652         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
653         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
654         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
655       };
656 
657       for (const auto &LC : MemOpsLibraryCalls) {
658         setLibcallName(LC.Op, LC.Name);
659         setLibcallCallingConv(LC.Op, LC.CC);
660         if (LC.Cond != ISD::SETCC_INVALID)
661           setCmpLibcallCC(LC.Op, LC.Cond);
662       }
663     }
664   }
665 
666   if (Subtarget->isTargetWindows()) {
667     static const struct {
668       const RTLIB::Libcall Op;
669       const char * const Name;
670       const CallingConv::ID CC;
671     } LibraryCalls[] = {
672       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
673       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
674       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
675       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
676       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
677       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
678       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
679       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
680     };
681 
682     for (const auto &LC : LibraryCalls) {
683       setLibcallName(LC.Op, LC.Name);
684       setLibcallCallingConv(LC.Op, LC.CC);
685     }
686   }
687 
688   // Use divmod compiler-rt calls for iOS 5.0 and later.
689   if (Subtarget->isTargetMachO() &&
690       !(Subtarget->isTargetIOS() &&
691         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
692     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
693     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
694   }
695 
696   // The half <-> float conversion functions are always soft-float on
697   // non-watchos platforms, but are needed for some targets which use a
698   // hard-float calling convention by default.
699   if (!Subtarget->isTargetWatchABI()) {
700     if (Subtarget->isAAPCS_ABI()) {
701       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
702       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
703       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
704     } else {
705       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
706       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
707       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
708     }
709   }
710 
711   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
712   // a __gnu_ prefix (which is the default).
713   if (Subtarget->isTargetAEABI()) {
714     static const struct {
715       const RTLIB::Libcall Op;
716       const char * const Name;
717       const CallingConv::ID CC;
718     } LibraryCalls[] = {
719       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
720       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
721       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
722     };
723 
724     for (const auto &LC : LibraryCalls) {
725       setLibcallName(LC.Op, LC.Name);
726       setLibcallCallingConv(LC.Op, LC.CC);
727     }
728   }
729 
730   if (Subtarget->isThumb1Only())
731     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
732   else
733     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
734 
735   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
736       Subtarget->hasFPRegs()) {
737     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
738     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
739     if (!Subtarget->hasVFP2Base())
740       setAllExpand(MVT::f32);
741     if (!Subtarget->hasFP64())
742       setAllExpand(MVT::f64);
743   }
744 
745   if (Subtarget->hasFullFP16()) {
746     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
747     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
748     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
749 
750     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
751     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
752   }
753 
754   if (Subtarget->hasBF16()) {
755     addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
756     setAllExpand(MVT::bf16);
757     if (!Subtarget->hasFullFP16())
758       setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
759   }
760 
761   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
762     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
763       setTruncStoreAction(VT, InnerVT, Expand);
764       addAllExtLoads(VT, InnerVT, Expand);
765     }
766 
767     setOperationAction(ISD::MULHS, VT, Expand);
768     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
769     setOperationAction(ISD::MULHU, VT, Expand);
770     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
771 
772     setOperationAction(ISD::BSWAP, VT, Expand);
773   }
774 
775   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
776   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
777 
778   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
779   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
780 
781   if (Subtarget->hasMVEIntegerOps())
782     addMVEVectorTypes(Subtarget->hasMVEFloatOps());
783 
784   // Combine low-overhead loop intrinsics so that we can lower i1 types.
785   if (Subtarget->hasLOB()) {
786     setTargetDAGCombine(ISD::BRCOND);
787     setTargetDAGCombine(ISD::BR_CC);
788   }
789 
790   if (Subtarget->hasNEON()) {
791     addDRTypeForNEON(MVT::v2f32);
792     addDRTypeForNEON(MVT::v8i8);
793     addDRTypeForNEON(MVT::v4i16);
794     addDRTypeForNEON(MVT::v2i32);
795     addDRTypeForNEON(MVT::v1i64);
796 
797     addQRTypeForNEON(MVT::v4f32);
798     addQRTypeForNEON(MVT::v2f64);
799     addQRTypeForNEON(MVT::v16i8);
800     addQRTypeForNEON(MVT::v8i16);
801     addQRTypeForNEON(MVT::v4i32);
802     addQRTypeForNEON(MVT::v2i64);
803 
804     if (Subtarget->hasFullFP16()) {
805       addQRTypeForNEON(MVT::v8f16);
806       addDRTypeForNEON(MVT::v4f16);
807     }
808 
809     if (Subtarget->hasBF16()) {
810       addQRTypeForNEON(MVT::v8bf16);
811       addDRTypeForNEON(MVT::v4bf16);
812     }
813   }
814 
815   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
816     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
817     // none of Neon, MVE or VFP supports any arithmetic operations on it.
818     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
819     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
820     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
821     // FIXME: Code duplication: FDIV and FREM are expanded always, see
822     // ARMTargetLowering::addTypeForNEON method for details.
823     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
824     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
825     // FIXME: Create unittest.
826     // In another words, find a way when "copysign" appears in DAG with vector
827     // operands.
828     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
829     // FIXME: Code duplication: SETCC has custom operation action, see
830     // ARMTargetLowering::addTypeForNEON method for details.
831     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
832     // FIXME: Create unittest for FNEG and for FABS.
833     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
834     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
835     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
836     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
837     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
838     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
839     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
840     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
841     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
842     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
843     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
844     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
845     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
846     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
847     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
848     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
849     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
850     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
851   }
852 
853   if (Subtarget->hasNEON()) {
854     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
855     // supported for v4f32.
856     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
857     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
858     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
859     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
860     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
861     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
862     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
863     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
864     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
865     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
866     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
867     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
868     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
869     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
870 
871     // Mark v2f32 intrinsics.
872     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
873     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
874     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
875     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
876     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
877     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
878     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
879     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
880     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
881     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
882     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
883     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
884     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
885     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
886 
887     // Neon does not support some operations on v1i64 and v2i64 types.
888     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
889     // Custom handling for some quad-vector types to detect VMULL.
890     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
891     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
892     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
893     // Custom handling for some vector types to avoid expensive expansions
894     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
895     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
896     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
897     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
898     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
899     // a destination type that is wider than the source, and nor does
900     // it have a FP_TO_[SU]INT instruction with a narrower destination than
901     // source.
902     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
903     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
904     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
905     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
906     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
907     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
908     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
909     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
910 
911     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
912     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
913 
914     // NEON does not have single instruction CTPOP for vectors with element
915     // types wider than 8-bits.  However, custom lowering can leverage the
916     // v8i8/v16i8 vcnt instruction.
917     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
918     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
919     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
920     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
921     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
922     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
923 
924     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
925     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
926 
927     // NEON does not have single instruction CTTZ for vectors.
928     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
929     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
930     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
931     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
932 
933     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
934     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
935     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
936     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
937 
938     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
939     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
940     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
941     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
942 
943     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
944     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
945     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
946     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
947 
948     // NEON only has FMA instructions as of VFP4.
949     if (!Subtarget->hasVFP4Base()) {
950       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
951       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
952     }
953 
954     setTargetDAGCombine(ISD::SHL);
955     setTargetDAGCombine(ISD::SRL);
956     setTargetDAGCombine(ISD::SRA);
957     setTargetDAGCombine(ISD::FP_TO_SINT);
958     setTargetDAGCombine(ISD::FP_TO_UINT);
959     setTargetDAGCombine(ISD::FDIV);
960     setTargetDAGCombine(ISD::LOAD);
961 
962     // It is legal to extload from v4i8 to v4i16 or v4i32.
963     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
964                    MVT::v2i32}) {
965       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
966         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
967         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
968         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
969       }
970     }
971   }
972 
973   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
974     setTargetDAGCombine(ISD::BUILD_VECTOR);
975     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
976     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
977     setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
978     setTargetDAGCombine(ISD::STORE);
979     setTargetDAGCombine(ISD::SIGN_EXTEND);
980     setTargetDAGCombine(ISD::ZERO_EXTEND);
981     setTargetDAGCombine(ISD::ANY_EXTEND);
982     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
983     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
984     setTargetDAGCombine(ISD::INTRINSIC_VOID);
985     setTargetDAGCombine(ISD::VECREDUCE_ADD);
986     setTargetDAGCombine(ISD::ADD);
987     setTargetDAGCombine(ISD::BITCAST);
988   }
989   if (Subtarget->hasMVEIntegerOps()) {
990     setTargetDAGCombine(ISD::SMIN);
991     setTargetDAGCombine(ISD::UMIN);
992     setTargetDAGCombine(ISD::SMAX);
993     setTargetDAGCombine(ISD::UMAX);
994     setTargetDAGCombine(ISD::FP_EXTEND);
995     setTargetDAGCombine(ISD::SELECT);
996     setTargetDAGCombine(ISD::SELECT_CC);
997   }
998 
999   if (!Subtarget->hasFP64()) {
1000     // When targeting a floating-point unit with only single-precision
1001     // operations, f64 is legal for the few double-precision instructions which
1002     // are present However, no double-precision operations other than moves,
1003     // loads and stores are provided by the hardware.
1004     setOperationAction(ISD::FADD,       MVT::f64, Expand);
1005     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
1006     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
1007     setOperationAction(ISD::FMA,        MVT::f64, Expand);
1008     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
1009     setOperationAction(ISD::FREM,       MVT::f64, Expand);
1010     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
1011     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
1012     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
1013     setOperationAction(ISD::FABS,       MVT::f64, Expand);
1014     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
1015     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
1016     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
1017     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
1018     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
1019     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
1020     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
1021     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
1022     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
1023     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
1024     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
1025     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
1026     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1027     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
1028     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1029     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1030     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1031     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1032     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1033     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1034     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
1035     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1036     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1037     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1038     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1039     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
1040   }
1041 
1042   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1043     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
1044     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1045     if (Subtarget->hasFullFP16()) {
1046       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
1047       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1048     }
1049   }
1050 
1051   if (!Subtarget->hasFP16()) {
1052     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1053     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1054   }
1055 
1056   computeRegisterProperties(Subtarget->getRegisterInfo());
1057 
1058   // ARM does not have floating-point extending loads.
1059   for (MVT VT : MVT::fp_valuetypes()) {
1060     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1061     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1062   }
1063 
1064   // ... or truncating stores
1065   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1066   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1067   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1068 
1069   // ARM does not have i1 sign extending load.
1070   for (MVT VT : MVT::integer_valuetypes())
1071     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1072 
1073   // ARM supports all 4 flavors of integer indexed load / store.
1074   if (!Subtarget->isThumb1Only()) {
1075     for (unsigned im = (unsigned)ISD::PRE_INC;
1076          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1077       setIndexedLoadAction(im,  MVT::i1,  Legal);
1078       setIndexedLoadAction(im,  MVT::i8,  Legal);
1079       setIndexedLoadAction(im,  MVT::i16, Legal);
1080       setIndexedLoadAction(im,  MVT::i32, Legal);
1081       setIndexedStoreAction(im, MVT::i1,  Legal);
1082       setIndexedStoreAction(im, MVT::i8,  Legal);
1083       setIndexedStoreAction(im, MVT::i16, Legal);
1084       setIndexedStoreAction(im, MVT::i32, Legal);
1085     }
1086   } else {
1087     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1088     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1089     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1090   }
1091 
1092   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1093   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1094   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1095   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1096 
1097   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1098   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1099   if (Subtarget->hasDSP()) {
1100     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1101     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1102     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1103     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1104   }
1105   if (Subtarget->hasBaseDSP()) {
1106     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1107     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1108   }
1109 
1110   // i64 operation support.
1111   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1112   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1113   if (Subtarget->isThumb1Only()) {
1114     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1115     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1116   }
1117   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1118       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1119     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1120 
1121   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1122   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1123   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1124   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1125   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1126   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1127   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1128   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1129   setOperationAction(ISD::STORE, MVT::i64, Custom);
1130 
1131   // MVE lowers 64 bit shifts to lsll and lsrl
1132   // assuming that ISD::SRL and SRA of i64 are already marked custom
1133   if (Subtarget->hasMVEIntegerOps())
1134     setOperationAction(ISD::SHL, MVT::i64, Custom);
1135 
1136   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1137   if (Subtarget->isThumb1Only()) {
1138     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1139     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1140     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1141   }
1142 
1143   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1144     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1145 
1146   // ARM does not have ROTL.
1147   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1148   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1149     setOperationAction(ISD::ROTL, VT, Expand);
1150     setOperationAction(ISD::ROTR, VT, Expand);
1151   }
1152   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1153   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1154   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1155     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1156     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1157   }
1158 
1159   // @llvm.readcyclecounter requires the Performance Monitors extension.
1160   // Default to the 0 expansion on unsupported platforms.
1161   // FIXME: Technically there are older ARM CPUs that have
1162   // implementation-specific ways of obtaining this information.
1163   if (Subtarget->hasPerfMon())
1164     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1165 
1166   // Only ARMv6 has BSWAP.
1167   if (!Subtarget->hasV6Ops())
1168     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1169 
1170   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1171                                         : Subtarget->hasDivideInARMMode();
1172   if (!hasDivide) {
1173     // These are expanded into libcalls if the cpu doesn't have HW divider.
1174     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1175     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1176   }
1177 
1178   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1179     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1180     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1181 
1182     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1183     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1184   }
1185 
1186   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1187   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1188 
1189   // Register based DivRem for AEABI (RTABI 4.2)
1190   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1191       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1192       Subtarget->isTargetWindows()) {
1193     setOperationAction(ISD::SREM, MVT::i64, Custom);
1194     setOperationAction(ISD::UREM, MVT::i64, Custom);
1195     HasStandaloneRem = false;
1196 
1197     if (Subtarget->isTargetWindows()) {
1198       const struct {
1199         const RTLIB::Libcall Op;
1200         const char * const Name;
1201         const CallingConv::ID CC;
1202       } LibraryCalls[] = {
1203         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1204         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1205         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1206         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1207 
1208         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1209         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1210         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1211         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1212       };
1213 
1214       for (const auto &LC : LibraryCalls) {
1215         setLibcallName(LC.Op, LC.Name);
1216         setLibcallCallingConv(LC.Op, LC.CC);
1217       }
1218     } else {
1219       const struct {
1220         const RTLIB::Libcall Op;
1221         const char * const Name;
1222         const CallingConv::ID CC;
1223       } LibraryCalls[] = {
1224         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1225         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1226         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1227         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1228 
1229         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1230         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1231         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1232         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1233       };
1234 
1235       for (const auto &LC : LibraryCalls) {
1236         setLibcallName(LC.Op, LC.Name);
1237         setLibcallCallingConv(LC.Op, LC.CC);
1238       }
1239     }
1240 
1241     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1242     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1243     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1244     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1245   } else {
1246     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1247     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1248   }
1249 
1250   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1251     // MSVCRT doesn't have powi; fall back to pow
1252     setLibcallName(RTLIB::POWI_F32, nullptr);
1253     setLibcallName(RTLIB::POWI_F64, nullptr);
1254   }
1255 
1256   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1257   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1258   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1259   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1260 
1261   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1262   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1263 
1264   // Use the default implementation.
1265   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1266   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1267   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1268   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1269   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1270   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1271 
1272   if (Subtarget->isTargetWindows())
1273     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1274   else
1275     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1276 
1277   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1278   // the default expansion.
1279   InsertFencesForAtomic = false;
1280   if (Subtarget->hasAnyDataBarrier() &&
1281       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1282     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1283     // to ldrex/strex loops already.
1284     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1285     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1286       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1287 
1288     // On v8, we have particularly efficient implementations of atomic fences
1289     // if they can be combined with nearby atomic loads and stores.
1290     if (!Subtarget->hasAcquireRelease() ||
1291         getTargetMachine().getOptLevel() == 0) {
1292       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1293       InsertFencesForAtomic = true;
1294     }
1295   } else {
1296     // If there's anything we can use as a barrier, go through custom lowering
1297     // for ATOMIC_FENCE.
1298     // If target has DMB in thumb, Fences can be inserted.
1299     if (Subtarget->hasDataBarrier())
1300       InsertFencesForAtomic = true;
1301 
1302     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1303                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1304 
1305     // Set them all for expansion, which will force libcalls.
1306     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1307     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1308     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1309     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1310     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1311     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1312     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1313     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1314     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1315     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1316     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1317     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1318     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1319     // Unordered/Monotonic case.
1320     if (!InsertFencesForAtomic) {
1321       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1322       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1323     }
1324   }
1325 
1326   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1327 
1328   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1329   if (!Subtarget->hasV6Ops()) {
1330     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1331     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1332   }
1333   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1334 
1335   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1336       !Subtarget->isThumb1Only()) {
1337     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1338     // iff target supports vfp2.
1339     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1340     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1341   }
1342 
1343   // We want to custom lower some of our intrinsics.
1344   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1345   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1346   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1347   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1348   if (Subtarget->useSjLjEH())
1349     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1350 
1351   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1352   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1353   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1354   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1355   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1356   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1357   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1358   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1359   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1360   if (Subtarget->hasFullFP16()) {
1361     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1362     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1363     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1364   }
1365 
1366   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1367 
1368   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1369   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1370   if (Subtarget->hasFullFP16())
1371       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1372   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1373   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1374   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1375 
1376   // We don't support sin/cos/fmod/copysign/pow
1377   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1378   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1379   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1380   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1381   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1382   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1383   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1384   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1385   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1386       !Subtarget->isThumb1Only()) {
1387     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1388     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1389   }
1390   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1391   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1392 
1393   if (!Subtarget->hasVFP4Base()) {
1394     setOperationAction(ISD::FMA, MVT::f64, Expand);
1395     setOperationAction(ISD::FMA, MVT::f32, Expand);
1396   }
1397 
1398   // Various VFP goodness
1399   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1400     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1401     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1402       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1403       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1404     }
1405 
1406     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1407     if (!Subtarget->hasFP16()) {
1408       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1409       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1410     }
1411 
1412     // Strict floating-point comparisons need custom lowering.
1413     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1414     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1415     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1416     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1417     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1418     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1419   }
1420 
1421   // Use __sincos_stret if available.
1422   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1423       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1424     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1425     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1426   }
1427 
1428   // FP-ARMv8 implements a lot of rounding-like FP operations.
1429   if (Subtarget->hasFPARMv8Base()) {
1430     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1431     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1432     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1433     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1434     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1435     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1436     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1437     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1438     if (Subtarget->hasNEON()) {
1439       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1440       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1441       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1442       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1443     }
1444 
1445     if (Subtarget->hasFP64()) {
1446       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1447       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1448       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1449       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1450       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1451       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1452       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1453       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1454     }
1455   }
1456 
1457   // FP16 often need to be promoted to call lib functions
1458   if (Subtarget->hasFullFP16()) {
1459     setOperationAction(ISD::FREM, MVT::f16, Promote);
1460     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1461     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1462     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1463     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1464     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1465     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1466     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1467     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1468     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1469     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1470     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1471 
1472     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1473   }
1474 
1475   if (Subtarget->hasNEON()) {
1476     // vmin and vmax aren't available in a scalar form, so we can use
1477     // a NEON instruction with an undef lane instead.  This has a performance
1478     // penalty on some cores, so we don't do this unless we have been
1479     // asked to by the core tuning model.
1480     if (Subtarget->useNEONForSinglePrecisionFP()) {
1481       setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1482       setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1483       setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1484       setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1485     }
1486     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1487     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1488     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1489     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1490 
1491     if (Subtarget->hasFullFP16()) {
1492       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1493       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1494       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1495       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1496 
1497       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1498       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1499       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1500       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1501     }
1502   }
1503 
1504   // We have target-specific dag combine patterns for the following nodes:
1505   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1506   setTargetDAGCombine(ISD::ADD);
1507   setTargetDAGCombine(ISD::SUB);
1508   setTargetDAGCombine(ISD::MUL);
1509   setTargetDAGCombine(ISD::AND);
1510   setTargetDAGCombine(ISD::OR);
1511   setTargetDAGCombine(ISD::XOR);
1512 
1513   if (Subtarget->hasMVEIntegerOps())
1514     setTargetDAGCombine(ISD::VSELECT);
1515 
1516   if (Subtarget->hasV6Ops())
1517     setTargetDAGCombine(ISD::SRL);
1518   if (Subtarget->isThumb1Only())
1519     setTargetDAGCombine(ISD::SHL);
1520 
1521   setStackPointerRegisterToSaveRestore(ARM::SP);
1522 
1523   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1524       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1525     setSchedulingPreference(Sched::RegPressure);
1526   else
1527     setSchedulingPreference(Sched::Hybrid);
1528 
1529   //// temporary - rewrite interface to use type
1530   MaxStoresPerMemset = 8;
1531   MaxStoresPerMemsetOptSize = 4;
1532   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1533   MaxStoresPerMemcpyOptSize = 2;
1534   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1535   MaxStoresPerMemmoveOptSize = 2;
1536 
1537   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1538   // are at least 4 bytes aligned.
1539   setMinStackArgumentAlignment(Align(4));
1540 
1541   // Prefer likely predicted branches to selects on out-of-order cores.
1542   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1543 
1544   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1545 
1546   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1547 
1548   if (Subtarget->isThumb() || Subtarget->isThumb2())
1549     setTargetDAGCombine(ISD::ABS);
1550 }
1551 
1552 bool ARMTargetLowering::useSoftFloat() const {
1553   return Subtarget->useSoftFloat();
1554 }
1555 
1556 // FIXME: It might make sense to define the representative register class as the
1557 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1558 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1559 // SPR's representative would be DPR_VFP2. This should work well if register
1560 // pressure tracking were modified such that a register use would increment the
1561 // pressure of the register class's representative and all of it's super
1562 // classes' representatives transitively. We have not implemented this because
1563 // of the difficulty prior to coalescing of modeling operand register classes
1564 // due to the common occurrence of cross class copies and subregister insertions
1565 // and extractions.
1566 std::pair<const TargetRegisterClass *, uint8_t>
1567 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1568                                            MVT VT) const {
1569   const TargetRegisterClass *RRC = nullptr;
1570   uint8_t Cost = 1;
1571   switch (VT.SimpleTy) {
1572   default:
1573     return TargetLowering::findRepresentativeClass(TRI, VT);
1574   // Use DPR as representative register class for all floating point
1575   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1576   // the cost is 1 for both f32 and f64.
1577   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1578   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1579     RRC = &ARM::DPRRegClass;
1580     // When NEON is used for SP, only half of the register file is available
1581     // because operations that define both SP and DP results will be constrained
1582     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1583     // coalescing by double-counting the SP regs. See the FIXME above.
1584     if (Subtarget->useNEONForSinglePrecisionFP())
1585       Cost = 2;
1586     break;
1587   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1588   case MVT::v4f32: case MVT::v2f64:
1589     RRC = &ARM::DPRRegClass;
1590     Cost = 2;
1591     break;
1592   case MVT::v4i64:
1593     RRC = &ARM::DPRRegClass;
1594     Cost = 4;
1595     break;
1596   case MVT::v8i64:
1597     RRC = &ARM::DPRRegClass;
1598     Cost = 8;
1599     break;
1600   }
1601   return std::make_pair(RRC, Cost);
1602 }
1603 
1604 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1605   switch ((ARMISD::NodeType)Opcode) {
1606   case ARMISD::FIRST_NUMBER:  break;
1607   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1608   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1609   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1610   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1611   case ARMISD::CALL:          return "ARMISD::CALL";
1612   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1613   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1614   case ARMISD::tSECALL:       return "ARMISD::tSECALL";
1615   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1616   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1617   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1618   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1619   case ARMISD::SERET_FLAG:    return "ARMISD::SERET_FLAG";
1620   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1621   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1622   case ARMISD::CMP:           return "ARMISD::CMP";
1623   case ARMISD::CMN:           return "ARMISD::CMN";
1624   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1625   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1626   case ARMISD::CMPFPE:        return "ARMISD::CMPFPE";
1627   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1628   case ARMISD::CMPFPEw0:      return "ARMISD::CMPFPEw0";
1629   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1630   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1631 
1632   case ARMISD::CMOV:          return "ARMISD::CMOV";
1633   case ARMISD::SUBS:          return "ARMISD::SUBS";
1634 
1635   case ARMISD::SSAT:          return "ARMISD::SSAT";
1636   case ARMISD::USAT:          return "ARMISD::USAT";
1637 
1638   case ARMISD::ASRL:          return "ARMISD::ASRL";
1639   case ARMISD::LSRL:          return "ARMISD::LSRL";
1640   case ARMISD::LSLL:          return "ARMISD::LSLL";
1641 
1642   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1643   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1644   case ARMISD::RRX:           return "ARMISD::RRX";
1645 
1646   case ARMISD::ADDC:          return "ARMISD::ADDC";
1647   case ARMISD::ADDE:          return "ARMISD::ADDE";
1648   case ARMISD::SUBC:          return "ARMISD::SUBC";
1649   case ARMISD::SUBE:          return "ARMISD::SUBE";
1650   case ARMISD::LSLS:          return "ARMISD::LSLS";
1651 
1652   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1653   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1654   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1655   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1656   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1657 
1658   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1659   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1660   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1661 
1662   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1663 
1664   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1665 
1666   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1667 
1668   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1669 
1670   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1671 
1672   case ARMISD::LDRD:          return "ARMISD::LDRD";
1673   case ARMISD::STRD:          return "ARMISD::STRD";
1674 
1675   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1676   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1677 
1678   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1679   case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1680   case ARMISD::VCMP:          return "ARMISD::VCMP";
1681   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1682   case ARMISD::VTST:          return "ARMISD::VTST";
1683 
1684   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1685   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1686   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1687   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1688   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1689   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1690   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1691   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1692   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1693   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1694   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1695   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1696   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1697   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1698   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1699   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1700   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1701   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1702   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1703   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1704   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1705   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1706   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1707   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1708   case ARMISD::VDUP:          return "ARMISD::VDUP";
1709   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1710   case ARMISD::VEXT:          return "ARMISD::VEXT";
1711   case ARMISD::VREV64:        return "ARMISD::VREV64";
1712   case ARMISD::VREV32:        return "ARMISD::VREV32";
1713   case ARMISD::VREV16:        return "ARMISD::VREV16";
1714   case ARMISD::VZIP:          return "ARMISD::VZIP";
1715   case ARMISD::VUZP:          return "ARMISD::VUZP";
1716   case ARMISD::VTRN:          return "ARMISD::VTRN";
1717   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1718   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1719   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1720   case ARMISD::VQMOVNs:       return "ARMISD::VQMOVNs";
1721   case ARMISD::VQMOVNu:       return "ARMISD::VQMOVNu";
1722   case ARMISD::VCVTN:         return "ARMISD::VCVTN";
1723   case ARMISD::VCVTL:         return "ARMISD::VCVTL";
1724   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1725   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1726   case ARMISD::VQDMULH:       return "ARMISD::VQDMULH";
1727   case ARMISD::VADDVs:        return "ARMISD::VADDVs";
1728   case ARMISD::VADDVu:        return "ARMISD::VADDVu";
1729   case ARMISD::VADDVps:       return "ARMISD::VADDVps";
1730   case ARMISD::VADDVpu:       return "ARMISD::VADDVpu";
1731   case ARMISD::VADDLVs:       return "ARMISD::VADDLVs";
1732   case ARMISD::VADDLVu:       return "ARMISD::VADDLVu";
1733   case ARMISD::VADDLVAs:      return "ARMISD::VADDLVAs";
1734   case ARMISD::VADDLVAu:      return "ARMISD::VADDLVAu";
1735   case ARMISD::VADDLVps:      return "ARMISD::VADDLVps";
1736   case ARMISD::VADDLVpu:      return "ARMISD::VADDLVpu";
1737   case ARMISD::VADDLVAps:     return "ARMISD::VADDLVAps";
1738   case ARMISD::VADDLVApu:     return "ARMISD::VADDLVApu";
1739   case ARMISD::VMLAVs:        return "ARMISD::VMLAVs";
1740   case ARMISD::VMLAVu:        return "ARMISD::VMLAVu";
1741   case ARMISD::VMLAVps:       return "ARMISD::VMLAVps";
1742   case ARMISD::VMLAVpu:       return "ARMISD::VMLAVpu";
1743   case ARMISD::VMLALVs:       return "ARMISD::VMLALVs";
1744   case ARMISD::VMLALVu:       return "ARMISD::VMLALVu";
1745   case ARMISD::VMLALVps:      return "ARMISD::VMLALVps";
1746   case ARMISD::VMLALVpu:      return "ARMISD::VMLALVpu";
1747   case ARMISD::VMLALVAs:      return "ARMISD::VMLALVAs";
1748   case ARMISD::VMLALVAu:      return "ARMISD::VMLALVAu";
1749   case ARMISD::VMLALVAps:     return "ARMISD::VMLALVAps";
1750   case ARMISD::VMLALVApu:     return "ARMISD::VMLALVApu";
1751   case ARMISD::VMINVu:        return "ARMISD::VMINVu";
1752   case ARMISD::VMINVs:        return "ARMISD::VMINVs";
1753   case ARMISD::VMAXVu:        return "ARMISD::VMAXVu";
1754   case ARMISD::VMAXVs:        return "ARMISD::VMAXVs";
1755   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1756   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1757   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1758   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1759   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1760   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1761   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1762   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1763   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1764   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1765   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1766   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1767   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1768   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1769   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1770   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1771   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1772   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1773   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1774   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1775   case ARMISD::BFI:           return "ARMISD::BFI";
1776   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1777   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1778   case ARMISD::VBSP:          return "ARMISD::VBSP";
1779   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1780   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1781   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1782   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1783   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1784   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1785   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1786   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1787   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1788   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1789   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1790   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1791   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1792   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1793   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1794   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1795   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1796   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1797   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1798   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1799   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1800   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1801   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1802   case ARMISD::WLS:           return "ARMISD::WLS";
1803   case ARMISD::LE:            return "ARMISD::LE";
1804   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1805   case ARMISD::CSINV:         return "ARMISD::CSINV";
1806   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1807   case ARMISD::CSINC:         return "ARMISD::CSINC";
1808   }
1809   return nullptr;
1810 }
1811 
1812 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1813                                           EVT VT) const {
1814   if (!VT.isVector())
1815     return getPointerTy(DL);
1816 
1817   // MVE has a predicate register.
1818   if (Subtarget->hasMVEIntegerOps() &&
1819       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1820     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1821   return VT.changeVectorElementTypeToInteger();
1822 }
1823 
1824 /// getRegClassFor - Return the register class that should be used for the
1825 /// specified value type.
1826 const TargetRegisterClass *
1827 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1828   (void)isDivergent;
1829   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1830   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1831   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1832   // MVE Q registers.
1833   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1834     if (VT == MVT::v4i64)
1835       return &ARM::QQPRRegClass;
1836     if (VT == MVT::v8i64)
1837       return &ARM::QQQQPRRegClass;
1838   }
1839   return TargetLowering::getRegClassFor(VT);
1840 }
1841 
1842 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1843 // source/dest is aligned and the copy size is large enough. We therefore want
1844 // to align such objects passed to memory intrinsics.
1845 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1846                                                unsigned &PrefAlign) const {
1847   if (!isa<MemIntrinsic>(CI))
1848     return false;
1849   MinSize = 8;
1850   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1851   // cycle faster than 4-byte aligned LDM.
1852   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1853   return true;
1854 }
1855 
1856 // Create a fast isel object.
1857 FastISel *
1858 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1859                                   const TargetLibraryInfo *libInfo) const {
1860   return ARM::createFastISel(funcInfo, libInfo);
1861 }
1862 
1863 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1864   unsigned NumVals = N->getNumValues();
1865   if (!NumVals)
1866     return Sched::RegPressure;
1867 
1868   for (unsigned i = 0; i != NumVals; ++i) {
1869     EVT VT = N->getValueType(i);
1870     if (VT == MVT::Glue || VT == MVT::Other)
1871       continue;
1872     if (VT.isFloatingPoint() || VT.isVector())
1873       return Sched::ILP;
1874   }
1875 
1876   if (!N->isMachineOpcode())
1877     return Sched::RegPressure;
1878 
1879   // Load are scheduled for latency even if there instruction itinerary
1880   // is not available.
1881   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1882   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1883 
1884   if (MCID.getNumDefs() == 0)
1885     return Sched::RegPressure;
1886   if (!Itins->isEmpty() &&
1887       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1888     return Sched::ILP;
1889 
1890   return Sched::RegPressure;
1891 }
1892 
1893 //===----------------------------------------------------------------------===//
1894 // Lowering Code
1895 //===----------------------------------------------------------------------===//
1896 
1897 static bool isSRL16(const SDValue &Op) {
1898   if (Op.getOpcode() != ISD::SRL)
1899     return false;
1900   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1901     return Const->getZExtValue() == 16;
1902   return false;
1903 }
1904 
1905 static bool isSRA16(const SDValue &Op) {
1906   if (Op.getOpcode() != ISD::SRA)
1907     return false;
1908   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1909     return Const->getZExtValue() == 16;
1910   return false;
1911 }
1912 
1913 static bool isSHL16(const SDValue &Op) {
1914   if (Op.getOpcode() != ISD::SHL)
1915     return false;
1916   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1917     return Const->getZExtValue() == 16;
1918   return false;
1919 }
1920 
1921 // Check for a signed 16-bit value. We special case SRA because it makes it
1922 // more simple when also looking for SRAs that aren't sign extending a
1923 // smaller value. Without the check, we'd need to take extra care with
1924 // checking order for some operations.
1925 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1926   if (isSRA16(Op))
1927     return isSHL16(Op.getOperand(0));
1928   return DAG.ComputeNumSignBits(Op) == 17;
1929 }
1930 
1931 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1932 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1933   switch (CC) {
1934   default: llvm_unreachable("Unknown condition code!");
1935   case ISD::SETNE:  return ARMCC::NE;
1936   case ISD::SETEQ:  return ARMCC::EQ;
1937   case ISD::SETGT:  return ARMCC::GT;
1938   case ISD::SETGE:  return ARMCC::GE;
1939   case ISD::SETLT:  return ARMCC::LT;
1940   case ISD::SETLE:  return ARMCC::LE;
1941   case ISD::SETUGT: return ARMCC::HI;
1942   case ISD::SETUGE: return ARMCC::HS;
1943   case ISD::SETULT: return ARMCC::LO;
1944   case ISD::SETULE: return ARMCC::LS;
1945   }
1946 }
1947 
1948 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1949 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1950                         ARMCC::CondCodes &CondCode2) {
1951   CondCode2 = ARMCC::AL;
1952   switch (CC) {
1953   default: llvm_unreachable("Unknown FP condition!");
1954   case ISD::SETEQ:
1955   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1956   case ISD::SETGT:
1957   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1958   case ISD::SETGE:
1959   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1960   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1961   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1962   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1963   case ISD::SETO:   CondCode = ARMCC::VC; break;
1964   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1965   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1966   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1967   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1968   case ISD::SETLT:
1969   case ISD::SETULT: CondCode = ARMCC::LT; break;
1970   case ISD::SETLE:
1971   case ISD::SETULE: CondCode = ARMCC::LE; break;
1972   case ISD::SETNE:
1973   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1974   }
1975 }
1976 
1977 //===----------------------------------------------------------------------===//
1978 //                      Calling Convention Implementation
1979 //===----------------------------------------------------------------------===//
1980 
1981 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1982 /// account presence of floating point hardware and calling convention
1983 /// limitations, such as support for variadic functions.
1984 CallingConv::ID
1985 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1986                                            bool isVarArg) const {
1987   switch (CC) {
1988   default:
1989     report_fatal_error("Unsupported calling convention");
1990   case CallingConv::ARM_AAPCS:
1991   case CallingConv::ARM_APCS:
1992   case CallingConv::GHC:
1993   case CallingConv::CFGuard_Check:
1994     return CC;
1995   case CallingConv::PreserveMost:
1996     return CallingConv::PreserveMost;
1997   case CallingConv::ARM_AAPCS_VFP:
1998   case CallingConv::Swift:
1999     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
2000   case CallingConv::C:
2001     if (!Subtarget->isAAPCS_ABI())
2002       return CallingConv::ARM_APCS;
2003     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
2004              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2005              !isVarArg)
2006       return CallingConv::ARM_AAPCS_VFP;
2007     else
2008       return CallingConv::ARM_AAPCS;
2009   case CallingConv::Fast:
2010   case CallingConv::CXX_FAST_TLS:
2011     if (!Subtarget->isAAPCS_ABI()) {
2012       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2013         return CallingConv::Fast;
2014       return CallingConv::ARM_APCS;
2015     } else if (Subtarget->hasVFP2Base() &&
2016                !Subtarget->isThumb1Only() && !isVarArg)
2017       return CallingConv::ARM_AAPCS_VFP;
2018     else
2019       return CallingConv::ARM_AAPCS;
2020   }
2021 }
2022 
2023 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2024                                                  bool isVarArg) const {
2025   return CCAssignFnForNode(CC, false, isVarArg);
2026 }
2027 
2028 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2029                                                    bool isVarArg) const {
2030   return CCAssignFnForNode(CC, true, isVarArg);
2031 }
2032 
2033 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2034 /// CallingConvention.
2035 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2036                                                  bool Return,
2037                                                  bool isVarArg) const {
2038   switch (getEffectiveCallingConv(CC, isVarArg)) {
2039   default:
2040     report_fatal_error("Unsupported calling convention");
2041   case CallingConv::ARM_APCS:
2042     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2043   case CallingConv::ARM_AAPCS:
2044     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2045   case CallingConv::ARM_AAPCS_VFP:
2046     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2047   case CallingConv::Fast:
2048     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2049   case CallingConv::GHC:
2050     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2051   case CallingConv::PreserveMost:
2052     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2053   case CallingConv::CFGuard_Check:
2054     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2055   }
2056 }
2057 
2058 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2059                                      MVT LocVT, MVT ValVT, SDValue Val) const {
2060   Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2061                     Val);
2062   if (Subtarget->hasFullFP16()) {
2063     Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2064   } else {
2065     Val = DAG.getNode(ISD::TRUNCATE, dl,
2066                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2067     Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2068   }
2069   return Val;
2070 }
2071 
2072 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2073                                        MVT LocVT, MVT ValVT,
2074                                        SDValue Val) const {
2075   if (Subtarget->hasFullFP16()) {
2076     Val = DAG.getNode(ARMISD::VMOVrh, dl,
2077                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2078   } else {
2079     Val = DAG.getNode(ISD::BITCAST, dl,
2080                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2081     Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2082                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2083   }
2084   return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2085 }
2086 
2087 /// LowerCallResult - Lower the result values of a call into the
2088 /// appropriate copies out of appropriate physical registers.
2089 SDValue ARMTargetLowering::LowerCallResult(
2090     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2091     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2092     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2093     SDValue ThisVal) const {
2094   // Assign locations to each value returned by this call.
2095   SmallVector<CCValAssign, 16> RVLocs;
2096   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2097                  *DAG.getContext());
2098   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2099 
2100   // Copy all of the result registers out of their specified physreg.
2101   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2102     CCValAssign VA = RVLocs[i];
2103 
2104     // Pass 'this' value directly from the argument to return value, to avoid
2105     // reg unit interference
2106     if (i == 0 && isThisReturn) {
2107       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2108              "unexpected return calling convention register assignment");
2109       InVals.push_back(ThisVal);
2110       continue;
2111     }
2112 
2113     SDValue Val;
2114     if (VA.needsCustom() &&
2115         (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2116       // Handle f64 or half of a v2f64.
2117       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2118                                       InFlag);
2119       Chain = Lo.getValue(1);
2120       InFlag = Lo.getValue(2);
2121       VA = RVLocs[++i]; // skip ahead to next loc
2122       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2123                                       InFlag);
2124       Chain = Hi.getValue(1);
2125       InFlag = Hi.getValue(2);
2126       if (!Subtarget->isLittle())
2127         std::swap (Lo, Hi);
2128       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2129 
2130       if (VA.getLocVT() == MVT::v2f64) {
2131         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2132         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2133                           DAG.getConstant(0, dl, MVT::i32));
2134 
2135         VA = RVLocs[++i]; // skip ahead to next loc
2136         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2137         Chain = Lo.getValue(1);
2138         InFlag = Lo.getValue(2);
2139         VA = RVLocs[++i]; // skip ahead to next loc
2140         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2141         Chain = Hi.getValue(1);
2142         InFlag = Hi.getValue(2);
2143         if (!Subtarget->isLittle())
2144           std::swap (Lo, Hi);
2145         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2146         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2147                           DAG.getConstant(1, dl, MVT::i32));
2148       }
2149     } else {
2150       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2151                                InFlag);
2152       Chain = Val.getValue(1);
2153       InFlag = Val.getValue(2);
2154     }
2155 
2156     switch (VA.getLocInfo()) {
2157     default: llvm_unreachable("Unknown loc info!");
2158     case CCValAssign::Full: break;
2159     case CCValAssign::BCvt:
2160       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2161       break;
2162     }
2163 
2164     // f16 arguments have their size extended to 4 bytes and passed as if they
2165     // had been copied to the LSBs of a 32-bit register.
2166     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2167     if (VA.needsCustom() &&
2168         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2169       Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2170 
2171     InVals.push_back(Val);
2172   }
2173 
2174   return Chain;
2175 }
2176 
2177 /// LowerMemOpCallTo - Store the argument to the stack.
2178 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2179                                             SDValue Arg, const SDLoc &dl,
2180                                             SelectionDAG &DAG,
2181                                             const CCValAssign &VA,
2182                                             ISD::ArgFlagsTy Flags) const {
2183   unsigned LocMemOffset = VA.getLocMemOffset();
2184   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2185   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2186                        StackPtr, PtrOff);
2187   return DAG.getStore(
2188       Chain, dl, Arg, PtrOff,
2189       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2190 }
2191 
2192 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2193                                          SDValue Chain, SDValue &Arg,
2194                                          RegsToPassVector &RegsToPass,
2195                                          CCValAssign &VA, CCValAssign &NextVA,
2196                                          SDValue &StackPtr,
2197                                          SmallVectorImpl<SDValue> &MemOpChains,
2198                                          ISD::ArgFlagsTy Flags) const {
2199   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2200                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2201   unsigned id = Subtarget->isLittle() ? 0 : 1;
2202   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2203 
2204   if (NextVA.isRegLoc())
2205     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2206   else {
2207     assert(NextVA.isMemLoc());
2208     if (!StackPtr.getNode())
2209       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2210                                     getPointerTy(DAG.getDataLayout()));
2211 
2212     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2213                                            dl, DAG, NextVA,
2214                                            Flags));
2215   }
2216 }
2217 
2218 /// LowerCall - Lowering a call into a callseq_start <-
2219 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2220 /// nodes.
2221 SDValue
2222 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2223                              SmallVectorImpl<SDValue> &InVals) const {
2224   SelectionDAG &DAG                     = CLI.DAG;
2225   SDLoc &dl                             = CLI.DL;
2226   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2227   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2228   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2229   SDValue Chain                         = CLI.Chain;
2230   SDValue Callee                        = CLI.Callee;
2231   bool &isTailCall                      = CLI.IsTailCall;
2232   CallingConv::ID CallConv              = CLI.CallConv;
2233   bool doesNotRet                       = CLI.DoesNotReturn;
2234   bool isVarArg                         = CLI.IsVarArg;
2235 
2236   MachineFunction &MF = DAG.getMachineFunction();
2237   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2238   MachineFunction::CallSiteInfo CSInfo;
2239   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2240   bool isThisReturn = false;
2241   bool isCmseNSCall   = false;
2242   bool PreferIndirect = false;
2243 
2244   // Determine whether this is a non-secure function call.
2245   if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call"))
2246     isCmseNSCall = true;
2247 
2248   // Disable tail calls if they're not supported.
2249   if (!Subtarget->supportsTailCall())
2250     isTailCall = false;
2251 
2252   // For both the non-secure calls and the returns from a CMSE entry function,
2253   // the function needs to do some extra work afte r the call, or before the
2254   // return, respectively, thus it cannot end with atail call
2255   if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2256     isTailCall = false;
2257 
2258   if (isa<GlobalAddressSDNode>(Callee)) {
2259     // If we're optimizing for minimum size and the function is called three or
2260     // more times in this block, we can improve codesize by calling indirectly
2261     // as BLXr has a 16-bit encoding.
2262     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2263     if (CLI.CB) {
2264       auto *BB = CLI.CB->getParent();
2265       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2266                        count_if(GV->users(), [&BB](const User *U) {
2267                          return isa<Instruction>(U) &&
2268                                 cast<Instruction>(U)->getParent() == BB;
2269                        }) > 2;
2270     }
2271   }
2272   if (isTailCall) {
2273     // Check if it's really possible to do a tail call.
2274     isTailCall = IsEligibleForTailCallOptimization(
2275         Callee, CallConv, isVarArg, isStructRet,
2276         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2277         PreferIndirect);
2278     if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2279       report_fatal_error("failed to perform tail call elimination on a call "
2280                          "site marked musttail");
2281     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2282     // detected sibcalls.
2283     if (isTailCall)
2284       ++NumTailCalls;
2285   }
2286 
2287   // Analyze operands of the call, assigning locations to each operand.
2288   SmallVector<CCValAssign, 16> ArgLocs;
2289   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2290                  *DAG.getContext());
2291   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2292 
2293   // Get a count of how many bytes are to be pushed on the stack.
2294   unsigned NumBytes = CCInfo.getNextStackOffset();
2295 
2296   if (isTailCall) {
2297     // For tail calls, memory operands are available in our caller's stack.
2298     NumBytes = 0;
2299   } else {
2300     // Adjust the stack pointer for the new arguments...
2301     // These operations are automatically eliminated by the prolog/epilog pass
2302     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2303   }
2304 
2305   SDValue StackPtr =
2306       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2307 
2308   RegsToPassVector RegsToPass;
2309   SmallVector<SDValue, 8> MemOpChains;
2310 
2311   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2312   // of tail call optimization, arguments are handled later.
2313   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2314        i != e;
2315        ++i, ++realArgIdx) {
2316     CCValAssign &VA = ArgLocs[i];
2317     SDValue Arg = OutVals[realArgIdx];
2318     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2319     bool isByVal = Flags.isByVal();
2320 
2321     // Promote the value if needed.
2322     switch (VA.getLocInfo()) {
2323     default: llvm_unreachable("Unknown loc info!");
2324     case CCValAssign::Full: break;
2325     case CCValAssign::SExt:
2326       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2327       break;
2328     case CCValAssign::ZExt:
2329       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2330       break;
2331     case CCValAssign::AExt:
2332       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2333       break;
2334     case CCValAssign::BCvt:
2335       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2336       break;
2337     }
2338 
2339     // f16 arguments have their size extended to 4 bytes and passed as if they
2340     // had been copied to the LSBs of a 32-bit register.
2341     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2342     if (VA.needsCustom() &&
2343         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2344       Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2345     } else {
2346       // f16 arguments could have been extended prior to argument lowering.
2347       // Mask them arguments if this is a CMSE nonsecure call.
2348       auto ArgVT = Outs[realArgIdx].ArgVT;
2349       if (isCmseNSCall && (ArgVT == MVT::f16)) {
2350         auto LocBits = VA.getLocVT().getSizeInBits();
2351         auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2352         SDValue Mask =
2353             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2354         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2355         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2356         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2357       }
2358     }
2359 
2360     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2361     if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2362       SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2363                                 DAG.getConstant(0, dl, MVT::i32));
2364       SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2365                                 DAG.getConstant(1, dl, MVT::i32));
2366 
2367       PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2368                        StackPtr, MemOpChains, Flags);
2369 
2370       VA = ArgLocs[++i]; // skip ahead to next loc
2371       if (VA.isRegLoc()) {
2372         PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2373                          StackPtr, MemOpChains, Flags);
2374       } else {
2375         assert(VA.isMemLoc());
2376 
2377         MemOpChains.push_back(
2378             LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags));
2379       }
2380     } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2381       PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2382                        StackPtr, MemOpChains, Flags);
2383     } else if (VA.isRegLoc()) {
2384       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2385           Outs[0].VT == MVT::i32) {
2386         assert(VA.getLocVT() == MVT::i32 &&
2387                "unexpected calling convention register assignment");
2388         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2389                "unexpected use of 'returned'");
2390         isThisReturn = true;
2391       }
2392       const TargetOptions &Options = DAG.getTarget().Options;
2393       if (Options.EmitCallSiteInfo)
2394         CSInfo.emplace_back(VA.getLocReg(), i);
2395       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2396     } else if (isByVal) {
2397       assert(VA.isMemLoc());
2398       unsigned offset = 0;
2399 
2400       // True if this byval aggregate will be split between registers
2401       // and memory.
2402       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2403       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2404 
2405       if (CurByValIdx < ByValArgsCount) {
2406 
2407         unsigned RegBegin, RegEnd;
2408         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2409 
2410         EVT PtrVT =
2411             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2412         unsigned int i, j;
2413         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2414           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2415           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2416           SDValue Load =
2417               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2418                           DAG.InferPtrAlign(AddArg));
2419           MemOpChains.push_back(Load.getValue(1));
2420           RegsToPass.push_back(std::make_pair(j, Load));
2421         }
2422 
2423         // If parameter size outsides register area, "offset" value
2424         // helps us to calculate stack slot for remained part properly.
2425         offset = RegEnd - RegBegin;
2426 
2427         CCInfo.nextInRegsParam();
2428       }
2429 
2430       if (Flags.getByValSize() > 4*offset) {
2431         auto PtrVT = getPointerTy(DAG.getDataLayout());
2432         unsigned LocMemOffset = VA.getLocMemOffset();
2433         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2434         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2435         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2436         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2437         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2438                                            MVT::i32);
2439         SDValue AlignNode =
2440             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2441 
2442         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2443         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2444         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2445                                           Ops));
2446       }
2447     } else if (!isTailCall) {
2448       assert(VA.isMemLoc());
2449 
2450       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2451                                              dl, DAG, VA, Flags));
2452     }
2453   }
2454 
2455   if (!MemOpChains.empty())
2456     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2457 
2458   // Build a sequence of copy-to-reg nodes chained together with token chain
2459   // and flag operands which copy the outgoing args into the appropriate regs.
2460   SDValue InFlag;
2461   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2462     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2463                              RegsToPass[i].second, InFlag);
2464     InFlag = Chain.getValue(1);
2465   }
2466 
2467   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2468   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2469   // node so that legalize doesn't hack it.
2470   bool isDirect = false;
2471 
2472   const TargetMachine &TM = getTargetMachine();
2473   const Module *Mod = MF.getFunction().getParent();
2474   const GlobalValue *GV = nullptr;
2475   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2476     GV = G->getGlobal();
2477   bool isStub =
2478       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2479 
2480   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2481   bool isLocalARMFunc = false;
2482   auto PtrVt = getPointerTy(DAG.getDataLayout());
2483 
2484   if (Subtarget->genLongCalls()) {
2485     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2486            "long-calls codegen is not position independent!");
2487     // Handle a global address or an external symbol. If it's not one of
2488     // those, the target's already in a register, so we don't need to do
2489     // anything extra.
2490     if (isa<GlobalAddressSDNode>(Callee)) {
2491       // Create a constant pool entry for the callee address
2492       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2493       ARMConstantPoolValue *CPV =
2494         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2495 
2496       // Get the address of the callee into a register
2497       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2498       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2499       Callee = DAG.getLoad(
2500           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2501           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2502     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2503       const char *Sym = S->getSymbol();
2504 
2505       // Create a constant pool entry for the callee address
2506       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2507       ARMConstantPoolValue *CPV =
2508         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2509                                       ARMPCLabelIndex, 0);
2510       // Get the address of the callee into a register
2511       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2512       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2513       Callee = DAG.getLoad(
2514           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2515           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2516     }
2517   } else if (isa<GlobalAddressSDNode>(Callee)) {
2518     if (!PreferIndirect) {
2519       isDirect = true;
2520       bool isDef = GV->isStrongDefinitionForLinker();
2521 
2522       // ARM call to a local ARM function is predicable.
2523       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2524       // tBX takes a register source operand.
2525       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2526         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2527         Callee = DAG.getNode(
2528             ARMISD::WrapperPIC, dl, PtrVt,
2529             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2530         Callee = DAG.getLoad(
2531             PtrVt, dl, DAG.getEntryNode(), Callee,
2532             MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2533             MachineMemOperand::MODereferenceable |
2534                 MachineMemOperand::MOInvariant);
2535       } else if (Subtarget->isTargetCOFF()) {
2536         assert(Subtarget->isTargetWindows() &&
2537                "Windows is the only supported COFF target");
2538         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2539         if (GV->hasDLLImportStorageClass())
2540           TargetFlags = ARMII::MO_DLLIMPORT;
2541         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2542           TargetFlags = ARMII::MO_COFFSTUB;
2543         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2544                                             TargetFlags);
2545         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2546           Callee =
2547               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2548                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2549                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2550       } else {
2551         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2552       }
2553     }
2554   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2555     isDirect = true;
2556     // tBX takes a register source operand.
2557     const char *Sym = S->getSymbol();
2558     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2559       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2560       ARMConstantPoolValue *CPV =
2561         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2562                                       ARMPCLabelIndex, 4);
2563       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2564       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2565       Callee = DAG.getLoad(
2566           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2567           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2568       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2569       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2570     } else {
2571       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2572     }
2573   }
2574 
2575   if (isCmseNSCall) {
2576     assert(!isARMFunc && !isDirect &&
2577            "Cannot handle call to ARM function or direct call");
2578     if (NumBytes > 0) {
2579       DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2580                                      "call to non-secure function would "
2581                                      "require passing arguments on stack",
2582                                      dl.getDebugLoc());
2583       DAG.getContext()->diagnose(Diag);
2584     }
2585     if (isStructRet) {
2586       DiagnosticInfoUnsupported Diag(
2587           DAG.getMachineFunction().getFunction(),
2588           "call to non-secure function would return value through pointer",
2589           dl.getDebugLoc());
2590       DAG.getContext()->diagnose(Diag);
2591     }
2592   }
2593 
2594   // FIXME: handle tail calls differently.
2595   unsigned CallOpc;
2596   if (Subtarget->isThumb()) {
2597     if (isCmseNSCall)
2598       CallOpc = ARMISD::tSECALL;
2599     else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2600       CallOpc = ARMISD::CALL_NOLINK;
2601     else
2602       CallOpc = ARMISD::CALL;
2603   } else {
2604     if (!isDirect && !Subtarget->hasV5TOps())
2605       CallOpc = ARMISD::CALL_NOLINK;
2606     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2607              // Emit regular call when code size is the priority
2608              !Subtarget->hasMinSize())
2609       // "mov lr, pc; b _foo" to avoid confusing the RSP
2610       CallOpc = ARMISD::CALL_NOLINK;
2611     else
2612       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2613   }
2614 
2615   std::vector<SDValue> Ops;
2616   Ops.push_back(Chain);
2617   Ops.push_back(Callee);
2618 
2619   // Add argument registers to the end of the list so that they are known live
2620   // into the call.
2621   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2622     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2623                                   RegsToPass[i].second.getValueType()));
2624 
2625   // Add a register mask operand representing the call-preserved registers.
2626   if (!isTailCall) {
2627     const uint32_t *Mask;
2628     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2629     if (isThisReturn) {
2630       // For 'this' returns, use the R0-preserving mask if applicable
2631       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2632       if (!Mask) {
2633         // Set isThisReturn to false if the calling convention is not one that
2634         // allows 'returned' to be modeled in this way, so LowerCallResult does
2635         // not try to pass 'this' straight through
2636         isThisReturn = false;
2637         Mask = ARI->getCallPreservedMask(MF, CallConv);
2638       }
2639     } else
2640       Mask = ARI->getCallPreservedMask(MF, CallConv);
2641 
2642     assert(Mask && "Missing call preserved mask for calling convention");
2643     Ops.push_back(DAG.getRegisterMask(Mask));
2644   }
2645 
2646   if (InFlag.getNode())
2647     Ops.push_back(InFlag);
2648 
2649   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2650   if (isTailCall) {
2651     MF.getFrameInfo().setHasTailCall();
2652     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2653     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2654     return Ret;
2655   }
2656 
2657   // Returns a chain and a flag for retval copy to use.
2658   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2659   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2660   InFlag = Chain.getValue(1);
2661   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2662 
2663   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2664                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2665   if (!Ins.empty())
2666     InFlag = Chain.getValue(1);
2667 
2668   // Handle result values, copying them out of physregs into vregs that we
2669   // return.
2670   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2671                          InVals, isThisReturn,
2672                          isThisReturn ? OutVals[0] : SDValue());
2673 }
2674 
2675 /// HandleByVal - Every parameter *after* a byval parameter is passed
2676 /// on the stack.  Remember the next parameter register to allocate,
2677 /// and then confiscate the rest of the parameter registers to insure
2678 /// this.
2679 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2680                                     Align Alignment) const {
2681   // Byval (as with any stack) slots are always at least 4 byte aligned.
2682   Alignment = std::max(Alignment, Align(4));
2683 
2684   unsigned Reg = State->AllocateReg(GPRArgRegs);
2685   if (!Reg)
2686     return;
2687 
2688   unsigned AlignInRegs = Alignment.value() / 4;
2689   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2690   for (unsigned i = 0; i < Waste; ++i)
2691     Reg = State->AllocateReg(GPRArgRegs);
2692 
2693   if (!Reg)
2694     return;
2695 
2696   unsigned Excess = 4 * (ARM::R4 - Reg);
2697 
2698   // Special case when NSAA != SP and parameter size greater than size of
2699   // all remained GPR regs. In that case we can't split parameter, we must
2700   // send it to stack. We also must set NCRN to R4, so waste all
2701   // remained registers.
2702   const unsigned NSAAOffset = State->getNextStackOffset();
2703   if (NSAAOffset != 0 && Size > Excess) {
2704     while (State->AllocateReg(GPRArgRegs))
2705       ;
2706     return;
2707   }
2708 
2709   // First register for byval parameter is the first register that wasn't
2710   // allocated before this method call, so it would be "reg".
2711   // If parameter is small enough to be saved in range [reg, r4), then
2712   // the end (first after last) register would be reg + param-size-in-regs,
2713   // else parameter would be splitted between registers and stack,
2714   // end register would be r4 in this case.
2715   unsigned ByValRegBegin = Reg;
2716   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2717   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2718   // Note, first register is allocated in the beginning of function already,
2719   // allocate remained amount of registers we need.
2720   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2721     State->AllocateReg(GPRArgRegs);
2722   // A byval parameter that is split between registers and memory needs its
2723   // size truncated here.
2724   // In the case where the entire structure fits in registers, we set the
2725   // size in memory to zero.
2726   Size = std::max<int>(Size - Excess, 0);
2727 }
2728 
2729 /// MatchingStackOffset - Return true if the given stack call argument is
2730 /// already available in the same position (relatively) of the caller's
2731 /// incoming argument stack.
2732 static
2733 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2734                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2735                          const TargetInstrInfo *TII) {
2736   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2737   int FI = std::numeric_limits<int>::max();
2738   if (Arg.getOpcode() == ISD::CopyFromReg) {
2739     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2740     if (!Register::isVirtualRegister(VR))
2741       return false;
2742     MachineInstr *Def = MRI->getVRegDef(VR);
2743     if (!Def)
2744       return false;
2745     if (!Flags.isByVal()) {
2746       if (!TII->isLoadFromStackSlot(*Def, FI))
2747         return false;
2748     } else {
2749       return false;
2750     }
2751   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2752     if (Flags.isByVal())
2753       // ByVal argument is passed in as a pointer but it's now being
2754       // dereferenced. e.g.
2755       // define @foo(%struct.X* %A) {
2756       //   tail call @bar(%struct.X* byval %A)
2757       // }
2758       return false;
2759     SDValue Ptr = Ld->getBasePtr();
2760     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2761     if (!FINode)
2762       return false;
2763     FI = FINode->getIndex();
2764   } else
2765     return false;
2766 
2767   assert(FI != std::numeric_limits<int>::max());
2768   if (!MFI.isFixedObjectIndex(FI))
2769     return false;
2770   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2771 }
2772 
2773 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2774 /// for tail call optimization. Targets which want to do tail call
2775 /// optimization should implement this function.
2776 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2777     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2778     bool isCalleeStructRet, bool isCallerStructRet,
2779     const SmallVectorImpl<ISD::OutputArg> &Outs,
2780     const SmallVectorImpl<SDValue> &OutVals,
2781     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2782     const bool isIndirect) const {
2783   MachineFunction &MF = DAG.getMachineFunction();
2784   const Function &CallerF = MF.getFunction();
2785   CallingConv::ID CallerCC = CallerF.getCallingConv();
2786 
2787   assert(Subtarget->supportsTailCall());
2788 
2789   // Indirect tail calls cannot be optimized for Thumb1 if the args
2790   // to the call take up r0-r3. The reason is that there are no legal registers
2791   // left to hold the pointer to the function to be called.
2792   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2793       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2794     return false;
2795 
2796   // Look for obvious safe cases to perform tail call optimization that do not
2797   // require ABI changes. This is what gcc calls sibcall.
2798 
2799   // Exception-handling functions need a special set of instructions to indicate
2800   // a return to the hardware. Tail-calling another function would probably
2801   // break this.
2802   if (CallerF.hasFnAttribute("interrupt"))
2803     return false;
2804 
2805   // Also avoid sibcall optimization if either caller or callee uses struct
2806   // return semantics.
2807   if (isCalleeStructRet || isCallerStructRet)
2808     return false;
2809 
2810   // Externally-defined functions with weak linkage should not be
2811   // tail-called on ARM when the OS does not support dynamic
2812   // pre-emption of symbols, as the AAELF spec requires normal calls
2813   // to undefined weak functions to be replaced with a NOP or jump to the
2814   // next instruction. The behaviour of branch instructions in this
2815   // situation (as used for tail calls) is implementation-defined, so we
2816   // cannot rely on the linker replacing the tail call with a return.
2817   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2818     const GlobalValue *GV = G->getGlobal();
2819     const Triple &TT = getTargetMachine().getTargetTriple();
2820     if (GV->hasExternalWeakLinkage() &&
2821         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2822       return false;
2823   }
2824 
2825   // Check that the call results are passed in the same way.
2826   LLVMContext &C = *DAG.getContext();
2827   if (!CCState::resultsCompatible(
2828           getEffectiveCallingConv(CalleeCC, isVarArg),
2829           getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2830           CCAssignFnForReturn(CalleeCC, isVarArg),
2831           CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2832     return false;
2833   // The callee has to preserve all registers the caller needs to preserve.
2834   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2835   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2836   if (CalleeCC != CallerCC) {
2837     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2838     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2839       return false;
2840   }
2841 
2842   // If Caller's vararg or byval argument has been split between registers and
2843   // stack, do not perform tail call, since part of the argument is in caller's
2844   // local frame.
2845   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2846   if (AFI_Caller->getArgRegsSaveSize())
2847     return false;
2848 
2849   // If the callee takes no arguments then go on to check the results of the
2850   // call.
2851   if (!Outs.empty()) {
2852     // Check if stack adjustment is needed. For now, do not do this if any
2853     // argument is passed on the stack.
2854     SmallVector<CCValAssign, 16> ArgLocs;
2855     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2856     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2857     if (CCInfo.getNextStackOffset()) {
2858       // Check if the arguments are already laid out in the right way as
2859       // the caller's fixed stack objects.
2860       MachineFrameInfo &MFI = MF.getFrameInfo();
2861       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2862       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2863       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2864            i != e;
2865            ++i, ++realArgIdx) {
2866         CCValAssign &VA = ArgLocs[i];
2867         EVT RegVT = VA.getLocVT();
2868         SDValue Arg = OutVals[realArgIdx];
2869         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2870         if (VA.getLocInfo() == CCValAssign::Indirect)
2871           return false;
2872         if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
2873           // f64 and vector types are split into multiple registers or
2874           // register/stack-slot combinations.  The types will not match
2875           // the registers; give up on memory f64 refs until we figure
2876           // out what to do about this.
2877           if (!VA.isRegLoc())
2878             return false;
2879           if (!ArgLocs[++i].isRegLoc())
2880             return false;
2881           if (RegVT == MVT::v2f64) {
2882             if (!ArgLocs[++i].isRegLoc())
2883               return false;
2884             if (!ArgLocs[++i].isRegLoc())
2885               return false;
2886           }
2887         } else if (!VA.isRegLoc()) {
2888           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2889                                    MFI, MRI, TII))
2890             return false;
2891         }
2892       }
2893     }
2894 
2895     const MachineRegisterInfo &MRI = MF.getRegInfo();
2896     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2897       return false;
2898   }
2899 
2900   return true;
2901 }
2902 
2903 bool
2904 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2905                                   MachineFunction &MF, bool isVarArg,
2906                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2907                                   LLVMContext &Context) const {
2908   SmallVector<CCValAssign, 16> RVLocs;
2909   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2910   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2911 }
2912 
2913 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2914                                     const SDLoc &DL, SelectionDAG &DAG) {
2915   const MachineFunction &MF = DAG.getMachineFunction();
2916   const Function &F = MF.getFunction();
2917 
2918   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2919 
2920   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2921   // version of the "preferred return address". These offsets affect the return
2922   // instruction if this is a return from PL1 without hypervisor extensions.
2923   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2924   //    SWI:     0      "subs pc, lr, #0"
2925   //    ABORT:   +4     "subs pc, lr, #4"
2926   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2927   // UNDEF varies depending on where the exception came from ARM or Thumb
2928   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2929 
2930   int64_t LROffset;
2931   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2932       IntKind == "ABORT")
2933     LROffset = 4;
2934   else if (IntKind == "SWI" || IntKind == "UNDEF")
2935     LROffset = 0;
2936   else
2937     report_fatal_error("Unsupported interrupt attribute. If present, value "
2938                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2939 
2940   RetOps.insert(RetOps.begin() + 1,
2941                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2942 
2943   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2944 }
2945 
2946 SDValue
2947 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2948                                bool isVarArg,
2949                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2950                                const SmallVectorImpl<SDValue> &OutVals,
2951                                const SDLoc &dl, SelectionDAG &DAG) const {
2952   // CCValAssign - represent the assignment of the return value to a location.
2953   SmallVector<CCValAssign, 16> RVLocs;
2954 
2955   // CCState - Info about the registers and stack slots.
2956   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2957                  *DAG.getContext());
2958 
2959   // Analyze outgoing return values.
2960   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2961 
2962   SDValue Flag;
2963   SmallVector<SDValue, 4> RetOps;
2964   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2965   bool isLittleEndian = Subtarget->isLittle();
2966 
2967   MachineFunction &MF = DAG.getMachineFunction();
2968   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2969   AFI->setReturnRegsCount(RVLocs.size());
2970 
2971  // Report error if cmse entry function returns structure through first ptr arg.
2972   if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2973     // Note: using an empty SDLoc(), as the first line of the function is a
2974     // better place to report than the last line.
2975     DiagnosticInfoUnsupported Diag(
2976         DAG.getMachineFunction().getFunction(),
2977         "secure entry function would return value through pointer",
2978         SDLoc().getDebugLoc());
2979     DAG.getContext()->diagnose(Diag);
2980   }
2981 
2982   // Copy the result values into the output registers.
2983   for (unsigned i = 0, realRVLocIdx = 0;
2984        i != RVLocs.size();
2985        ++i, ++realRVLocIdx) {
2986     CCValAssign &VA = RVLocs[i];
2987     assert(VA.isRegLoc() && "Can only return in registers!");
2988 
2989     SDValue Arg = OutVals[realRVLocIdx];
2990     bool ReturnF16 = false;
2991 
2992     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2993       // Half-precision return values can be returned like this:
2994       //
2995       // t11 f16 = fadd ...
2996       // t12: i16 = bitcast t11
2997       //   t13: i32 = zero_extend t12
2998       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2999       //
3000       // to avoid code generation for bitcasts, we simply set Arg to the node
3001       // that produces the f16 value, t11 in this case.
3002       //
3003       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3004         SDValue ZE = Arg.getOperand(0);
3005         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3006           SDValue BC = ZE.getOperand(0);
3007           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3008             Arg = BC.getOperand(0);
3009             ReturnF16 = true;
3010           }
3011         }
3012       }
3013     }
3014 
3015     switch (VA.getLocInfo()) {
3016     default: llvm_unreachable("Unknown loc info!");
3017     case CCValAssign::Full: break;
3018     case CCValAssign::BCvt:
3019       if (!ReturnF16)
3020         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3021       break;
3022     }
3023 
3024     // Mask f16 arguments if this is a CMSE nonsecure entry.
3025     auto RetVT = Outs[realRVLocIdx].ArgVT;
3026     if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3027       if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3028         Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3029       } else {
3030         auto LocBits = VA.getLocVT().getSizeInBits();
3031         auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3032         SDValue Mask =
3033             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3034         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3035         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3036         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3037       }
3038     }
3039 
3040     if (VA.needsCustom() &&
3041         (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3042       if (VA.getLocVT() == MVT::v2f64) {
3043         // Extract the first half and return it in two registers.
3044         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3045                                    DAG.getConstant(0, dl, MVT::i32));
3046         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3047                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
3048 
3049         Chain =
3050             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3051                              HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3052         Flag = Chain.getValue(1);
3053         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3054         VA = RVLocs[++i]; // skip ahead to next loc
3055         Chain =
3056             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3057                              HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3058         Flag = Chain.getValue(1);
3059         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3060         VA = RVLocs[++i]; // skip ahead to next loc
3061 
3062         // Extract the 2nd half and fall through to handle it as an f64 value.
3063         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3064                           DAG.getConstant(1, dl, MVT::i32));
3065       }
3066       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
3067       // available.
3068       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3069                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
3070       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3071                                fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3072       Flag = Chain.getValue(1);
3073       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3074       VA = RVLocs[++i]; // skip ahead to next loc
3075       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3076                                fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3077     } else
3078       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3079 
3080     // Guarantee that all emitted copies are
3081     // stuck together, avoiding something bad.
3082     Flag = Chain.getValue(1);
3083     RetOps.push_back(DAG.getRegister(
3084         VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3085   }
3086   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3087   const MCPhysReg *I =
3088       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3089   if (I) {
3090     for (; *I; ++I) {
3091       if (ARM::GPRRegClass.contains(*I))
3092         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3093       else if (ARM::DPRRegClass.contains(*I))
3094         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3095       else
3096         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3097     }
3098   }
3099 
3100   // Update chain and glue.
3101   RetOps[0] = Chain;
3102   if (Flag.getNode())
3103     RetOps.push_back(Flag);
3104 
3105   // CPUs which aren't M-class use a special sequence to return from
3106   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3107   // though we use "subs pc, lr, #N").
3108   //
3109   // M-class CPUs actually use a normal return sequence with a special
3110   // (hardware-provided) value in LR, so the normal code path works.
3111   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3112       !Subtarget->isMClass()) {
3113     if (Subtarget->isThumb1Only())
3114       report_fatal_error("interrupt attribute is not supported in Thumb1");
3115     return LowerInterruptReturn(RetOps, dl, DAG);
3116   }
3117 
3118   ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3119                                                             ARMISD::RET_FLAG;
3120   return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3121 }
3122 
3123 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3124   if (N->getNumValues() != 1)
3125     return false;
3126   if (!N->hasNUsesOfValue(1, 0))
3127     return false;
3128 
3129   SDValue TCChain = Chain;
3130   SDNode *Copy = *N->use_begin();
3131   if (Copy->getOpcode() == ISD::CopyToReg) {
3132     // If the copy has a glue operand, we conservatively assume it isn't safe to
3133     // perform a tail call.
3134     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3135       return false;
3136     TCChain = Copy->getOperand(0);
3137   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3138     SDNode *VMov = Copy;
3139     // f64 returned in a pair of GPRs.
3140     SmallPtrSet<SDNode*, 2> Copies;
3141     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3142          UI != UE; ++UI) {
3143       if (UI->getOpcode() != ISD::CopyToReg)
3144         return false;
3145       Copies.insert(*UI);
3146     }
3147     if (Copies.size() > 2)
3148       return false;
3149 
3150     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3151          UI != UE; ++UI) {
3152       SDValue UseChain = UI->getOperand(0);
3153       if (Copies.count(UseChain.getNode()))
3154         // Second CopyToReg
3155         Copy = *UI;
3156       else {
3157         // We are at the top of this chain.
3158         // If the copy has a glue operand, we conservatively assume it
3159         // isn't safe to perform a tail call.
3160         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3161           return false;
3162         // First CopyToReg
3163         TCChain = UseChain;
3164       }
3165     }
3166   } else if (Copy->getOpcode() == ISD::BITCAST) {
3167     // f32 returned in a single GPR.
3168     if (!Copy->hasOneUse())
3169       return false;
3170     Copy = *Copy->use_begin();
3171     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3172       return false;
3173     // If the copy has a glue operand, we conservatively assume it isn't safe to
3174     // perform a tail call.
3175     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3176       return false;
3177     TCChain = Copy->getOperand(0);
3178   } else {
3179     return false;
3180   }
3181 
3182   bool HasRet = false;
3183   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3184        UI != UE; ++UI) {
3185     if (UI->getOpcode() != ARMISD::RET_FLAG &&
3186         UI->getOpcode() != ARMISD::INTRET_FLAG)
3187       return false;
3188     HasRet = true;
3189   }
3190 
3191   if (!HasRet)
3192     return false;
3193 
3194   Chain = TCChain;
3195   return true;
3196 }
3197 
3198 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3199   if (!Subtarget->supportsTailCall())
3200     return false;
3201 
3202   if (!CI->isTailCall())
3203     return false;
3204 
3205   return true;
3206 }
3207 
3208 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3209 // and pass the lower and high parts through.
3210 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3211   SDLoc DL(Op);
3212   SDValue WriteValue = Op->getOperand(2);
3213 
3214   // This function is only supposed to be called for i64 type argument.
3215   assert(WriteValue.getValueType() == MVT::i64
3216           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3217 
3218   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3219                            DAG.getConstant(0, DL, MVT::i32));
3220   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3221                            DAG.getConstant(1, DL, MVT::i32));
3222   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3223   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3224 }
3225 
3226 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3227 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3228 // one of the above mentioned nodes. It has to be wrapped because otherwise
3229 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3230 // be used to form addressing mode. These wrapped nodes will be selected
3231 // into MOVi.
3232 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3233                                              SelectionDAG &DAG) const {
3234   EVT PtrVT = Op.getValueType();
3235   // FIXME there is no actual debug info here
3236   SDLoc dl(Op);
3237   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3238   SDValue Res;
3239 
3240   // When generating execute-only code Constant Pools must be promoted to the
3241   // global data section. It's a bit ugly that we can't share them across basic
3242   // blocks, but this way we guarantee that execute-only behaves correct with
3243   // position-independent addressing modes.
3244   if (Subtarget->genExecuteOnly()) {
3245     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3246     auto T = const_cast<Type*>(CP->getType());
3247     auto C = const_cast<Constant*>(CP->getConstVal());
3248     auto M = const_cast<Module*>(DAG.getMachineFunction().
3249                                  getFunction().getParent());
3250     auto GV = new GlobalVariable(
3251                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3252                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3253                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3254                     Twine(AFI->createPICLabelUId())
3255                   );
3256     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3257                                             dl, PtrVT);
3258     return LowerGlobalAddress(GA, DAG);
3259   }
3260 
3261   if (CP->isMachineConstantPoolEntry())
3262     Res =
3263         DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3264   else
3265     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3266   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3267 }
3268 
3269 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3270   return MachineJumpTableInfo::EK_Inline;
3271 }
3272 
3273 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3274                                              SelectionDAG &DAG) const {
3275   MachineFunction &MF = DAG.getMachineFunction();
3276   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3277   unsigned ARMPCLabelIndex = 0;
3278   SDLoc DL(Op);
3279   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3280   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3281   SDValue CPAddr;
3282   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3283   if (!IsPositionIndependent) {
3284     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3285   } else {
3286     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3287     ARMPCLabelIndex = AFI->createPICLabelUId();
3288     ARMConstantPoolValue *CPV =
3289       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3290                                       ARMCP::CPBlockAddress, PCAdj);
3291     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3292   }
3293   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3294   SDValue Result = DAG.getLoad(
3295       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3296       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3297   if (!IsPositionIndependent)
3298     return Result;
3299   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3300   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3301 }
3302 
3303 /// Convert a TLS address reference into the correct sequence of loads
3304 /// and calls to compute the variable's address for Darwin, and return an
3305 /// SDValue containing the final node.
3306 
3307 /// Darwin only has one TLS scheme which must be capable of dealing with the
3308 /// fully general situation, in the worst case. This means:
3309 ///     + "extern __thread" declaration.
3310 ///     + Defined in a possibly unknown dynamic library.
3311 ///
3312 /// The general system is that each __thread variable has a [3 x i32] descriptor
3313 /// which contains information used by the runtime to calculate the address. The
3314 /// only part of this the compiler needs to know about is the first word, which
3315 /// contains a function pointer that must be called with the address of the
3316 /// entire descriptor in "r0".
3317 ///
3318 /// Since this descriptor may be in a different unit, in general access must
3319 /// proceed along the usual ARM rules. A common sequence to produce is:
3320 ///
3321 ///     movw rT1, :lower16:_var$non_lazy_ptr
3322 ///     movt rT1, :upper16:_var$non_lazy_ptr
3323 ///     ldr r0, [rT1]
3324 ///     ldr rT2, [r0]
3325 ///     blx rT2
3326 ///     [...address now in r0...]
3327 SDValue
3328 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3329                                                SelectionDAG &DAG) const {
3330   assert(Subtarget->isTargetDarwin() &&
3331          "This function expects a Darwin target");
3332   SDLoc DL(Op);
3333 
3334   // First step is to get the address of the actua global symbol. This is where
3335   // the TLS descriptor lives.
3336   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3337 
3338   // The first entry in the descriptor is a function pointer that we must call
3339   // to obtain the address of the variable.
3340   SDValue Chain = DAG.getEntryNode();
3341   SDValue FuncTLVGet = DAG.getLoad(
3342       MVT::i32, DL, Chain, DescAddr,
3343       MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3344       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3345           MachineMemOperand::MOInvariant);
3346   Chain = FuncTLVGet.getValue(1);
3347 
3348   MachineFunction &F = DAG.getMachineFunction();
3349   MachineFrameInfo &MFI = F.getFrameInfo();
3350   MFI.setAdjustsStack(true);
3351 
3352   // TLS calls preserve all registers except those that absolutely must be
3353   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3354   // silly).
3355   auto TRI =
3356       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3357   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3358   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3359 
3360   // Finally, we can make the call. This is just a degenerate version of a
3361   // normal AArch64 call node: r0 takes the address of the descriptor, and
3362   // returns the address of the variable in this thread.
3363   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3364   Chain =
3365       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3366                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3367                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3368   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3369 }
3370 
3371 SDValue
3372 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3373                                                 SelectionDAG &DAG) const {
3374   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3375 
3376   SDValue Chain = DAG.getEntryNode();
3377   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3378   SDLoc DL(Op);
3379 
3380   // Load the current TEB (thread environment block)
3381   SDValue Ops[] = {Chain,
3382                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3383                    DAG.getTargetConstant(15, DL, MVT::i32),
3384                    DAG.getTargetConstant(0, DL, MVT::i32),
3385                    DAG.getTargetConstant(13, DL, MVT::i32),
3386                    DAG.getTargetConstant(0, DL, MVT::i32),
3387                    DAG.getTargetConstant(2, DL, MVT::i32)};
3388   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3389                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3390 
3391   SDValue TEB = CurrentTEB.getValue(0);
3392   Chain = CurrentTEB.getValue(1);
3393 
3394   // Load the ThreadLocalStoragePointer from the TEB
3395   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3396   SDValue TLSArray =
3397       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3398   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3399 
3400   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3401   // offset into the TLSArray.
3402 
3403   // Load the TLS index from the C runtime
3404   SDValue TLSIndex =
3405       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3406   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3407   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3408 
3409   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3410                               DAG.getConstant(2, DL, MVT::i32));
3411   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3412                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3413                             MachinePointerInfo());
3414 
3415   // Get the offset of the start of the .tls section (section base)
3416   const auto *GA = cast<GlobalAddressSDNode>(Op);
3417   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3418   SDValue Offset = DAG.getLoad(
3419       PtrVT, DL, Chain,
3420       DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3421                   DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3422       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3423 
3424   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3425 }
3426 
3427 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3428 SDValue
3429 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3430                                                  SelectionDAG &DAG) const {
3431   SDLoc dl(GA);
3432   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3433   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3434   MachineFunction &MF = DAG.getMachineFunction();
3435   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3436   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3437   ARMConstantPoolValue *CPV =
3438     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3439                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3440   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3441   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3442   Argument = DAG.getLoad(
3443       PtrVT, dl, DAG.getEntryNode(), Argument,
3444       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3445   SDValue Chain = Argument.getValue(1);
3446 
3447   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3448   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3449 
3450   // call __tls_get_addr.
3451   ArgListTy Args;
3452   ArgListEntry Entry;
3453   Entry.Node = Argument;
3454   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3455   Args.push_back(Entry);
3456 
3457   // FIXME: is there useful debug info available here?
3458   TargetLowering::CallLoweringInfo CLI(DAG);
3459   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3460       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3461       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3462 
3463   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3464   return CallResult.first;
3465 }
3466 
3467 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3468 // "local exec" model.
3469 SDValue
3470 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3471                                         SelectionDAG &DAG,
3472                                         TLSModel::Model model) const {
3473   const GlobalValue *GV = GA->getGlobal();
3474   SDLoc dl(GA);
3475   SDValue Offset;
3476   SDValue Chain = DAG.getEntryNode();
3477   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3478   // Get the Thread Pointer
3479   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3480 
3481   if (model == TLSModel::InitialExec) {
3482     MachineFunction &MF = DAG.getMachineFunction();
3483     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3484     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3485     // Initial exec model.
3486     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3487     ARMConstantPoolValue *CPV =
3488       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3489                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3490                                       true);
3491     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3492     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3493     Offset = DAG.getLoad(
3494         PtrVT, dl, Chain, Offset,
3495         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3496     Chain = Offset.getValue(1);
3497 
3498     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3499     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3500 
3501     Offset = DAG.getLoad(
3502         PtrVT, dl, Chain, Offset,
3503         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3504   } else {
3505     // local exec model
3506     assert(model == TLSModel::LocalExec);
3507     ARMConstantPoolValue *CPV =
3508       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3509     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3510     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3511     Offset = DAG.getLoad(
3512         PtrVT, dl, Chain, Offset,
3513         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3514   }
3515 
3516   // The address of the thread local variable is the add of the thread
3517   // pointer with the offset of the variable.
3518   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3519 }
3520 
3521 SDValue
3522 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3523   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3524   if (DAG.getTarget().useEmulatedTLS())
3525     return LowerToTLSEmulatedModel(GA, DAG);
3526 
3527   if (Subtarget->isTargetDarwin())
3528     return LowerGlobalTLSAddressDarwin(Op, DAG);
3529 
3530   if (Subtarget->isTargetWindows())
3531     return LowerGlobalTLSAddressWindows(Op, DAG);
3532 
3533   // TODO: implement the "local dynamic" model
3534   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3535   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3536 
3537   switch (model) {
3538     case TLSModel::GeneralDynamic:
3539     case TLSModel::LocalDynamic:
3540       return LowerToTLSGeneralDynamicModel(GA, DAG);
3541     case TLSModel::InitialExec:
3542     case TLSModel::LocalExec:
3543       return LowerToTLSExecModels(GA, DAG, model);
3544   }
3545   llvm_unreachable("bogus TLS model");
3546 }
3547 
3548 /// Return true if all users of V are within function F, looking through
3549 /// ConstantExprs.
3550 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3551   SmallVector<const User*,4> Worklist;
3552   for (auto *U : V->users())
3553     Worklist.push_back(U);
3554   while (!Worklist.empty()) {
3555     auto *U = Worklist.pop_back_val();
3556     if (isa<ConstantExpr>(U)) {
3557       for (auto *UU : U->users())
3558         Worklist.push_back(UU);
3559       continue;
3560     }
3561 
3562     auto *I = dyn_cast<Instruction>(U);
3563     if (!I || I->getParent()->getParent() != F)
3564       return false;
3565   }
3566   return true;
3567 }
3568 
3569 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3570                                      const GlobalValue *GV, SelectionDAG &DAG,
3571                                      EVT PtrVT, const SDLoc &dl) {
3572   // If we're creating a pool entry for a constant global with unnamed address,
3573   // and the global is small enough, we can emit it inline into the constant pool
3574   // to save ourselves an indirection.
3575   //
3576   // This is a win if the constant is only used in one function (so it doesn't
3577   // need to be duplicated) or duplicating the constant wouldn't increase code
3578   // size (implying the constant is no larger than 4 bytes).
3579   const Function &F = DAG.getMachineFunction().getFunction();
3580 
3581   // We rely on this decision to inline being idemopotent and unrelated to the
3582   // use-site. We know that if we inline a variable at one use site, we'll
3583   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3584   // doesn't know about this optimization, so bail out if it's enabled else
3585   // we could decide to inline here (and thus never emit the GV) but require
3586   // the GV from fast-isel generated code.
3587   if (!EnableConstpoolPromotion ||
3588       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3589       return SDValue();
3590 
3591   auto *GVar = dyn_cast<GlobalVariable>(GV);
3592   if (!GVar || !GVar->hasInitializer() ||
3593       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3594       !GVar->hasLocalLinkage())
3595     return SDValue();
3596 
3597   // If we inline a value that contains relocations, we move the relocations
3598   // from .data to .text. This is not allowed in position-independent code.
3599   auto *Init = GVar->getInitializer();
3600   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3601       Init->needsRelocation())
3602     return SDValue();
3603 
3604   // The constant islands pass can only really deal with alignment requests
3605   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3606   // any type wanting greater alignment requirements than 4 bytes. We also
3607   // can only promote constants that are multiples of 4 bytes in size or
3608   // are paddable to a multiple of 4. Currently we only try and pad constants
3609   // that are strings for simplicity.
3610   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3611   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3612   Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3613   unsigned RequiredPadding = 4 - (Size % 4);
3614   bool PaddingPossible =
3615     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3616   if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3617       Size == 0)
3618     return SDValue();
3619 
3620   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3621   MachineFunction &MF = DAG.getMachineFunction();
3622   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3623 
3624   // We can't bloat the constant pool too much, else the ConstantIslands pass
3625   // may fail to converge. If we haven't promoted this global yet (it may have
3626   // multiple uses), and promoting it would increase the constant pool size (Sz
3627   // > 4), ensure we have space to do so up to MaxTotal.
3628   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3629     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3630         ConstpoolPromotionMaxTotal)
3631       return SDValue();
3632 
3633   // This is only valid if all users are in a single function; we can't clone
3634   // the constant in general. The LLVM IR unnamed_addr allows merging
3635   // constants, but not cloning them.
3636   //
3637   // We could potentially allow cloning if we could prove all uses of the
3638   // constant in the current function don't care about the address, like
3639   // printf format strings. But that isn't implemented for now.
3640   if (!allUsersAreInFunction(GVar, &F))
3641     return SDValue();
3642 
3643   // We're going to inline this global. Pad it out if needed.
3644   if (RequiredPadding != 4) {
3645     StringRef S = CDAInit->getAsString();
3646 
3647     SmallVector<uint8_t,16> V(S.size());
3648     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3649     while (RequiredPadding--)
3650       V.push_back(0);
3651     Init = ConstantDataArray::get(*DAG.getContext(), V);
3652   }
3653 
3654   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3655   SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3656   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3657     AFI->markGlobalAsPromotedToConstantPool(GVar);
3658     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3659                                       PaddedSize - 4);
3660   }
3661   ++NumConstpoolPromoted;
3662   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3663 }
3664 
3665 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3666   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3667     if (!(GV = GA->getBaseObject()))
3668       return false;
3669   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3670     return V->isConstant();
3671   return isa<Function>(GV);
3672 }
3673 
3674 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3675                                               SelectionDAG &DAG) const {
3676   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3677   default: llvm_unreachable("unknown object format");
3678   case Triple::COFF:
3679     return LowerGlobalAddressWindows(Op, DAG);
3680   case Triple::ELF:
3681     return LowerGlobalAddressELF(Op, DAG);
3682   case Triple::MachO:
3683     return LowerGlobalAddressDarwin(Op, DAG);
3684   }
3685 }
3686 
3687 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3688                                                  SelectionDAG &DAG) const {
3689   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3690   SDLoc dl(Op);
3691   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3692   const TargetMachine &TM = getTargetMachine();
3693   bool IsRO = isReadOnly(GV);
3694 
3695   // promoteToConstantPool only if not generating XO text section
3696   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3697     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3698       return V;
3699 
3700   if (isPositionIndependent()) {
3701     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3702     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3703                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3704     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3705     if (UseGOT_PREL)
3706       Result =
3707           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3708                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3709     return Result;
3710   } else if (Subtarget->isROPI() && IsRO) {
3711     // PC-relative.
3712     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3713     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3714     return Result;
3715   } else if (Subtarget->isRWPI() && !IsRO) {
3716     // SB-relative.
3717     SDValue RelAddr;
3718     if (Subtarget->useMovt()) {
3719       ++NumMovwMovt;
3720       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3721       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3722     } else { // use literal pool for address constant
3723       ARMConstantPoolValue *CPV =
3724         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3725       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3726       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3727       RelAddr = DAG.getLoad(
3728           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3729           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3730     }
3731     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3732     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3733     return Result;
3734   }
3735 
3736   // If we have T2 ops, we can materialize the address directly via movt/movw
3737   // pair. This is always cheaper.
3738   if (Subtarget->useMovt()) {
3739     ++NumMovwMovt;
3740     // FIXME: Once remat is capable of dealing with instructions with register
3741     // operands, expand this into two nodes.
3742     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3743                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3744   } else {
3745     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3746     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3747     return DAG.getLoad(
3748         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3749         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3750   }
3751 }
3752 
3753 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3754                                                     SelectionDAG &DAG) const {
3755   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3756          "ROPI/RWPI not currently supported for Darwin");
3757   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3758   SDLoc dl(Op);
3759   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3760 
3761   if (Subtarget->useMovt())
3762     ++NumMovwMovt;
3763 
3764   // FIXME: Once remat is capable of dealing with instructions with register
3765   // operands, expand this into multiple nodes
3766   unsigned Wrapper =
3767       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3768 
3769   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3770   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3771 
3772   if (Subtarget->isGVIndirectSymbol(GV))
3773     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3774                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3775   return Result;
3776 }
3777 
3778 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3779                                                      SelectionDAG &DAG) const {
3780   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3781   assert(Subtarget->useMovt() &&
3782          "Windows on ARM expects to use movw/movt");
3783   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3784          "ROPI/RWPI not currently supported for Windows");
3785 
3786   const TargetMachine &TM = getTargetMachine();
3787   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3788   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3789   if (GV->hasDLLImportStorageClass())
3790     TargetFlags = ARMII::MO_DLLIMPORT;
3791   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3792     TargetFlags = ARMII::MO_COFFSTUB;
3793   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3794   SDValue Result;
3795   SDLoc DL(Op);
3796 
3797   ++NumMovwMovt;
3798 
3799   // FIXME: Once remat is capable of dealing with instructions with register
3800   // operands, expand this into two nodes.
3801   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3802                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3803                                                   TargetFlags));
3804   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3805     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3806                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3807   return Result;
3808 }
3809 
3810 SDValue
3811 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3812   SDLoc dl(Op);
3813   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3814   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3815                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3816                      Op.getOperand(1), Val);
3817 }
3818 
3819 SDValue
3820 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3821   SDLoc dl(Op);
3822   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3823                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3824 }
3825 
3826 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3827                                                       SelectionDAG &DAG) const {
3828   SDLoc dl(Op);
3829   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3830                      Op.getOperand(0));
3831 }
3832 
3833 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3834     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3835   unsigned IntNo =
3836       cast<ConstantSDNode>(
3837           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3838           ->getZExtValue();
3839   switch (IntNo) {
3840     default:
3841       return SDValue();  // Don't custom lower most intrinsics.
3842     case Intrinsic::arm_gnu_eabi_mcount: {
3843       MachineFunction &MF = DAG.getMachineFunction();
3844       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3845       SDLoc dl(Op);
3846       SDValue Chain = Op.getOperand(0);
3847       // call "\01__gnu_mcount_nc"
3848       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3849       const uint32_t *Mask =
3850           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3851       assert(Mask && "Missing call preserved mask for calling convention");
3852       // Mark LR an implicit live-in.
3853       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3854       SDValue ReturnAddress =
3855           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3856       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3857       SDValue Callee =
3858           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3859       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3860       if (Subtarget->isThumb())
3861         return SDValue(
3862             DAG.getMachineNode(
3863                 ARM::tBL_PUSHLR, dl, ResultTys,
3864                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3865                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3866             0);
3867       return SDValue(
3868           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3869                              {ReturnAddress, Callee, RegisterMask, Chain}),
3870           0);
3871     }
3872   }
3873 }
3874 
3875 SDValue
3876 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3877                                           const ARMSubtarget *Subtarget) const {
3878   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3879   SDLoc dl(Op);
3880   switch (IntNo) {
3881   default: return SDValue();    // Don't custom lower most intrinsics.
3882   case Intrinsic::thread_pointer: {
3883     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3884     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3885   }
3886   case Intrinsic::arm_cls: {
3887     const SDValue &Operand = Op.getOperand(1);
3888     const EVT VTy = Op.getValueType();
3889     SDValue SRA =
3890         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3891     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3892     SDValue SHL =
3893         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3894     SDValue OR =
3895         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3896     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3897     return Result;
3898   }
3899   case Intrinsic::arm_cls64: {
3900     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3901     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3902     const SDValue &Operand = Op.getOperand(1);
3903     const EVT VTy = Op.getValueType();
3904 
3905     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3906                              DAG.getConstant(1, dl, VTy));
3907     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3908                              DAG.getConstant(0, dl, VTy));
3909     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3910     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3911     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3912     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3913     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3914     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3915     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3916     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3917     SDValue CheckLo =
3918         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3919     SDValue HiIsZero =
3920         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3921     SDValue AdjustedLo =
3922         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3923     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3924     SDValue Result =
3925         DAG.getSelect(dl, VTy, CheckLo,
3926                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3927     return Result;
3928   }
3929   case Intrinsic::eh_sjlj_lsda: {
3930     MachineFunction &MF = DAG.getMachineFunction();
3931     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3932     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3933     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3934     SDValue CPAddr;
3935     bool IsPositionIndependent = isPositionIndependent();
3936     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3937     ARMConstantPoolValue *CPV =
3938       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3939                                       ARMCP::CPLSDA, PCAdj);
3940     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3941     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3942     SDValue Result = DAG.getLoad(
3943         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3944         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3945 
3946     if (IsPositionIndependent) {
3947       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3948       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3949     }
3950     return Result;
3951   }
3952   case Intrinsic::arm_neon_vabs:
3953     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3954                         Op.getOperand(1));
3955   case Intrinsic::arm_neon_vmulls:
3956   case Intrinsic::arm_neon_vmullu: {
3957     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3958       ? ARMISD::VMULLs : ARMISD::VMULLu;
3959     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3960                        Op.getOperand(1), Op.getOperand(2));
3961   }
3962   case Intrinsic::arm_neon_vminnm:
3963   case Intrinsic::arm_neon_vmaxnm: {
3964     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3965       ? ISD::FMINNUM : ISD::FMAXNUM;
3966     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3967                        Op.getOperand(1), Op.getOperand(2));
3968   }
3969   case Intrinsic::arm_neon_vminu:
3970   case Intrinsic::arm_neon_vmaxu: {
3971     if (Op.getValueType().isFloatingPoint())
3972       return SDValue();
3973     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3974       ? ISD::UMIN : ISD::UMAX;
3975     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3976                          Op.getOperand(1), Op.getOperand(2));
3977   }
3978   case Intrinsic::arm_neon_vmins:
3979   case Intrinsic::arm_neon_vmaxs: {
3980     // v{min,max}s is overloaded between signed integers and floats.
3981     if (!Op.getValueType().isFloatingPoint()) {
3982       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3983         ? ISD::SMIN : ISD::SMAX;
3984       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3985                          Op.getOperand(1), Op.getOperand(2));
3986     }
3987     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3988       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3989     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3990                        Op.getOperand(1), Op.getOperand(2));
3991   }
3992   case Intrinsic::arm_neon_vtbl1:
3993     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3994                        Op.getOperand(1), Op.getOperand(2));
3995   case Intrinsic::arm_neon_vtbl2:
3996     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3997                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3998   case Intrinsic::arm_mve_pred_i2v:
3999   case Intrinsic::arm_mve_pred_v2i:
4000     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4001                        Op.getOperand(1));
4002   case Intrinsic::arm_mve_vreinterpretq:
4003     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4004                        Op.getOperand(1));
4005   case Intrinsic::arm_mve_lsll:
4006     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4007                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4008   case Intrinsic::arm_mve_asrl:
4009     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4010                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4011   }
4012 }
4013 
4014 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4015                                  const ARMSubtarget *Subtarget) {
4016   SDLoc dl(Op);
4017   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4018   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4019   if (SSID == SyncScope::SingleThread)
4020     return Op;
4021 
4022   if (!Subtarget->hasDataBarrier()) {
4023     // Some ARMv6 cpus can support data barriers with an mcr instruction.
4024     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4025     // here.
4026     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4027            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4028     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4029                        DAG.getConstant(0, dl, MVT::i32));
4030   }
4031 
4032   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4033   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4034   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4035   if (Subtarget->isMClass()) {
4036     // Only a full system barrier exists in the M-class architectures.
4037     Domain = ARM_MB::SY;
4038   } else if (Subtarget->preferISHSTBarriers() &&
4039              Ord == AtomicOrdering::Release) {
4040     // Swift happens to implement ISHST barriers in a way that's compatible with
4041     // Release semantics but weaker than ISH so we'd be fools not to use
4042     // it. Beware: other processors probably don't!
4043     Domain = ARM_MB::ISHST;
4044   }
4045 
4046   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4047                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4048                      DAG.getConstant(Domain, dl, MVT::i32));
4049 }
4050 
4051 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4052                              const ARMSubtarget *Subtarget) {
4053   // ARM pre v5TE and Thumb1 does not have preload instructions.
4054   if (!(Subtarget->isThumb2() ||
4055         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4056     // Just preserve the chain.
4057     return Op.getOperand(0);
4058 
4059   SDLoc dl(Op);
4060   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4061   if (!isRead &&
4062       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4063     // ARMv7 with MP extension has PLDW.
4064     return Op.getOperand(0);
4065 
4066   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4067   if (Subtarget->isThumb()) {
4068     // Invert the bits.
4069     isRead = ~isRead & 1;
4070     isData = ~isData & 1;
4071   }
4072 
4073   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4074                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4075                      DAG.getConstant(isData, dl, MVT::i32));
4076 }
4077 
4078 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4079   MachineFunction &MF = DAG.getMachineFunction();
4080   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4081 
4082   // vastart just stores the address of the VarArgsFrameIndex slot into the
4083   // memory location argument.
4084   SDLoc dl(Op);
4085   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4086   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4087   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4088   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4089                       MachinePointerInfo(SV));
4090 }
4091 
4092 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4093                                                 CCValAssign &NextVA,
4094                                                 SDValue &Root,
4095                                                 SelectionDAG &DAG,
4096                                                 const SDLoc &dl) const {
4097   MachineFunction &MF = DAG.getMachineFunction();
4098   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4099 
4100   const TargetRegisterClass *RC;
4101   if (AFI->isThumb1OnlyFunction())
4102     RC = &ARM::tGPRRegClass;
4103   else
4104     RC = &ARM::GPRRegClass;
4105 
4106   // Transform the arguments stored in physical registers into virtual ones.
4107   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4108   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4109 
4110   SDValue ArgValue2;
4111   if (NextVA.isMemLoc()) {
4112     MachineFrameInfo &MFI = MF.getFrameInfo();
4113     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4114 
4115     // Create load node to retrieve arguments from the stack.
4116     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4117     ArgValue2 = DAG.getLoad(
4118         MVT::i32, dl, Root, FIN,
4119         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4120   } else {
4121     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4122     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4123   }
4124   if (!Subtarget->isLittle())
4125     std::swap (ArgValue, ArgValue2);
4126   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4127 }
4128 
4129 // The remaining GPRs hold either the beginning of variable-argument
4130 // data, or the beginning of an aggregate passed by value (usually
4131 // byval).  Either way, we allocate stack slots adjacent to the data
4132 // provided by our caller, and store the unallocated registers there.
4133 // If this is a variadic function, the va_list pointer will begin with
4134 // these values; otherwise, this reassembles a (byval) structure that
4135 // was split between registers and memory.
4136 // Return: The frame index registers were stored into.
4137 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4138                                       const SDLoc &dl, SDValue &Chain,
4139                                       const Value *OrigArg,
4140                                       unsigned InRegsParamRecordIdx,
4141                                       int ArgOffset, unsigned ArgSize) const {
4142   // Currently, two use-cases possible:
4143   // Case #1. Non-var-args function, and we meet first byval parameter.
4144   //          Setup first unallocated register as first byval register;
4145   //          eat all remained registers
4146   //          (these two actions are performed by HandleByVal method).
4147   //          Then, here, we initialize stack frame with
4148   //          "store-reg" instructions.
4149   // Case #2. Var-args function, that doesn't contain byval parameters.
4150   //          The same: eat all remained unallocated registers,
4151   //          initialize stack frame.
4152 
4153   MachineFunction &MF = DAG.getMachineFunction();
4154   MachineFrameInfo &MFI = MF.getFrameInfo();
4155   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4156   unsigned RBegin, REnd;
4157   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4158     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4159   } else {
4160     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4161     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4162     REnd = ARM::R4;
4163   }
4164 
4165   if (REnd != RBegin)
4166     ArgOffset = -4 * (ARM::R4 - RBegin);
4167 
4168   auto PtrVT = getPointerTy(DAG.getDataLayout());
4169   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4170   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4171 
4172   SmallVector<SDValue, 4> MemOps;
4173   const TargetRegisterClass *RC =
4174       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4175 
4176   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4177     unsigned VReg = MF.addLiveIn(Reg, RC);
4178     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4179     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4180                                  MachinePointerInfo(OrigArg, 4 * i));
4181     MemOps.push_back(Store);
4182     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4183   }
4184 
4185   if (!MemOps.empty())
4186     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4187   return FrameIndex;
4188 }
4189 
4190 // Setup stack frame, the va_list pointer will start from.
4191 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4192                                              const SDLoc &dl, SDValue &Chain,
4193                                              unsigned ArgOffset,
4194                                              unsigned TotalArgRegsSaveSize,
4195                                              bool ForceMutable) const {
4196   MachineFunction &MF = DAG.getMachineFunction();
4197   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4198 
4199   // Try to store any remaining integer argument regs
4200   // to their spots on the stack so that they may be loaded by dereferencing
4201   // the result of va_next.
4202   // If there is no regs to be stored, just point address after last
4203   // argument passed via stack.
4204   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4205                                   CCInfo.getInRegsParamsCount(),
4206                                   CCInfo.getNextStackOffset(),
4207                                   std::max(4U, TotalArgRegsSaveSize));
4208   AFI->setVarArgsFrameIndex(FrameIndex);
4209 }
4210 
4211 bool ARMTargetLowering::splitValueIntoRegisterParts(
4212     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4213     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4214   bool IsABIRegCopy = CC.hasValue();
4215   EVT ValueVT = Val.getValueType();
4216   if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4217       PartVT == MVT::f32) {
4218     unsigned ValueBits = ValueVT.getSizeInBits();
4219     unsigned PartBits = PartVT.getSizeInBits();
4220     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4221     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4222     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4223     Parts[0] = Val;
4224     return true;
4225   }
4226   return false;
4227 }
4228 
4229 SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4230     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4231     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4232   bool IsABIRegCopy = CC.hasValue();
4233   if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4234       PartVT == MVT::f32) {
4235     unsigned ValueBits = ValueVT.getSizeInBits();
4236     unsigned PartBits = PartVT.getSizeInBits();
4237     SDValue Val = Parts[0];
4238 
4239     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4240     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4241     Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4242     return Val;
4243   }
4244   return SDValue();
4245 }
4246 
4247 SDValue ARMTargetLowering::LowerFormalArguments(
4248     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4249     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4250     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4251   MachineFunction &MF = DAG.getMachineFunction();
4252   MachineFrameInfo &MFI = MF.getFrameInfo();
4253 
4254   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4255 
4256   // Assign locations to all of the incoming arguments.
4257   SmallVector<CCValAssign, 16> ArgLocs;
4258   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4259                  *DAG.getContext());
4260   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4261 
4262   SmallVector<SDValue, 16> ArgValues;
4263   SDValue ArgValue;
4264   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4265   unsigned CurArgIdx = 0;
4266 
4267   // Initially ArgRegsSaveSize is zero.
4268   // Then we increase this value each time we meet byval parameter.
4269   // We also increase this value in case of varargs function.
4270   AFI->setArgRegsSaveSize(0);
4271 
4272   // Calculate the amount of stack space that we need to allocate to store
4273   // byval and variadic arguments that are passed in registers.
4274   // We need to know this before we allocate the first byval or variadic
4275   // argument, as they will be allocated a stack slot below the CFA (Canonical
4276   // Frame Address, the stack pointer at entry to the function).
4277   unsigned ArgRegBegin = ARM::R4;
4278   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4279     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4280       break;
4281 
4282     CCValAssign &VA = ArgLocs[i];
4283     unsigned Index = VA.getValNo();
4284     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4285     if (!Flags.isByVal())
4286       continue;
4287 
4288     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4289     unsigned RBegin, REnd;
4290     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4291     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4292 
4293     CCInfo.nextInRegsParam();
4294   }
4295   CCInfo.rewindByValRegsInfo();
4296 
4297   int lastInsIndex = -1;
4298   if (isVarArg && MFI.hasVAStart()) {
4299     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4300     if (RegIdx != array_lengthof(GPRArgRegs))
4301       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4302   }
4303 
4304   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4305   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4306   auto PtrVT = getPointerTy(DAG.getDataLayout());
4307 
4308   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4309     CCValAssign &VA = ArgLocs[i];
4310     if (Ins[VA.getValNo()].isOrigArg()) {
4311       std::advance(CurOrigArg,
4312                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4313       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4314     }
4315     // Arguments stored in registers.
4316     if (VA.isRegLoc()) {
4317       EVT RegVT = VA.getLocVT();
4318 
4319       if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4320         // f64 and vector types are split up into multiple registers or
4321         // combinations of registers and stack slots.
4322         SDValue ArgValue1 =
4323             GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4324         VA = ArgLocs[++i]; // skip ahead to next loc
4325         SDValue ArgValue2;
4326         if (VA.isMemLoc()) {
4327           int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4328           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4329           ArgValue2 = DAG.getLoad(
4330               MVT::f64, dl, Chain, FIN,
4331               MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4332         } else {
4333           ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4334         }
4335         ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4336         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4337                                ArgValue1, DAG.getIntPtrConstant(0, dl));
4338         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4339                                ArgValue2, DAG.getIntPtrConstant(1, dl));
4340       } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4341         ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4342       } else {
4343         const TargetRegisterClass *RC;
4344 
4345         if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4346           RC = &ARM::HPRRegClass;
4347         else if (RegVT == MVT::f32)
4348           RC = &ARM::SPRRegClass;
4349         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4350                  RegVT == MVT::v4bf16)
4351           RC = &ARM::DPRRegClass;
4352         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4353                  RegVT == MVT::v8bf16)
4354           RC = &ARM::QPRRegClass;
4355         else if (RegVT == MVT::i32)
4356           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4357                                            : &ARM::GPRRegClass;
4358         else
4359           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4360 
4361         // Transform the arguments in physical registers into virtual ones.
4362         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4363         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4364 
4365         // If this value is passed in r0 and has the returned attribute (e.g.
4366         // C++ 'structors), record this fact for later use.
4367         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4368           AFI->setPreservesR0();
4369         }
4370       }
4371 
4372       // If this is an 8 or 16-bit value, it is really passed promoted
4373       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4374       // truncate to the right size.
4375       switch (VA.getLocInfo()) {
4376       default: llvm_unreachable("Unknown loc info!");
4377       case CCValAssign::Full: break;
4378       case CCValAssign::BCvt:
4379         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4380         break;
4381       case CCValAssign::SExt:
4382         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4383                                DAG.getValueType(VA.getValVT()));
4384         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4385         break;
4386       case CCValAssign::ZExt:
4387         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4388                                DAG.getValueType(VA.getValVT()));
4389         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4390         break;
4391       }
4392 
4393       // f16 arguments have their size extended to 4 bytes and passed as if they
4394       // had been copied to the LSBs of a 32-bit register.
4395       // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4396       if (VA.needsCustom() &&
4397           (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4398         ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4399 
4400       InVals.push_back(ArgValue);
4401     } else { // VA.isRegLoc()
4402       // sanity check
4403       assert(VA.isMemLoc());
4404       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4405 
4406       int index = VA.getValNo();
4407 
4408       // Some Ins[] entries become multiple ArgLoc[] entries.
4409       // Process them only once.
4410       if (index != lastInsIndex)
4411         {
4412           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4413           // FIXME: For now, all byval parameter objects are marked mutable.
4414           // This can be changed with more analysis.
4415           // In case of tail call optimization mark all arguments mutable.
4416           // Since they could be overwritten by lowering of arguments in case of
4417           // a tail call.
4418           if (Flags.isByVal()) {
4419             assert(Ins[index].isOrigArg() &&
4420                    "Byval arguments cannot be implicit");
4421             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4422 
4423             int FrameIndex = StoreByValRegs(
4424                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4425                 VA.getLocMemOffset(), Flags.getByValSize());
4426             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4427             CCInfo.nextInRegsParam();
4428           } else {
4429             unsigned FIOffset = VA.getLocMemOffset();
4430             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4431                                            FIOffset, true);
4432 
4433             // Create load nodes to retrieve arguments from the stack.
4434             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4435             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4436                                          MachinePointerInfo::getFixedStack(
4437                                              DAG.getMachineFunction(), FI)));
4438           }
4439           lastInsIndex = index;
4440         }
4441     }
4442   }
4443 
4444   // varargs
4445   if (isVarArg && MFI.hasVAStart()) {
4446     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4447                          TotalArgRegsSaveSize);
4448     if (AFI->isCmseNSEntryFunction()) {
4449       DiagnosticInfoUnsupported Diag(
4450           DAG.getMachineFunction().getFunction(),
4451           "secure entry function must not be variadic", dl.getDebugLoc());
4452       DAG.getContext()->diagnose(Diag);
4453     }
4454   }
4455 
4456   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4457 
4458   if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4459     DiagnosticInfoUnsupported Diag(
4460         DAG.getMachineFunction().getFunction(),
4461         "secure entry function requires arguments on stack", dl.getDebugLoc());
4462     DAG.getContext()->diagnose(Diag);
4463   }
4464 
4465   return Chain;
4466 }
4467 
4468 /// isFloatingPointZero - Return true if this is +0.0.
4469 static bool isFloatingPointZero(SDValue Op) {
4470   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4471     return CFP->getValueAPF().isPosZero();
4472   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4473     // Maybe this has already been legalized into the constant pool?
4474     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4475       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4476       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4477         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4478           return CFP->getValueAPF().isPosZero();
4479     }
4480   } else if (Op->getOpcode() == ISD::BITCAST &&
4481              Op->getValueType(0) == MVT::f64) {
4482     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4483     // created by LowerConstantFP().
4484     SDValue BitcastOp = Op->getOperand(0);
4485     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4486         isNullConstant(BitcastOp->getOperand(0)))
4487       return true;
4488   }
4489   return false;
4490 }
4491 
4492 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4493 /// the given operands.
4494 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4495                                      SDValue &ARMcc, SelectionDAG &DAG,
4496                                      const SDLoc &dl) const {
4497   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4498     unsigned C = RHSC->getZExtValue();
4499     if (!isLegalICmpImmediate((int32_t)C)) {
4500       // Constant does not fit, try adjusting it by one.
4501       switch (CC) {
4502       default: break;
4503       case ISD::SETLT:
4504       case ISD::SETGE:
4505         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4506           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4507           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4508         }
4509         break;
4510       case ISD::SETULT:
4511       case ISD::SETUGE:
4512         if (C != 0 && isLegalICmpImmediate(C-1)) {
4513           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4514           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4515         }
4516         break;
4517       case ISD::SETLE:
4518       case ISD::SETGT:
4519         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4520           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4521           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4522         }
4523         break;
4524       case ISD::SETULE:
4525       case ISD::SETUGT:
4526         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4527           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4528           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4529         }
4530         break;
4531       }
4532     }
4533   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4534              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4535     // In ARM and Thumb-2, the compare instructions can shift their second
4536     // operand.
4537     CC = ISD::getSetCCSwappedOperands(CC);
4538     std::swap(LHS, RHS);
4539   }
4540 
4541   // Thumb1 has very limited immediate modes, so turning an "and" into a
4542   // shift can save multiple instructions.
4543   //
4544   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4545   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4546   // own. If it's the operand to an unsigned comparison with an immediate,
4547   // we can eliminate one of the shifts: we transform
4548   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4549   //
4550   // We avoid transforming cases which aren't profitable due to encoding
4551   // details:
4552   //
4553   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4554   // would not; in that case, we're essentially trading one immediate load for
4555   // another.
4556   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4557   // 3. C2 is zero; we have other code for this special case.
4558   //
4559   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4560   // instruction, since the AND is always one instruction anyway, but we could
4561   // use narrow instructions in some cases.
4562   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4563       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4564       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4565       !isSignedIntSetCC(CC)) {
4566     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4567     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4568     uint64_t RHSV = RHSC->getZExtValue();
4569     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4570       unsigned ShiftBits = countLeadingZeros(Mask);
4571       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4572         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4573         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4574         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4575       }
4576     }
4577   }
4578 
4579   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4580   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4581   // way a cmp would.
4582   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4583   // some tweaks to the heuristics for the previous and->shift transform.
4584   // FIXME: Optimize cases where the LHS isn't a shift.
4585   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4586       isa<ConstantSDNode>(RHS) &&
4587       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4588       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4589       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4590     unsigned ShiftAmt =
4591       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4592     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4593                                 DAG.getVTList(MVT::i32, MVT::i32),
4594                                 LHS.getOperand(0),
4595                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4596     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4597                                      Shift.getValue(1), SDValue());
4598     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4599     return Chain.getValue(1);
4600   }
4601 
4602   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4603 
4604   // If the RHS is a constant zero then the V (overflow) flag will never be
4605   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4606   // simpler for other passes (like the peephole optimiser) to deal with.
4607   if (isNullConstant(RHS)) {
4608     switch (CondCode) {
4609       default: break;
4610       case ARMCC::GE:
4611         CondCode = ARMCC::PL;
4612         break;
4613       case ARMCC::LT:
4614         CondCode = ARMCC::MI;
4615         break;
4616     }
4617   }
4618 
4619   ARMISD::NodeType CompareType;
4620   switch (CondCode) {
4621   default:
4622     CompareType = ARMISD::CMP;
4623     break;
4624   case ARMCC::EQ:
4625   case ARMCC::NE:
4626     // Uses only Z Flag
4627     CompareType = ARMISD::CMPZ;
4628     break;
4629   }
4630   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4631   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4632 }
4633 
4634 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4635 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4636                                      SelectionDAG &DAG, const SDLoc &dl,
4637                                      bool Signaling) const {
4638   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4639   SDValue Cmp;
4640   if (!isFloatingPointZero(RHS))
4641     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4642                       dl, MVT::Glue, LHS, RHS);
4643   else
4644     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4645                       dl, MVT::Glue, LHS);
4646   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4647 }
4648 
4649 /// duplicateCmp - Glue values can have only one use, so this function
4650 /// duplicates a comparison node.
4651 SDValue
4652 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4653   unsigned Opc = Cmp.getOpcode();
4654   SDLoc DL(Cmp);
4655   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4656     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4657 
4658   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4659   Cmp = Cmp.getOperand(0);
4660   Opc = Cmp.getOpcode();
4661   if (Opc == ARMISD::CMPFP)
4662     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4663   else {
4664     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4665     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4666   }
4667   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4668 }
4669 
4670 // This function returns three things: the arithmetic computation itself
4671 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4672 // comparison and the condition code define the case in which the arithmetic
4673 // computation *does not* overflow.
4674 std::pair<SDValue, SDValue>
4675 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4676                                  SDValue &ARMcc) const {
4677   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4678 
4679   SDValue Value, OverflowCmp;
4680   SDValue LHS = Op.getOperand(0);
4681   SDValue RHS = Op.getOperand(1);
4682   SDLoc dl(Op);
4683 
4684   // FIXME: We are currently always generating CMPs because we don't support
4685   // generating CMN through the backend. This is not as good as the natural
4686   // CMP case because it causes a register dependency and cannot be folded
4687   // later.
4688 
4689   switch (Op.getOpcode()) {
4690   default:
4691     llvm_unreachable("Unknown overflow instruction!");
4692   case ISD::SADDO:
4693     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4694     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4695     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4696     break;
4697   case ISD::UADDO:
4698     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4699     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4700     // We do not use it in the USUBO case as Value may not be used.
4701     Value = DAG.getNode(ARMISD::ADDC, dl,
4702                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4703                 .getValue(0);
4704     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4705     break;
4706   case ISD::SSUBO:
4707     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4708     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4709     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4710     break;
4711   case ISD::USUBO:
4712     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4713     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4714     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4715     break;
4716   case ISD::UMULO:
4717     // We generate a UMUL_LOHI and then check if the high word is 0.
4718     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4719     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4720                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4721                         LHS, RHS);
4722     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4723                               DAG.getConstant(0, dl, MVT::i32));
4724     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4725     break;
4726   case ISD::SMULO:
4727     // We generate a SMUL_LOHI and then check if all the bits of the high word
4728     // are the same as the sign bit of the low word.
4729     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4730     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4731                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4732                         LHS, RHS);
4733     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4734                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4735                                           Value.getValue(0),
4736                                           DAG.getConstant(31, dl, MVT::i32)));
4737     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4738     break;
4739   } // switch (...)
4740 
4741   return std::make_pair(Value, OverflowCmp);
4742 }
4743 
4744 SDValue
4745 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4746   // Let legalize expand this if it isn't a legal type yet.
4747   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4748     return SDValue();
4749 
4750   SDValue Value, OverflowCmp;
4751   SDValue ARMcc;
4752   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4753   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4754   SDLoc dl(Op);
4755   // We use 0 and 1 as false and true values.
4756   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4757   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4758   EVT VT = Op.getValueType();
4759 
4760   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4761                                  ARMcc, CCR, OverflowCmp);
4762 
4763   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4764   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4765 }
4766 
4767 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4768                                               SelectionDAG &DAG) {
4769   SDLoc DL(BoolCarry);
4770   EVT CarryVT = BoolCarry.getValueType();
4771 
4772   // This converts the boolean value carry into the carry flag by doing
4773   // ARMISD::SUBC Carry, 1
4774   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4775                               DAG.getVTList(CarryVT, MVT::i32),
4776                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4777   return Carry.getValue(1);
4778 }
4779 
4780 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4781                                               SelectionDAG &DAG) {
4782   SDLoc DL(Flags);
4783 
4784   // Now convert the carry flag into a boolean carry. We do this
4785   // using ARMISD:ADDE 0, 0, Carry
4786   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4787                      DAG.getConstant(0, DL, MVT::i32),
4788                      DAG.getConstant(0, DL, MVT::i32), Flags);
4789 }
4790 
4791 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4792                                              SelectionDAG &DAG) const {
4793   // Let legalize expand this if it isn't a legal type yet.
4794   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4795     return SDValue();
4796 
4797   SDValue LHS = Op.getOperand(0);
4798   SDValue RHS = Op.getOperand(1);
4799   SDLoc dl(Op);
4800 
4801   EVT VT = Op.getValueType();
4802   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4803   SDValue Value;
4804   SDValue Overflow;
4805   switch (Op.getOpcode()) {
4806   default:
4807     llvm_unreachable("Unknown overflow instruction!");
4808   case ISD::UADDO:
4809     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4810     // Convert the carry flag into a boolean value.
4811     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4812     break;
4813   case ISD::USUBO: {
4814     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4815     // Convert the carry flag into a boolean value.
4816     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4817     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4818     // value. So compute 1 - C.
4819     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4820                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4821     break;
4822   }
4823   }
4824 
4825   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4826 }
4827 
4828 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4829                                const ARMSubtarget *Subtarget) {
4830   EVT VT = Op.getValueType();
4831   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4832     return SDValue();
4833   if (!VT.isSimple())
4834     return SDValue();
4835 
4836   unsigned NewOpcode;
4837   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4838   switch (VT.getSimpleVT().SimpleTy) {
4839   default:
4840     return SDValue();
4841   case MVT::i8:
4842     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4843     break;
4844   case MVT::i16:
4845     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4846     break;
4847   }
4848 
4849   SDLoc dl(Op);
4850   SDValue Add =
4851       DAG.getNode(NewOpcode, dl, MVT::i32,
4852                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4853                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4854   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4855 }
4856 
4857 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4858   SDValue Cond = Op.getOperand(0);
4859   SDValue SelectTrue = Op.getOperand(1);
4860   SDValue SelectFalse = Op.getOperand(2);
4861   SDLoc dl(Op);
4862   unsigned Opc = Cond.getOpcode();
4863 
4864   if (Cond.getResNo() == 1 &&
4865       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4866        Opc == ISD::USUBO)) {
4867     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4868       return SDValue();
4869 
4870     SDValue Value, OverflowCmp;
4871     SDValue ARMcc;
4872     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4873     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4874     EVT VT = Op.getValueType();
4875 
4876     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4877                    OverflowCmp, DAG);
4878   }
4879 
4880   // Convert:
4881   //
4882   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4883   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4884   //
4885   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4886     const ConstantSDNode *CMOVTrue =
4887       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4888     const ConstantSDNode *CMOVFalse =
4889       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4890 
4891     if (CMOVTrue && CMOVFalse) {
4892       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4893       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4894 
4895       SDValue True;
4896       SDValue False;
4897       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4898         True = SelectTrue;
4899         False = SelectFalse;
4900       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4901         True = SelectFalse;
4902         False = SelectTrue;
4903       }
4904 
4905       if (True.getNode() && False.getNode()) {
4906         EVT VT = Op.getValueType();
4907         SDValue ARMcc = Cond.getOperand(2);
4908         SDValue CCR = Cond.getOperand(3);
4909         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4910         assert(True.getValueType() == VT);
4911         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4912       }
4913     }
4914   }
4915 
4916   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4917   // undefined bits before doing a full-word comparison with zero.
4918   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4919                      DAG.getConstant(1, dl, Cond.getValueType()));
4920 
4921   return DAG.getSelectCC(dl, Cond,
4922                          DAG.getConstant(0, dl, Cond.getValueType()),
4923                          SelectTrue, SelectFalse, ISD::SETNE);
4924 }
4925 
4926 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4927                                  bool &swpCmpOps, bool &swpVselOps) {
4928   // Start by selecting the GE condition code for opcodes that return true for
4929   // 'equality'
4930   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4931       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4932     CondCode = ARMCC::GE;
4933 
4934   // and GT for opcodes that return false for 'equality'.
4935   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4936            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4937     CondCode = ARMCC::GT;
4938 
4939   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4940   // to swap the compare operands.
4941   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4942       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4943     swpCmpOps = true;
4944 
4945   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4946   // If we have an unordered opcode, we need to swap the operands to the VSEL
4947   // instruction (effectively negating the condition).
4948   //
4949   // This also has the effect of swapping which one of 'less' or 'greater'
4950   // returns true, so we also swap the compare operands. It also switches
4951   // whether we return true for 'equality', so we compensate by picking the
4952   // opposite condition code to our original choice.
4953   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4954       CC == ISD::SETUGT) {
4955     swpCmpOps = !swpCmpOps;
4956     swpVselOps = !swpVselOps;
4957     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4958   }
4959 
4960   // 'ordered' is 'anything but unordered', so use the VS condition code and
4961   // swap the VSEL operands.
4962   if (CC == ISD::SETO) {
4963     CondCode = ARMCC::VS;
4964     swpVselOps = true;
4965   }
4966 
4967   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4968   // code and swap the VSEL operands. Also do this if we don't care about the
4969   // unordered case.
4970   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4971     CondCode = ARMCC::EQ;
4972     swpVselOps = true;
4973   }
4974 }
4975 
4976 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4977                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4978                                    SDValue Cmp, SelectionDAG &DAG) const {
4979   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4980     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4981                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4982     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4983                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4984 
4985     SDValue TrueLow = TrueVal.getValue(0);
4986     SDValue TrueHigh = TrueVal.getValue(1);
4987     SDValue FalseLow = FalseVal.getValue(0);
4988     SDValue FalseHigh = FalseVal.getValue(1);
4989 
4990     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4991                               ARMcc, CCR, Cmp);
4992     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4993                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4994 
4995     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4996   } else {
4997     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4998                        Cmp);
4999   }
5000 }
5001 
5002 static bool isGTorGE(ISD::CondCode CC) {
5003   return CC == ISD::SETGT || CC == ISD::SETGE;
5004 }
5005 
5006 static bool isLTorLE(ISD::CondCode CC) {
5007   return CC == ISD::SETLT || CC == ISD::SETLE;
5008 }
5009 
5010 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5011 // All of these conditions (and their <= and >= counterparts) will do:
5012 //          x < k ? k : x
5013 //          x > k ? x : k
5014 //          k < x ? x : k
5015 //          k > x ? k : x
5016 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5017                             const SDValue TrueVal, const SDValue FalseVal,
5018                             const ISD::CondCode CC, const SDValue K) {
5019   return (isGTorGE(CC) &&
5020           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5021          (isLTorLE(CC) &&
5022           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5023 }
5024 
5025 // Check if two chained conditionals could be converted into SSAT or USAT.
5026 //
5027 // SSAT can replace a set of two conditional selectors that bound a number to an
5028 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5029 //
5030 //     x < -k ? -k : (x > k ? k : x)
5031 //     x < -k ? -k : (x < k ? x : k)
5032 //     x > -k ? (x > k ? k : x) : -k
5033 //     x < k ? (x < -k ? -k : x) : k
5034 //     etc.
5035 //
5036 // LLVM canonicalizes these to either a min(max()) or a max(min())
5037 // pattern. This function tries to match one of these and will return true
5038 // if successful.
5039 //
5040 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
5041 // a power of 2.
5042 //
5043 // It returns true if the conversion can be done, false otherwise.
5044 // Additionally, the variable is returned in parameter V, the constant in K and
5045 // usat is set to true if the conditional represents an unsigned saturation
5046 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
5047                                     uint64_t &K, bool &Usat) {
5048   SDValue V1 = Op.getOperand(0);
5049   SDValue K1 = Op.getOperand(1);
5050   SDValue TrueVal1 = Op.getOperand(2);
5051   SDValue FalseVal1 = Op.getOperand(3);
5052   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5053 
5054   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5055   if (Op2.getOpcode() != ISD::SELECT_CC)
5056     return false;
5057 
5058   SDValue V2 = Op2.getOperand(0);
5059   SDValue K2 = Op2.getOperand(1);
5060   SDValue TrueVal2 = Op2.getOperand(2);
5061   SDValue FalseVal2 = Op2.getOperand(3);
5062   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5063 
5064   SDValue V1Tmp = V1;
5065   SDValue V2Tmp = V2;
5066 
5067   if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5068       V2.getOpcode() == ISD::SIGN_EXTEND_INREG) {
5069     V1Tmp = V1.getOperand(0);
5070     V2Tmp = V2.getOperand(0);
5071   }
5072 
5073   // Check that the registers and the constants match a max(min()) or min(max())
5074   // pattern
5075   if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 &&
5076       K2 == FalseVal2 &&
5077       ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) {
5078 
5079     // Check that the constant in the lower-bound check is
5080     // the opposite of the constant in the upper-bound check
5081     // in 1's complement.
5082     if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5083       return false;
5084 
5085     int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5086     int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5087     int64_t PosVal = std::max(Val1, Val2);
5088     int64_t NegVal = std::min(Val1, Val2);
5089 
5090     if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5091         !isPowerOf2_64(PosVal + 1))
5092       return false;
5093 
5094     // Handle the difference between USAT (unsigned) and SSAT (signed)
5095     // saturation
5096     if (Val1 == ~Val2)
5097       Usat = false;
5098     else if (NegVal == 0)
5099       Usat = true;
5100     else
5101       return false;
5102 
5103     V = V2Tmp;
5104     // At this point, PosVal is guaranteed to be positive
5105     K = (uint64_t) PosVal;
5106 
5107     return true;
5108   }
5109   return false;
5110 }
5111 
5112 // Check if a condition of the type x < k ? k : x can be converted into a
5113 // bit operation instead of conditional moves.
5114 // Currently this is allowed given:
5115 // - The conditions and values match up
5116 // - k is 0 or -1 (all ones)
5117 // This function will not check the last condition, thats up to the caller
5118 // It returns true if the transformation can be made, and in such case
5119 // returns x in V, and k in SatK.
5120 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5121                                          SDValue &SatK)
5122 {
5123   SDValue LHS = Op.getOperand(0);
5124   SDValue RHS = Op.getOperand(1);
5125   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5126   SDValue TrueVal = Op.getOperand(2);
5127   SDValue FalseVal = Op.getOperand(3);
5128 
5129   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5130                                                ? &RHS
5131                                                : nullptr;
5132 
5133   // No constant operation in comparison, early out
5134   if (!K)
5135     return false;
5136 
5137   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5138   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5139   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5140 
5141   // If the constant on left and right side, or variable on left and right,
5142   // does not match, early out
5143   if (*K != KTmp || V != VTmp)
5144     return false;
5145 
5146   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5147     SatK = *K;
5148     return true;
5149   }
5150 
5151   return false;
5152 }
5153 
5154 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5155   if (VT == MVT::f32)
5156     return !Subtarget->hasVFP2Base();
5157   if (VT == MVT::f64)
5158     return !Subtarget->hasFP64();
5159   if (VT == MVT::f16)
5160     return !Subtarget->hasFullFP16();
5161   return false;
5162 }
5163 
5164 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5165   EVT VT = Op.getValueType();
5166   SDLoc dl(Op);
5167 
5168   // Try to convert two saturating conditional selects into a single SSAT
5169   SDValue SatValue;
5170   uint64_t SatConstant;
5171   bool SatUSat;
5172   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
5173       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
5174     if (SatUSat)
5175       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
5176                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5177     else
5178       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
5179                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5180   }
5181 
5182   // Try to convert expressions of the form x < k ? k : x (and similar forms)
5183   // into more efficient bit operations, which is possible when k is 0 or -1
5184   // On ARM and Thumb-2 which have flexible operand 2 this will result in
5185   // single instructions. On Thumb the shift and the bit operation will be two
5186   // instructions.
5187   // Only allow this transformation on full-width (32-bit) operations
5188   SDValue LowerSatConstant;
5189   if (VT == MVT::i32 &&
5190       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5191     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5192                                  DAG.getConstant(31, dl, VT));
5193     if (isNullConstant(LowerSatConstant)) {
5194       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5195                                       DAG.getAllOnesConstant(dl, VT));
5196       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5197     } else if (isAllOnesConstant(LowerSatConstant))
5198       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5199   }
5200 
5201   SDValue LHS = Op.getOperand(0);
5202   SDValue RHS = Op.getOperand(1);
5203   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5204   SDValue TrueVal = Op.getOperand(2);
5205   SDValue FalseVal = Op.getOperand(3);
5206   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5207   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5208 
5209   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5210       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5211     unsigned TVal = CTVal->getZExtValue();
5212     unsigned FVal = CFVal->getZExtValue();
5213     unsigned Opcode = 0;
5214 
5215     if (TVal == ~FVal) {
5216       Opcode = ARMISD::CSINV;
5217     } else if (TVal == ~FVal + 1) {
5218       Opcode = ARMISD::CSNEG;
5219     } else if (TVal + 1 == FVal) {
5220       Opcode = ARMISD::CSINC;
5221     } else if (TVal == FVal + 1) {
5222       Opcode = ARMISD::CSINC;
5223       std::swap(TrueVal, FalseVal);
5224       std::swap(TVal, FVal);
5225       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5226     }
5227 
5228     if (Opcode) {
5229       // If one of the constants is cheaper than another, materialise the
5230       // cheaper one and let the csel generate the other.
5231       if (Opcode != ARMISD::CSINC &&
5232           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5233         std::swap(TrueVal, FalseVal);
5234         std::swap(TVal, FVal);
5235         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5236       }
5237 
5238       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5239       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5240       // -(-a) == a, but (a+1)+1 != a).
5241       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5242         std::swap(TrueVal, FalseVal);
5243         std::swap(TVal, FVal);
5244         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5245       }
5246       if (TVal == 0)
5247         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5248 
5249       // Drops F's value because we can get it by inverting/negating TVal.
5250       FalseVal = TrueVal;
5251 
5252       SDValue ARMcc;
5253       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5254       EVT VT = TrueVal.getValueType();
5255       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5256     }
5257   }
5258 
5259   if (isUnsupportedFloatingType(LHS.getValueType())) {
5260     DAG.getTargetLoweringInfo().softenSetCCOperands(
5261         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5262 
5263     // If softenSetCCOperands only returned one value, we should compare it to
5264     // zero.
5265     if (!RHS.getNode()) {
5266       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5267       CC = ISD::SETNE;
5268     }
5269   }
5270 
5271   if (LHS.getValueType() == MVT::i32) {
5272     // Try to generate VSEL on ARMv8.
5273     // The VSEL instruction can't use all the usual ARM condition
5274     // codes: it only has two bits to select the condition code, so it's
5275     // constrained to use only GE, GT, VS and EQ.
5276     //
5277     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5278     // swap the operands of the previous compare instruction (effectively
5279     // inverting the compare condition, swapping 'less' and 'greater') and
5280     // sometimes need to swap the operands to the VSEL (which inverts the
5281     // condition in the sense of firing whenever the previous condition didn't)
5282     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5283                                         TrueVal.getValueType() == MVT::f32 ||
5284                                         TrueVal.getValueType() == MVT::f64)) {
5285       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5286       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5287           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5288         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5289         std::swap(TrueVal, FalseVal);
5290       }
5291     }
5292 
5293     SDValue ARMcc;
5294     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5295     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5296     // Choose GE over PL, which vsel does now support
5297     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5298       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5299     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5300   }
5301 
5302   ARMCC::CondCodes CondCode, CondCode2;
5303   FPCCToARMCC(CC, CondCode, CondCode2);
5304 
5305   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5306   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5307   // must use VSEL (limited condition codes), due to not having conditional f16
5308   // moves.
5309   if (Subtarget->hasFPARMv8Base() &&
5310       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5311       (TrueVal.getValueType() == MVT::f16 ||
5312        TrueVal.getValueType() == MVT::f32 ||
5313        TrueVal.getValueType() == MVT::f64)) {
5314     bool swpCmpOps = false;
5315     bool swpVselOps = false;
5316     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5317 
5318     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5319         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5320       if (swpCmpOps)
5321         std::swap(LHS, RHS);
5322       if (swpVselOps)
5323         std::swap(TrueVal, FalseVal);
5324     }
5325   }
5326 
5327   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5328   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5329   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5330   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5331   if (CondCode2 != ARMCC::AL) {
5332     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5333     // FIXME: Needs another CMP because flag can have but one use.
5334     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5335     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5336   }
5337   return Result;
5338 }
5339 
5340 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5341 /// to morph to an integer compare sequence.
5342 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5343                            const ARMSubtarget *Subtarget) {
5344   SDNode *N = Op.getNode();
5345   if (!N->hasOneUse())
5346     // Otherwise it requires moving the value from fp to integer registers.
5347     return false;
5348   if (!N->getNumValues())
5349     return false;
5350   EVT VT = Op.getValueType();
5351   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5352     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5353     // vmrs are very slow, e.g. cortex-a8.
5354     return false;
5355 
5356   if (isFloatingPointZero(Op)) {
5357     SeenZero = true;
5358     return true;
5359   }
5360   return ISD::isNormalLoad(N);
5361 }
5362 
5363 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5364   if (isFloatingPointZero(Op))
5365     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5366 
5367   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5368     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5369                        Ld->getPointerInfo(), Ld->getAlignment(),
5370                        Ld->getMemOperand()->getFlags());
5371 
5372   llvm_unreachable("Unknown VFP cmp argument!");
5373 }
5374 
5375 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5376                            SDValue &RetVal1, SDValue &RetVal2) {
5377   SDLoc dl(Op);
5378 
5379   if (isFloatingPointZero(Op)) {
5380     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5381     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5382     return;
5383   }
5384 
5385   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5386     SDValue Ptr = Ld->getBasePtr();
5387     RetVal1 =
5388         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5389                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5390 
5391     EVT PtrType = Ptr.getValueType();
5392     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5393     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5394                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5395     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5396                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5397                           Ld->getMemOperand()->getFlags());
5398     return;
5399   }
5400 
5401   llvm_unreachable("Unknown VFP cmp argument!");
5402 }
5403 
5404 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5405 /// f32 and even f64 comparisons to integer ones.
5406 SDValue
5407 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5408   SDValue Chain = Op.getOperand(0);
5409   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5410   SDValue LHS = Op.getOperand(2);
5411   SDValue RHS = Op.getOperand(3);
5412   SDValue Dest = Op.getOperand(4);
5413   SDLoc dl(Op);
5414 
5415   bool LHSSeenZero = false;
5416   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5417   bool RHSSeenZero = false;
5418   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5419   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5420     // If unsafe fp math optimization is enabled and there are no other uses of
5421     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5422     // to an integer comparison.
5423     if (CC == ISD::SETOEQ)
5424       CC = ISD::SETEQ;
5425     else if (CC == ISD::SETUNE)
5426       CC = ISD::SETNE;
5427 
5428     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5429     SDValue ARMcc;
5430     if (LHS.getValueType() == MVT::f32) {
5431       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5432                         bitcastf32Toi32(LHS, DAG), Mask);
5433       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5434                         bitcastf32Toi32(RHS, DAG), Mask);
5435       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5436       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5437       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5438                          Chain, Dest, ARMcc, CCR, Cmp);
5439     }
5440 
5441     SDValue LHS1, LHS2;
5442     SDValue RHS1, RHS2;
5443     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5444     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5445     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5446     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5447     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5448     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5449     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5450     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5451     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5452   }
5453 
5454   return SDValue();
5455 }
5456 
5457 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5458   SDValue Chain = Op.getOperand(0);
5459   SDValue Cond = Op.getOperand(1);
5460   SDValue Dest = Op.getOperand(2);
5461   SDLoc dl(Op);
5462 
5463   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5464   // instruction.
5465   unsigned Opc = Cond.getOpcode();
5466   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5467                       !Subtarget->isThumb1Only();
5468   if (Cond.getResNo() == 1 &&
5469       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5470        Opc == ISD::USUBO || OptimizeMul)) {
5471     // Only lower legal XALUO ops.
5472     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5473       return SDValue();
5474 
5475     // The actual operation with overflow check.
5476     SDValue Value, OverflowCmp;
5477     SDValue ARMcc;
5478     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5479 
5480     // Reverse the condition code.
5481     ARMCC::CondCodes CondCode =
5482         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5483     CondCode = ARMCC::getOppositeCondition(CondCode);
5484     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5485     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5486 
5487     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5488                        OverflowCmp);
5489   }
5490 
5491   return SDValue();
5492 }
5493 
5494 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5495   SDValue Chain = Op.getOperand(0);
5496   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5497   SDValue LHS = Op.getOperand(2);
5498   SDValue RHS = Op.getOperand(3);
5499   SDValue Dest = Op.getOperand(4);
5500   SDLoc dl(Op);
5501 
5502   if (isUnsupportedFloatingType(LHS.getValueType())) {
5503     DAG.getTargetLoweringInfo().softenSetCCOperands(
5504         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5505 
5506     // If softenSetCCOperands only returned one value, we should compare it to
5507     // zero.
5508     if (!RHS.getNode()) {
5509       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5510       CC = ISD::SETNE;
5511     }
5512   }
5513 
5514   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5515   // instruction.
5516   unsigned Opc = LHS.getOpcode();
5517   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5518                       !Subtarget->isThumb1Only();
5519   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5520       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5521        Opc == ISD::USUBO || OptimizeMul) &&
5522       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5523     // Only lower legal XALUO ops.
5524     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5525       return SDValue();
5526 
5527     // The actual operation with overflow check.
5528     SDValue Value, OverflowCmp;
5529     SDValue ARMcc;
5530     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5531 
5532     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5533       // Reverse the condition code.
5534       ARMCC::CondCodes CondCode =
5535           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5536       CondCode = ARMCC::getOppositeCondition(CondCode);
5537       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5538     }
5539     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5540 
5541     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5542                        OverflowCmp);
5543   }
5544 
5545   if (LHS.getValueType() == MVT::i32) {
5546     SDValue ARMcc;
5547     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5548     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5549     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5550                        Chain, Dest, ARMcc, CCR, Cmp);
5551   }
5552 
5553   if (getTargetMachine().Options.UnsafeFPMath &&
5554       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5555        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5556     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5557       return Result;
5558   }
5559 
5560   ARMCC::CondCodes CondCode, CondCode2;
5561   FPCCToARMCC(CC, CondCode, CondCode2);
5562 
5563   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5564   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5565   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5566   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5567   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5568   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5569   if (CondCode2 != ARMCC::AL) {
5570     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5571     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5572     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5573   }
5574   return Res;
5575 }
5576 
5577 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5578   SDValue Chain = Op.getOperand(0);
5579   SDValue Table = Op.getOperand(1);
5580   SDValue Index = Op.getOperand(2);
5581   SDLoc dl(Op);
5582 
5583   EVT PTy = getPointerTy(DAG.getDataLayout());
5584   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5585   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5586   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5587   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5588   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5589   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5590     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5591     // which does another jump to the destination. This also makes it easier
5592     // to translate it to TBB / TBH later (Thumb2 only).
5593     // FIXME: This might not work if the function is extremely large.
5594     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5595                        Addr, Op.getOperand(2), JTI);
5596   }
5597   if (isPositionIndependent() || Subtarget->isROPI()) {
5598     Addr =
5599         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5600                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5601     Chain = Addr.getValue(1);
5602     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5603     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5604   } else {
5605     Addr =
5606         DAG.getLoad(PTy, dl, Chain, Addr,
5607                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5608     Chain = Addr.getValue(1);
5609     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5610   }
5611 }
5612 
5613 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5614   EVT VT = Op.getValueType();
5615   SDLoc dl(Op);
5616 
5617   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5618     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5619       return Op;
5620     return DAG.UnrollVectorOp(Op.getNode());
5621   }
5622 
5623   const bool HasFullFP16 =
5624     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5625 
5626   EVT NewTy;
5627   const EVT OpTy = Op.getOperand(0).getValueType();
5628   if (OpTy == MVT::v4f32)
5629     NewTy = MVT::v4i32;
5630   else if (OpTy == MVT::v4f16 && HasFullFP16)
5631     NewTy = MVT::v4i16;
5632   else if (OpTy == MVT::v8f16 && HasFullFP16)
5633     NewTy = MVT::v8i16;
5634   else
5635     llvm_unreachable("Invalid type for custom lowering!");
5636 
5637   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5638     return DAG.UnrollVectorOp(Op.getNode());
5639 
5640   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5641   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5642 }
5643 
5644 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5645   EVT VT = Op.getValueType();
5646   if (VT.isVector())
5647     return LowerVectorFP_TO_INT(Op, DAG);
5648 
5649   bool IsStrict = Op->isStrictFPOpcode();
5650   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5651 
5652   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5653     RTLIB::Libcall LC;
5654     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5655         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5656       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5657                               Op.getValueType());
5658     else
5659       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5660                               Op.getValueType());
5661     SDLoc Loc(Op);
5662     MakeLibCallOptions CallOptions;
5663     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5664     SDValue Result;
5665     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5666                                           CallOptions, Loc, Chain);
5667     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5668   }
5669 
5670   // FIXME: Remove this when we have strict fp instruction selection patterns
5671   if (IsStrict) {
5672     SDLoc Loc(Op);
5673     SDValue Result =
5674         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5675                                                              : ISD::FP_TO_UINT,
5676                     Loc, Op.getValueType(), SrcVal);
5677     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5678   }
5679 
5680   return Op;
5681 }
5682 
5683 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5684   EVT VT = Op.getValueType();
5685   SDLoc dl(Op);
5686 
5687   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5688     if (VT.getVectorElementType() == MVT::f32)
5689       return Op;
5690     return DAG.UnrollVectorOp(Op.getNode());
5691   }
5692 
5693   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5694           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5695          "Invalid type for custom lowering!");
5696 
5697   const bool HasFullFP16 =
5698     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5699 
5700   EVT DestVecType;
5701   if (VT == MVT::v4f32)
5702     DestVecType = MVT::v4i32;
5703   else if (VT == MVT::v4f16 && HasFullFP16)
5704     DestVecType = MVT::v4i16;
5705   else if (VT == MVT::v8f16 && HasFullFP16)
5706     DestVecType = MVT::v8i16;
5707   else
5708     return DAG.UnrollVectorOp(Op.getNode());
5709 
5710   unsigned CastOpc;
5711   unsigned Opc;
5712   switch (Op.getOpcode()) {
5713   default: llvm_unreachable("Invalid opcode!");
5714   case ISD::SINT_TO_FP:
5715     CastOpc = ISD::SIGN_EXTEND;
5716     Opc = ISD::SINT_TO_FP;
5717     break;
5718   case ISD::UINT_TO_FP:
5719     CastOpc = ISD::ZERO_EXTEND;
5720     Opc = ISD::UINT_TO_FP;
5721     break;
5722   }
5723 
5724   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5725   return DAG.getNode(Opc, dl, VT, Op);
5726 }
5727 
5728 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5729   EVT VT = Op.getValueType();
5730   if (VT.isVector())
5731     return LowerVectorINT_TO_FP(Op, DAG);
5732   if (isUnsupportedFloatingType(VT)) {
5733     RTLIB::Libcall LC;
5734     if (Op.getOpcode() == ISD::SINT_TO_FP)
5735       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5736                               Op.getValueType());
5737     else
5738       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5739                               Op.getValueType());
5740     MakeLibCallOptions CallOptions;
5741     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5742                        CallOptions, SDLoc(Op)).first;
5743   }
5744 
5745   return Op;
5746 }
5747 
5748 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5749   // Implement fcopysign with a fabs and a conditional fneg.
5750   SDValue Tmp0 = Op.getOperand(0);
5751   SDValue Tmp1 = Op.getOperand(1);
5752   SDLoc dl(Op);
5753   EVT VT = Op.getValueType();
5754   EVT SrcVT = Tmp1.getValueType();
5755   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5756     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5757   bool UseNEON = !InGPR && Subtarget->hasNEON();
5758 
5759   if (UseNEON) {
5760     // Use VBSL to copy the sign bit.
5761     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5762     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5763                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5764     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5765     if (VT == MVT::f64)
5766       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5767                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5768                          DAG.getConstant(32, dl, MVT::i32));
5769     else /*if (VT == MVT::f32)*/
5770       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5771     if (SrcVT == MVT::f32) {
5772       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5773       if (VT == MVT::f64)
5774         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5775                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5776                            DAG.getConstant(32, dl, MVT::i32));
5777     } else if (VT == MVT::f32)
5778       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5779                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5780                          DAG.getConstant(32, dl, MVT::i32));
5781     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5782     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5783 
5784     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5785                                             dl, MVT::i32);
5786     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5787     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5788                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5789 
5790     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5791                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5792                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5793     if (VT == MVT::f32) {
5794       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5795       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5796                         DAG.getConstant(0, dl, MVT::i32));
5797     } else {
5798       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5799     }
5800 
5801     return Res;
5802   }
5803 
5804   // Bitcast operand 1 to i32.
5805   if (SrcVT == MVT::f64)
5806     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5807                        Tmp1).getValue(1);
5808   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5809 
5810   // Or in the signbit with integer operations.
5811   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5812   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5813   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5814   if (VT == MVT::f32) {
5815     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5816                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5817     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5818                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5819   }
5820 
5821   // f64: Or the high part with signbit and then combine two parts.
5822   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5823                      Tmp0);
5824   SDValue Lo = Tmp0.getValue(0);
5825   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5826   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5827   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5828 }
5829 
5830 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5831   MachineFunction &MF = DAG.getMachineFunction();
5832   MachineFrameInfo &MFI = MF.getFrameInfo();
5833   MFI.setReturnAddressIsTaken(true);
5834 
5835   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5836     return SDValue();
5837 
5838   EVT VT = Op.getValueType();
5839   SDLoc dl(Op);
5840   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5841   if (Depth) {
5842     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5843     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5844     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5845                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5846                        MachinePointerInfo());
5847   }
5848 
5849   // Return LR, which contains the return address. Mark it an implicit live-in.
5850   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5851   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5852 }
5853 
5854 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5855   const ARMBaseRegisterInfo &ARI =
5856     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5857   MachineFunction &MF = DAG.getMachineFunction();
5858   MachineFrameInfo &MFI = MF.getFrameInfo();
5859   MFI.setFrameAddressIsTaken(true);
5860 
5861   EVT VT = Op.getValueType();
5862   SDLoc dl(Op);  // FIXME probably not meaningful
5863   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5864   Register FrameReg = ARI.getFrameRegister(MF);
5865   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5866   while (Depth--)
5867     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5868                             MachinePointerInfo());
5869   return FrameAddr;
5870 }
5871 
5872 // FIXME? Maybe this could be a TableGen attribute on some registers and
5873 // this table could be generated automatically from RegInfo.
5874 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5875                                               const MachineFunction &MF) const {
5876   Register Reg = StringSwitch<unsigned>(RegName)
5877                        .Case("sp", ARM::SP)
5878                        .Default(0);
5879   if (Reg)
5880     return Reg;
5881   report_fatal_error(Twine("Invalid register name \""
5882                               + StringRef(RegName)  + "\"."));
5883 }
5884 
5885 // Result is 64 bit value so split into two 32 bit values and return as a
5886 // pair of values.
5887 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5888                                 SelectionDAG &DAG) {
5889   SDLoc DL(N);
5890 
5891   // This function is only supposed to be called for i64 type destination.
5892   assert(N->getValueType(0) == MVT::i64
5893           && "ExpandREAD_REGISTER called for non-i64 type result.");
5894 
5895   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5896                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5897                              N->getOperand(0),
5898                              N->getOperand(1));
5899 
5900   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5901                     Read.getValue(1)));
5902   Results.push_back(Read.getOperand(0));
5903 }
5904 
5905 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5906 /// When \p DstVT, the destination type of \p BC, is on the vector
5907 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5908 /// it might be possible to combine them, such that everything stays on the
5909 /// vector register bank.
5910 /// \p return The node that would replace \p BT, if the combine
5911 /// is possible.
5912 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5913                                                 SelectionDAG &DAG) {
5914   SDValue Op = BC->getOperand(0);
5915   EVT DstVT = BC->getValueType(0);
5916 
5917   // The only vector instruction that can produce a scalar (remember,
5918   // since the bitcast was about to be turned into VMOVDRR, the source
5919   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5920   // Moreover, we can do this combine only if there is one use.
5921   // Finally, if the destination type is not a vector, there is not
5922   // much point on forcing everything on the vector bank.
5923   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5924       !Op.hasOneUse())
5925     return SDValue();
5926 
5927   // If the index is not constant, we will introduce an additional
5928   // multiply that will stick.
5929   // Give up in that case.
5930   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5931   if (!Index)
5932     return SDValue();
5933   unsigned DstNumElt = DstVT.getVectorNumElements();
5934 
5935   // Compute the new index.
5936   const APInt &APIntIndex = Index->getAPIntValue();
5937   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5938   NewIndex *= APIntIndex;
5939   // Check if the new constant index fits into i32.
5940   if (NewIndex.getBitWidth() > 32)
5941     return SDValue();
5942 
5943   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5944   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5945   SDLoc dl(Op);
5946   SDValue ExtractSrc = Op.getOperand(0);
5947   EVT VecVT = EVT::getVectorVT(
5948       *DAG.getContext(), DstVT.getScalarType(),
5949       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5950   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5951   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5952                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5953 }
5954 
5955 /// ExpandBITCAST - If the target supports VFP, this function is called to
5956 /// expand a bit convert where either the source or destination type is i64 to
5957 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5958 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5959 /// vectors), since the legalizer won't know what to do with that.
5960 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5961                                          const ARMSubtarget *Subtarget) const {
5962   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5963   SDLoc dl(N);
5964   SDValue Op = N->getOperand(0);
5965 
5966   // This function is only supposed to be called for i16 and i64 types, either
5967   // as the source or destination of the bit convert.
5968   EVT SrcVT = Op.getValueType();
5969   EVT DstVT = N->getValueType(0);
5970 
5971   if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
5972       (DstVT == MVT::f16 || DstVT == MVT::bf16))
5973     return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
5974                      DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5975 
5976   if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
5977       (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
5978     return DAG.getNode(
5979         ISD::TRUNCATE, SDLoc(N), DstVT,
5980         MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
5981 
5982   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5983     return SDValue();
5984 
5985   // Turn i64->f64 into VMOVDRR.
5986   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5987     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5988     // if we can combine the bitcast with its source.
5989     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5990       return Val;
5991 
5992     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5993                              DAG.getConstant(0, dl, MVT::i32));
5994     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5995                              DAG.getConstant(1, dl, MVT::i32));
5996     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5997                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5998   }
5999 
6000   // Turn f64->i64 into VMOVRRD.
6001   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
6002     SDValue Cvt;
6003     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6004         SrcVT.getVectorNumElements() > 1)
6005       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6006                         DAG.getVTList(MVT::i32, MVT::i32),
6007                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6008     else
6009       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6010                         DAG.getVTList(MVT::i32, MVT::i32), Op);
6011     // Merge the pieces into a single i64 value.
6012     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6013   }
6014 
6015   return SDValue();
6016 }
6017 
6018 /// getZeroVector - Returns a vector of specified type with all zero elements.
6019 /// Zero vectors are used to represent vector negation and in those cases
6020 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
6021 /// not support i64 elements, so sometimes the zero vectors will need to be
6022 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
6023 /// zero vector.
6024 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6025   assert(VT.isVector() && "Expected a vector type");
6026   // The canonical modified immediate encoding of a zero vector is....0!
6027   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6028   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6029   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6030   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6031 }
6032 
6033 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6034 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
6035 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6036                                                 SelectionDAG &DAG) const {
6037   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6038   EVT VT = Op.getValueType();
6039   unsigned VTBits = VT.getSizeInBits();
6040   SDLoc dl(Op);
6041   SDValue ShOpLo = Op.getOperand(0);
6042   SDValue ShOpHi = Op.getOperand(1);
6043   SDValue ShAmt  = Op.getOperand(2);
6044   SDValue ARMcc;
6045   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6046   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6047 
6048   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6049 
6050   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6051                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6052   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6053   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6054                                    DAG.getConstant(VTBits, dl, MVT::i32));
6055   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6056   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6057   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6058   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6059                             ISD::SETGE, ARMcc, DAG, dl);
6060   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6061                            ARMcc, CCR, CmpLo);
6062 
6063   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6064   SDValue HiBigShift = Opc == ISD::SRA
6065                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
6066                                          DAG.getConstant(VTBits - 1, dl, VT))
6067                            : DAG.getConstant(0, dl, VT);
6068   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6069                             ISD::SETGE, ARMcc, DAG, dl);
6070   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6071                            ARMcc, CCR, CmpHi);
6072 
6073   SDValue Ops[2] = { Lo, Hi };
6074   return DAG.getMergeValues(Ops, dl);
6075 }
6076 
6077 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6078 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
6079 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6080                                                SelectionDAG &DAG) const {
6081   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6082   EVT VT = Op.getValueType();
6083   unsigned VTBits = VT.getSizeInBits();
6084   SDLoc dl(Op);
6085   SDValue ShOpLo = Op.getOperand(0);
6086   SDValue ShOpHi = Op.getOperand(1);
6087   SDValue ShAmt  = Op.getOperand(2);
6088   SDValue ARMcc;
6089   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6090 
6091   assert(Op.getOpcode() == ISD::SHL_PARTS);
6092   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6093                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6094   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6095   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6096   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6097 
6098   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6099                                    DAG.getConstant(VTBits, dl, MVT::i32));
6100   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6101   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6102                             ISD::SETGE, ARMcc, DAG, dl);
6103   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6104                            ARMcc, CCR, CmpHi);
6105 
6106   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6107                           ISD::SETGE, ARMcc, DAG, dl);
6108   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6109   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6110                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6111 
6112   SDValue Ops[2] = { Lo, Hi };
6113   return DAG.getMergeValues(Ops, dl);
6114 }
6115 
6116 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6117                                             SelectionDAG &DAG) const {
6118   // The rounding mode is in bits 23:22 of the FPSCR.
6119   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6120   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6121   // so that the shift + and get folded into a bitfield extract.
6122   SDLoc dl(Op);
6123   SDValue Chain = Op.getOperand(0);
6124   SDValue Ops[] = {Chain,
6125                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6126 
6127   SDValue FPSCR =
6128       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6129   Chain = FPSCR.getValue(1);
6130   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6131                                   DAG.getConstant(1U << 22, dl, MVT::i32));
6132   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6133                               DAG.getConstant(22, dl, MVT::i32));
6134   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6135                             DAG.getConstant(3, dl, MVT::i32));
6136   return DAG.getMergeValues({And, Chain}, dl);
6137 }
6138 
6139 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6140                          const ARMSubtarget *ST) {
6141   SDLoc dl(N);
6142   EVT VT = N->getValueType(0);
6143   if (VT.isVector() && ST->hasNEON()) {
6144 
6145     // Compute the least significant set bit: LSB = X & -X
6146     SDValue X = N->getOperand(0);
6147     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6148     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6149 
6150     EVT ElemTy = VT.getVectorElementType();
6151 
6152     if (ElemTy == MVT::i8) {
6153       // Compute with: cttz(x) = ctpop(lsb - 1)
6154       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6155                                 DAG.getTargetConstant(1, dl, ElemTy));
6156       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6157       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6158     }
6159 
6160     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6161         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6162       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6163       unsigned NumBits = ElemTy.getSizeInBits();
6164       SDValue WidthMinus1 =
6165           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6166                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6167       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6168       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6169     }
6170 
6171     // Compute with: cttz(x) = ctpop(lsb - 1)
6172 
6173     // Compute LSB - 1.
6174     SDValue Bits;
6175     if (ElemTy == MVT::i64) {
6176       // Load constant 0xffff'ffff'ffff'ffff to register.
6177       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6178                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6179       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6180     } else {
6181       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6182                                 DAG.getTargetConstant(1, dl, ElemTy));
6183       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6184     }
6185     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6186   }
6187 
6188   if (!ST->hasV6T2Ops())
6189     return SDValue();
6190 
6191   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6192   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6193 }
6194 
6195 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6196                           const ARMSubtarget *ST) {
6197   EVT VT = N->getValueType(0);
6198   SDLoc DL(N);
6199 
6200   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6201   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6202           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6203          "Unexpected type for custom ctpop lowering");
6204 
6205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6206   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6207   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6208   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6209 
6210   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6211   unsigned EltSize = 8;
6212   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6213   while (EltSize != VT.getScalarSizeInBits()) {
6214     SmallVector<SDValue, 8> Ops;
6215     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6216                                   TLI.getPointerTy(DAG.getDataLayout())));
6217     Ops.push_back(Res);
6218 
6219     EltSize *= 2;
6220     NumElts /= 2;
6221     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6222     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6223   }
6224 
6225   return Res;
6226 }
6227 
6228 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6229 /// operand of a vector shift operation, where all the elements of the
6230 /// build_vector must have the same constant integer value.
6231 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6232   // Ignore bit_converts.
6233   while (Op.getOpcode() == ISD::BITCAST)
6234     Op = Op.getOperand(0);
6235   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6236   APInt SplatBits, SplatUndef;
6237   unsigned SplatBitSize;
6238   bool HasAnyUndefs;
6239   if (!BVN ||
6240       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6241                             ElementBits) ||
6242       SplatBitSize > ElementBits)
6243     return false;
6244   Cnt = SplatBits.getSExtValue();
6245   return true;
6246 }
6247 
6248 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6249 /// operand of a vector shift left operation.  That value must be in the range:
6250 ///   0 <= Value < ElementBits for a left shift; or
6251 ///   0 <= Value <= ElementBits for a long left shift.
6252 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6253   assert(VT.isVector() && "vector shift count is not a vector type");
6254   int64_t ElementBits = VT.getScalarSizeInBits();
6255   if (!getVShiftImm(Op, ElementBits, Cnt))
6256     return false;
6257   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6258 }
6259 
6260 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6261 /// operand of a vector shift right operation.  For a shift opcode, the value
6262 /// is positive, but for an intrinsic the value count must be negative. The
6263 /// absolute value must be in the range:
6264 ///   1 <= |Value| <= ElementBits for a right shift; or
6265 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6266 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6267                          int64_t &Cnt) {
6268   assert(VT.isVector() && "vector shift count is not a vector type");
6269   int64_t ElementBits = VT.getScalarSizeInBits();
6270   if (!getVShiftImm(Op, ElementBits, Cnt))
6271     return false;
6272   if (!isIntrinsic)
6273     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6274   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6275     Cnt = -Cnt;
6276     return true;
6277   }
6278   return false;
6279 }
6280 
6281 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6282                           const ARMSubtarget *ST) {
6283   EVT VT = N->getValueType(0);
6284   SDLoc dl(N);
6285   int64_t Cnt;
6286 
6287   if (!VT.isVector())
6288     return SDValue();
6289 
6290   // We essentially have two forms here. Shift by an immediate and shift by a
6291   // vector register (there are also shift by a gpr, but that is just handled
6292   // with a tablegen pattern). We cannot easily match shift by an immediate in
6293   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6294   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6295   // signed or unsigned, and a negative shift indicates a shift right).
6296   if (N->getOpcode() == ISD::SHL) {
6297     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6298       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6299                          DAG.getConstant(Cnt, dl, MVT::i32));
6300     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6301                        N->getOperand(1));
6302   }
6303 
6304   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6305          "unexpected vector shift opcode");
6306 
6307   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6308     unsigned VShiftOpc =
6309         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6310     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6311                        DAG.getConstant(Cnt, dl, MVT::i32));
6312   }
6313 
6314   // Other right shifts we don't have operations for (we use a shift left by a
6315   // negative number).
6316   EVT ShiftVT = N->getOperand(1).getValueType();
6317   SDValue NegatedCount = DAG.getNode(
6318       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6319   unsigned VShiftOpc =
6320       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6321   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6322 }
6323 
6324 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6325                                 const ARMSubtarget *ST) {
6326   EVT VT = N->getValueType(0);
6327   SDLoc dl(N);
6328 
6329   // We can get here for a node like i32 = ISD::SHL i32, i64
6330   if (VT != MVT::i64)
6331     return SDValue();
6332 
6333   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6334           N->getOpcode() == ISD::SHL) &&
6335          "Unknown shift to lower!");
6336 
6337   unsigned ShOpc = N->getOpcode();
6338   if (ST->hasMVEIntegerOps()) {
6339     SDValue ShAmt = N->getOperand(1);
6340     unsigned ShPartsOpc = ARMISD::LSLL;
6341     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6342 
6343     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6344     // then do the default optimisation
6345     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6346         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6347       return SDValue();
6348 
6349     // Extract the lower 32 bits of the shift amount if it's not an i32
6350     if (ShAmt->getValueType(0) != MVT::i32)
6351       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6352 
6353     if (ShOpc == ISD::SRL) {
6354       if (!Con)
6355         // There is no t2LSRLr instruction so negate and perform an lsll if the
6356         // shift amount is in a register, emulating a right shift.
6357         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6358                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6359       else
6360         // Else generate an lsrl on the immediate shift amount
6361         ShPartsOpc = ARMISD::LSRL;
6362     } else if (ShOpc == ISD::SRA)
6363       ShPartsOpc = ARMISD::ASRL;
6364 
6365     // Lower 32 bits of the destination/source
6366     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6367                              DAG.getConstant(0, dl, MVT::i32));
6368     // Upper 32 bits of the destination/source
6369     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6370                              DAG.getConstant(1, dl, MVT::i32));
6371 
6372     // Generate the shift operation as computed above
6373     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6374                      ShAmt);
6375     // The upper 32 bits come from the second return value of lsll
6376     Hi = SDValue(Lo.getNode(), 1);
6377     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6378   }
6379 
6380   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6381   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6382     return SDValue();
6383 
6384   // If we are in thumb mode, we don't have RRX.
6385   if (ST->isThumb1Only())
6386     return SDValue();
6387 
6388   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6389   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6390                            DAG.getConstant(0, dl, MVT::i32));
6391   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6392                            DAG.getConstant(1, dl, MVT::i32));
6393 
6394   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6395   // captures the result into a carry flag.
6396   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6397   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6398 
6399   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6400   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6401 
6402   // Merge the pieces into a single i64 value.
6403  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6404 }
6405 
6406 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6407                            const ARMSubtarget *ST) {
6408   bool Invert = false;
6409   bool Swap = false;
6410   unsigned Opc = ARMCC::AL;
6411 
6412   SDValue Op0 = Op.getOperand(0);
6413   SDValue Op1 = Op.getOperand(1);
6414   SDValue CC = Op.getOperand(2);
6415   EVT VT = Op.getValueType();
6416   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6417   SDLoc dl(Op);
6418 
6419   EVT CmpVT;
6420   if (ST->hasNEON())
6421     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6422   else {
6423     assert(ST->hasMVEIntegerOps() &&
6424            "No hardware support for integer vector comparison!");
6425 
6426     if (Op.getValueType().getVectorElementType() != MVT::i1)
6427       return SDValue();
6428 
6429     // Make sure we expand floating point setcc to scalar if we do not have
6430     // mve.fp, so that we can handle them from there.
6431     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6432       return SDValue();
6433 
6434     CmpVT = VT;
6435   }
6436 
6437   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6438       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6439     // Special-case integer 64-bit equality comparisons. They aren't legal,
6440     // but they can be lowered with a few vector instructions.
6441     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6442     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6443     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6444     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6445     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6446                               DAG.getCondCode(ISD::SETEQ));
6447     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6448     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6449     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6450     if (SetCCOpcode == ISD::SETNE)
6451       Merged = DAG.getNOT(dl, Merged, CmpVT);
6452     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6453     return Merged;
6454   }
6455 
6456   if (CmpVT.getVectorElementType() == MVT::i64)
6457     // 64-bit comparisons are not legal in general.
6458     return SDValue();
6459 
6460   if (Op1.getValueType().isFloatingPoint()) {
6461     switch (SetCCOpcode) {
6462     default: llvm_unreachable("Illegal FP comparison");
6463     case ISD::SETUNE:
6464     case ISD::SETNE:
6465       if (ST->hasMVEFloatOps()) {
6466         Opc = ARMCC::NE; break;
6467       } else {
6468         Invert = true; LLVM_FALLTHROUGH;
6469       }
6470     case ISD::SETOEQ:
6471     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6472     case ISD::SETOLT:
6473     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6474     case ISD::SETOGT:
6475     case ISD::SETGT:  Opc = ARMCC::GT; break;
6476     case ISD::SETOLE:
6477     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6478     case ISD::SETOGE:
6479     case ISD::SETGE: Opc = ARMCC::GE; break;
6480     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6481     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6482     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6483     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6484     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6485     case ISD::SETONE: {
6486       // Expand this to (OLT | OGT).
6487       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6488                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6489       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6490                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6491       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6492       if (Invert)
6493         Result = DAG.getNOT(dl, Result, VT);
6494       return Result;
6495     }
6496     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6497     case ISD::SETO: {
6498       // Expand this to (OLT | OGE).
6499       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6500                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6501       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6502                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6503       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6504       if (Invert)
6505         Result = DAG.getNOT(dl, Result, VT);
6506       return Result;
6507     }
6508     }
6509   } else {
6510     // Integer comparisons.
6511     switch (SetCCOpcode) {
6512     default: llvm_unreachable("Illegal integer comparison");
6513     case ISD::SETNE:
6514       if (ST->hasMVEIntegerOps()) {
6515         Opc = ARMCC::NE; break;
6516       } else {
6517         Invert = true; LLVM_FALLTHROUGH;
6518       }
6519     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6520     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6521     case ISD::SETGT:  Opc = ARMCC::GT; break;
6522     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6523     case ISD::SETGE:  Opc = ARMCC::GE; break;
6524     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6525     case ISD::SETUGT: Opc = ARMCC::HI; break;
6526     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6527     case ISD::SETUGE: Opc = ARMCC::HS; break;
6528     }
6529 
6530     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6531     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6532       SDValue AndOp;
6533       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6534         AndOp = Op0;
6535       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6536         AndOp = Op1;
6537 
6538       // Ignore bitconvert.
6539       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6540         AndOp = AndOp.getOperand(0);
6541 
6542       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6543         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6544         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6545         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6546         if (!Invert)
6547           Result = DAG.getNOT(dl, Result, VT);
6548         return Result;
6549       }
6550     }
6551   }
6552 
6553   if (Swap)
6554     std::swap(Op0, Op1);
6555 
6556   // If one of the operands is a constant vector zero, attempt to fold the
6557   // comparison to a specialized compare-against-zero form.
6558   SDValue SingleOp;
6559   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6560     SingleOp = Op0;
6561   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6562     if (Opc == ARMCC::GE)
6563       Opc = ARMCC::LE;
6564     else if (Opc == ARMCC::GT)
6565       Opc = ARMCC::LT;
6566     SingleOp = Op1;
6567   }
6568 
6569   SDValue Result;
6570   if (SingleOp.getNode()) {
6571     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6572                          DAG.getConstant(Opc, dl, MVT::i32));
6573   } else {
6574     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6575                          DAG.getConstant(Opc, dl, MVT::i32));
6576   }
6577 
6578   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6579 
6580   if (Invert)
6581     Result = DAG.getNOT(dl, Result, VT);
6582 
6583   return Result;
6584 }
6585 
6586 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6587   SDValue LHS = Op.getOperand(0);
6588   SDValue RHS = Op.getOperand(1);
6589   SDValue Carry = Op.getOperand(2);
6590   SDValue Cond = Op.getOperand(3);
6591   SDLoc DL(Op);
6592 
6593   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6594 
6595   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6596   // have to invert the carry first.
6597   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6598                       DAG.getConstant(1, DL, MVT::i32), Carry);
6599   // This converts the boolean value carry into the carry flag.
6600   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6601 
6602   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6603   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6604 
6605   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6606   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6607   SDValue ARMcc = DAG.getConstant(
6608       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6609   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6610   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6611                                    Cmp.getValue(1), SDValue());
6612   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6613                      CCR, Chain.getValue(1));
6614 }
6615 
6616 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6617 /// valid vector constant for a NEON or MVE instruction with a "modified
6618 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6619 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6620                                  unsigned SplatBitSize, SelectionDAG &DAG,
6621                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
6622                                  VMOVModImmType type) {
6623   unsigned OpCmode, Imm;
6624   bool is128Bits = VectorVT.is128BitVector();
6625 
6626   // SplatBitSize is set to the smallest size that splats the vector, so a
6627   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6628   // immediate instructions others than VMOV do not support the 8-bit encoding
6629   // of a zero vector, and the default encoding of zero is supposed to be the
6630   // 32-bit version.
6631   if (SplatBits == 0)
6632     SplatBitSize = 32;
6633 
6634   switch (SplatBitSize) {
6635   case 8:
6636     if (type != VMOVModImm)
6637       return SDValue();
6638     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6639     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6640     OpCmode = 0xe;
6641     Imm = SplatBits;
6642     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6643     break;
6644 
6645   case 16:
6646     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6647     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6648     if ((SplatBits & ~0xff) == 0) {
6649       // Value = 0x00nn: Op=x, Cmode=100x.
6650       OpCmode = 0x8;
6651       Imm = SplatBits;
6652       break;
6653     }
6654     if ((SplatBits & ~0xff00) == 0) {
6655       // Value = 0xnn00: Op=x, Cmode=101x.
6656       OpCmode = 0xa;
6657       Imm = SplatBits >> 8;
6658       break;
6659     }
6660     return SDValue();
6661 
6662   case 32:
6663     // NEON's 32-bit VMOV supports splat values where:
6664     // * only one byte is nonzero, or
6665     // * the least significant byte is 0xff and the second byte is nonzero, or
6666     // * the least significant 2 bytes are 0xff and the third is nonzero.
6667     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6668     if ((SplatBits & ~0xff) == 0) {
6669       // Value = 0x000000nn: Op=x, Cmode=000x.
6670       OpCmode = 0;
6671       Imm = SplatBits;
6672       break;
6673     }
6674     if ((SplatBits & ~0xff00) == 0) {
6675       // Value = 0x0000nn00: Op=x, Cmode=001x.
6676       OpCmode = 0x2;
6677       Imm = SplatBits >> 8;
6678       break;
6679     }
6680     if ((SplatBits & ~0xff0000) == 0) {
6681       // Value = 0x00nn0000: Op=x, Cmode=010x.
6682       OpCmode = 0x4;
6683       Imm = SplatBits >> 16;
6684       break;
6685     }
6686     if ((SplatBits & ~0xff000000) == 0) {
6687       // Value = 0xnn000000: Op=x, Cmode=011x.
6688       OpCmode = 0x6;
6689       Imm = SplatBits >> 24;
6690       break;
6691     }
6692 
6693     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6694     if (type == OtherModImm) return SDValue();
6695 
6696     if ((SplatBits & ~0xffff) == 0 &&
6697         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6698       // Value = 0x0000nnff: Op=x, Cmode=1100.
6699       OpCmode = 0xc;
6700       Imm = SplatBits >> 8;
6701       break;
6702     }
6703 
6704     // cmode == 0b1101 is not supported for MVE VMVN
6705     if (type == MVEVMVNModImm)
6706       return SDValue();
6707 
6708     if ((SplatBits & ~0xffffff) == 0 &&
6709         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6710       // Value = 0x00nnffff: Op=x, Cmode=1101.
6711       OpCmode = 0xd;
6712       Imm = SplatBits >> 16;
6713       break;
6714     }
6715 
6716     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6717     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6718     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6719     // and fall through here to test for a valid 64-bit splat.  But, then the
6720     // caller would also need to check and handle the change in size.
6721     return SDValue();
6722 
6723   case 64: {
6724     if (type != VMOVModImm)
6725       return SDValue();
6726     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6727     uint64_t BitMask = 0xff;
6728     uint64_t Val = 0;
6729     unsigned ImmMask = 1;
6730     Imm = 0;
6731     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6732       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6733         Val |= BitMask;
6734         Imm |= ImmMask;
6735       } else if ((SplatBits & BitMask) != 0) {
6736         return SDValue();
6737       }
6738       BitMask <<= 8;
6739       ImmMask <<= 1;
6740     }
6741 
6742     if (DAG.getDataLayout().isBigEndian()) {
6743       // Reverse the order of elements within the vector.
6744       unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6745       unsigned Mask = (1 << BytesPerElem) - 1;
6746       unsigned NumElems = 8 / BytesPerElem;
6747       unsigned NewImm = 0;
6748       for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6749         unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6750         NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6751       }
6752       Imm = NewImm;
6753     }
6754 
6755     // Op=1, Cmode=1110.
6756     OpCmode = 0x1e;
6757     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6758     break;
6759   }
6760 
6761   default:
6762     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6763   }
6764 
6765   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6766   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6767 }
6768 
6769 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6770                                            const ARMSubtarget *ST) const {
6771   EVT VT = Op.getValueType();
6772   bool IsDouble = (VT == MVT::f64);
6773   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6774   const APFloat &FPVal = CFP->getValueAPF();
6775 
6776   // Prevent floating-point constants from using literal loads
6777   // when execute-only is enabled.
6778   if (ST->genExecuteOnly()) {
6779     // If we can represent the constant as an immediate, don't lower it
6780     if (isFPImmLegal(FPVal, VT))
6781       return Op;
6782     // Otherwise, construct as integer, and move to float register
6783     APInt INTVal = FPVal.bitcastToAPInt();
6784     SDLoc DL(CFP);
6785     switch (VT.getSimpleVT().SimpleTy) {
6786       default:
6787         llvm_unreachable("Unknown floating point type!");
6788         break;
6789       case MVT::f64: {
6790         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6791         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6792         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6793       }
6794       case MVT::f32:
6795           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6796               DAG.getConstant(INTVal, DL, MVT::i32));
6797     }
6798   }
6799 
6800   if (!ST->hasVFP3Base())
6801     return SDValue();
6802 
6803   // Use the default (constant pool) lowering for double constants when we have
6804   // an SP-only FPU
6805   if (IsDouble && !Subtarget->hasFP64())
6806     return SDValue();
6807 
6808   // Try splatting with a VMOV.f32...
6809   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6810 
6811   if (ImmVal != -1) {
6812     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6813       // We have code in place to select a valid ConstantFP already, no need to
6814       // do any mangling.
6815       return Op;
6816     }
6817 
6818     // It's a float and we are trying to use NEON operations where
6819     // possible. Lower it to a splat followed by an extract.
6820     SDLoc DL(Op);
6821     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6822     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6823                                       NewVal);
6824     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6825                        DAG.getConstant(0, DL, MVT::i32));
6826   }
6827 
6828   // The rest of our options are NEON only, make sure that's allowed before
6829   // proceeding..
6830   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6831     return SDValue();
6832 
6833   EVT VMovVT;
6834   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6835 
6836   // It wouldn't really be worth bothering for doubles except for one very
6837   // important value, which does happen to match: 0.0. So make sure we don't do
6838   // anything stupid.
6839   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6840     return SDValue();
6841 
6842   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6843   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6844                                      VMovVT, VT, VMOVModImm);
6845   if (NewVal != SDValue()) {
6846     SDLoc DL(Op);
6847     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6848                                       NewVal);
6849     if (IsDouble)
6850       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6851 
6852     // It's a float: cast and extract a vector element.
6853     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6854                                        VecConstant);
6855     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6856                        DAG.getConstant(0, DL, MVT::i32));
6857   }
6858 
6859   // Finally, try a VMVN.i32
6860   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6861                              VT, VMVNModImm);
6862   if (NewVal != SDValue()) {
6863     SDLoc DL(Op);
6864     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6865 
6866     if (IsDouble)
6867       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6868 
6869     // It's a float: cast and extract a vector element.
6870     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6871                                        VecConstant);
6872     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6873                        DAG.getConstant(0, DL, MVT::i32));
6874   }
6875 
6876   return SDValue();
6877 }
6878 
6879 // check if an VEXT instruction can handle the shuffle mask when the
6880 // vector sources of the shuffle are the same.
6881 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6882   unsigned NumElts = VT.getVectorNumElements();
6883 
6884   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6885   if (M[0] < 0)
6886     return false;
6887 
6888   Imm = M[0];
6889 
6890   // If this is a VEXT shuffle, the immediate value is the index of the first
6891   // element.  The other shuffle indices must be the successive elements after
6892   // the first one.
6893   unsigned ExpectedElt = Imm;
6894   for (unsigned i = 1; i < NumElts; ++i) {
6895     // Increment the expected index.  If it wraps around, just follow it
6896     // back to index zero and keep going.
6897     ++ExpectedElt;
6898     if (ExpectedElt == NumElts)
6899       ExpectedElt = 0;
6900 
6901     if (M[i] < 0) continue; // ignore UNDEF indices
6902     if (ExpectedElt != static_cast<unsigned>(M[i]))
6903       return false;
6904   }
6905 
6906   return true;
6907 }
6908 
6909 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6910                        bool &ReverseVEXT, unsigned &Imm) {
6911   unsigned NumElts = VT.getVectorNumElements();
6912   ReverseVEXT = false;
6913 
6914   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6915   if (M[0] < 0)
6916     return false;
6917 
6918   Imm = M[0];
6919 
6920   // If this is a VEXT shuffle, the immediate value is the index of the first
6921   // element.  The other shuffle indices must be the successive elements after
6922   // the first one.
6923   unsigned ExpectedElt = Imm;
6924   for (unsigned i = 1; i < NumElts; ++i) {
6925     // Increment the expected index.  If it wraps around, it may still be
6926     // a VEXT but the source vectors must be swapped.
6927     ExpectedElt += 1;
6928     if (ExpectedElt == NumElts * 2) {
6929       ExpectedElt = 0;
6930       ReverseVEXT = true;
6931     }
6932 
6933     if (M[i] < 0) continue; // ignore UNDEF indices
6934     if (ExpectedElt != static_cast<unsigned>(M[i]))
6935       return false;
6936   }
6937 
6938   // Adjust the index value if the source operands will be swapped.
6939   if (ReverseVEXT)
6940     Imm -= NumElts;
6941 
6942   return true;
6943 }
6944 
6945 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6946 /// instruction with the specified blocksize.  (The order of the elements
6947 /// within each block of the vector is reversed.)
6948 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6949   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6950          "Only possible block sizes for VREV are: 16, 32, 64");
6951 
6952   unsigned EltSz = VT.getScalarSizeInBits();
6953   if (EltSz == 64)
6954     return false;
6955 
6956   unsigned NumElts = VT.getVectorNumElements();
6957   unsigned BlockElts = M[0] + 1;
6958   // If the first shuffle index is UNDEF, be optimistic.
6959   if (M[0] < 0)
6960     BlockElts = BlockSize / EltSz;
6961 
6962   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6963     return false;
6964 
6965   for (unsigned i = 0; i < NumElts; ++i) {
6966     if (M[i] < 0) continue; // ignore UNDEF indices
6967     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6968       return false;
6969   }
6970 
6971   return true;
6972 }
6973 
6974 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6975   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6976   // range, then 0 is placed into the resulting vector. So pretty much any mask
6977   // of 8 elements can work here.
6978   return VT == MVT::v8i8 && M.size() == 8;
6979 }
6980 
6981 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6982                                unsigned Index) {
6983   if (Mask.size() == Elements * 2)
6984     return Index / Elements;
6985   return Mask[Index] == 0 ? 0 : 1;
6986 }
6987 
6988 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6989 // checking that pairs of elements in the shuffle mask represent the same index
6990 // in each vector, incrementing the expected index by 2 at each step.
6991 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6992 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6993 //  v2={e,f,g,h}
6994 // WhichResult gives the offset for each element in the mask based on which
6995 // of the two results it belongs to.
6996 //
6997 // The transpose can be represented either as:
6998 // result1 = shufflevector v1, v2, result1_shuffle_mask
6999 // result2 = shufflevector v1, v2, result2_shuffle_mask
7000 // where v1/v2 and the shuffle masks have the same number of elements
7001 // (here WhichResult (see below) indicates which result is being checked)
7002 //
7003 // or as:
7004 // results = shufflevector v1, v2, shuffle_mask
7005 // where both results are returned in one vector and the shuffle mask has twice
7006 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7007 // want to check the low half and high half of the shuffle mask as if it were
7008 // the other case
7009 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7010   unsigned EltSz = VT.getScalarSizeInBits();
7011   if (EltSz == 64)
7012     return false;
7013 
7014   unsigned NumElts = VT.getVectorNumElements();
7015   if (M.size() != NumElts && M.size() != NumElts*2)
7016     return false;
7017 
7018   // If the mask is twice as long as the input vector then we need to check the
7019   // upper and lower parts of the mask with a matching value for WhichResult
7020   // FIXME: A mask with only even values will be rejected in case the first
7021   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7022   // M[0] is used to determine WhichResult
7023   for (unsigned i = 0; i < M.size(); i += NumElts) {
7024     WhichResult = SelectPairHalf(NumElts, M, i);
7025     for (unsigned j = 0; j < NumElts; j += 2) {
7026       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7027           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7028         return false;
7029     }
7030   }
7031 
7032   if (M.size() == NumElts*2)
7033     WhichResult = 0;
7034 
7035   return true;
7036 }
7037 
7038 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7039 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7040 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7041 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7042   unsigned EltSz = VT.getScalarSizeInBits();
7043   if (EltSz == 64)
7044     return false;
7045 
7046   unsigned NumElts = VT.getVectorNumElements();
7047   if (M.size() != NumElts && M.size() != NumElts*2)
7048     return false;
7049 
7050   for (unsigned i = 0; i < M.size(); i += NumElts) {
7051     WhichResult = SelectPairHalf(NumElts, M, i);
7052     for (unsigned j = 0; j < NumElts; j += 2) {
7053       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7054           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7055         return false;
7056     }
7057   }
7058 
7059   if (M.size() == NumElts*2)
7060     WhichResult = 0;
7061 
7062   return true;
7063 }
7064 
7065 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7066 // that the mask elements are either all even and in steps of size 2 or all odd
7067 // and in steps of size 2.
7068 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7069 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7070 //  v2={e,f,g,h}
7071 // Requires similar checks to that of isVTRNMask with
7072 // respect the how results are returned.
7073 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7074   unsigned EltSz = VT.getScalarSizeInBits();
7075   if (EltSz == 64)
7076     return false;
7077 
7078   unsigned NumElts = VT.getVectorNumElements();
7079   if (M.size() != NumElts && M.size() != NumElts*2)
7080     return false;
7081 
7082   for (unsigned i = 0; i < M.size(); i += NumElts) {
7083     WhichResult = SelectPairHalf(NumElts, M, i);
7084     for (unsigned j = 0; j < NumElts; ++j) {
7085       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7086         return false;
7087     }
7088   }
7089 
7090   if (M.size() == NumElts*2)
7091     WhichResult = 0;
7092 
7093   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7094   if (VT.is64BitVector() && EltSz == 32)
7095     return false;
7096 
7097   return true;
7098 }
7099 
7100 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7101 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7102 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7103 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7104   unsigned EltSz = VT.getScalarSizeInBits();
7105   if (EltSz == 64)
7106     return false;
7107 
7108   unsigned NumElts = VT.getVectorNumElements();
7109   if (M.size() != NumElts && M.size() != NumElts*2)
7110     return false;
7111 
7112   unsigned Half = NumElts / 2;
7113   for (unsigned i = 0; i < M.size(); i += NumElts) {
7114     WhichResult = SelectPairHalf(NumElts, M, i);
7115     for (unsigned j = 0; j < NumElts; j += Half) {
7116       unsigned Idx = WhichResult;
7117       for (unsigned k = 0; k < Half; ++k) {
7118         int MIdx = M[i + j + k];
7119         if (MIdx >= 0 && (unsigned) MIdx != Idx)
7120           return false;
7121         Idx += 2;
7122       }
7123     }
7124   }
7125 
7126   if (M.size() == NumElts*2)
7127     WhichResult = 0;
7128 
7129   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7130   if (VT.is64BitVector() && EltSz == 32)
7131     return false;
7132 
7133   return true;
7134 }
7135 
7136 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7137 // that pairs of elements of the shufflemask represent the same index in each
7138 // vector incrementing sequentially through the vectors.
7139 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7140 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7141 //  v2={e,f,g,h}
7142 // Requires similar checks to that of isVTRNMask with respect the how results
7143 // are returned.
7144 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7145   unsigned EltSz = VT.getScalarSizeInBits();
7146   if (EltSz == 64)
7147     return false;
7148 
7149   unsigned NumElts = VT.getVectorNumElements();
7150   if (M.size() != NumElts && M.size() != NumElts*2)
7151     return false;
7152 
7153   for (unsigned i = 0; i < M.size(); i += NumElts) {
7154     WhichResult = SelectPairHalf(NumElts, M, i);
7155     unsigned Idx = WhichResult * NumElts / 2;
7156     for (unsigned j = 0; j < NumElts; j += 2) {
7157       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7158           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7159         return false;
7160       Idx += 1;
7161     }
7162   }
7163 
7164   if (M.size() == NumElts*2)
7165     WhichResult = 0;
7166 
7167   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7168   if (VT.is64BitVector() && EltSz == 32)
7169     return false;
7170 
7171   return true;
7172 }
7173 
7174 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7175 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7176 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7177 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7178   unsigned EltSz = VT.getScalarSizeInBits();
7179   if (EltSz == 64)
7180     return false;
7181 
7182   unsigned NumElts = VT.getVectorNumElements();
7183   if (M.size() != NumElts && M.size() != NumElts*2)
7184     return false;
7185 
7186   for (unsigned i = 0; i < M.size(); i += NumElts) {
7187     WhichResult = SelectPairHalf(NumElts, M, i);
7188     unsigned Idx = WhichResult * NumElts / 2;
7189     for (unsigned j = 0; j < NumElts; j += 2) {
7190       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7191           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7192         return false;
7193       Idx += 1;
7194     }
7195   }
7196 
7197   if (M.size() == NumElts*2)
7198     WhichResult = 0;
7199 
7200   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7201   if (VT.is64BitVector() && EltSz == 32)
7202     return false;
7203 
7204   return true;
7205 }
7206 
7207 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7208 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7209 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7210                                            unsigned &WhichResult,
7211                                            bool &isV_UNDEF) {
7212   isV_UNDEF = false;
7213   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7214     return ARMISD::VTRN;
7215   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7216     return ARMISD::VUZP;
7217   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7218     return ARMISD::VZIP;
7219 
7220   isV_UNDEF = true;
7221   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7222     return ARMISD::VTRN;
7223   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7224     return ARMISD::VUZP;
7225   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7226     return ARMISD::VZIP;
7227 
7228   return 0;
7229 }
7230 
7231 /// \return true if this is a reverse operation on an vector.
7232 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7233   unsigned NumElts = VT.getVectorNumElements();
7234   // Make sure the mask has the right size.
7235   if (NumElts != M.size())
7236       return false;
7237 
7238   // Look for <15, ..., 3, -1, 1, 0>.
7239   for (unsigned i = 0; i != NumElts; ++i)
7240     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7241       return false;
7242 
7243   return true;
7244 }
7245 
7246 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7247   unsigned NumElts = VT.getVectorNumElements();
7248   // Make sure the mask has the right size.
7249   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7250       return false;
7251 
7252   // If Top
7253   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7254   //   This inserts Input2 into Input1
7255   // else if not Top
7256   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7257   //   This inserts Input1 into Input2
7258   unsigned Offset = Top ? 0 : 1;
7259   for (unsigned i = 0; i < NumElts; i+=2) {
7260     if (M[i] >= 0 && M[i] != (int)i)
7261       return false;
7262     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7263       return false;
7264   }
7265 
7266   return true;
7267 }
7268 
7269 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7270 // from a pair of inputs. For example:
7271 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7272 //             FP_ROUND(EXTRACT_ELT(Y, 0),
7273 //             FP_ROUND(EXTRACT_ELT(X, 1),
7274 //             FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7275 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7276                                          const ARMSubtarget *ST) {
7277   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7278   if (!ST->hasMVEFloatOps())
7279     return SDValue();
7280 
7281   SDLoc dl(BV);
7282   EVT VT = BV.getValueType();
7283   if (VT != MVT::v8f16)
7284     return SDValue();
7285 
7286   // We are looking for a buildvector of fptrunc elements, where all the
7287   // elements are interleavingly extracted from two sources. Check the first two
7288   // items are valid enough and extract some info from them (they are checked
7289   // properly in the loop below).
7290   if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7291       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7292       BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7293     return SDValue();
7294   if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7295       BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7296       BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7297     return SDValue();
7298   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7299   SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7300   if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7301     return SDValue();
7302 
7303   // Check all the values in the BuildVector line up with our expectations.
7304   for (unsigned i = 1; i < 4; i++) {
7305     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7306       return Trunc.getOpcode() == ISD::FP_ROUND &&
7307              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7308              Trunc.getOperand(0).getOperand(0) == Op &&
7309              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7310     };
7311     if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7312       return SDValue();
7313     if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7314       return SDValue();
7315   }
7316 
7317   SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7318                            DAG.getConstant(0, dl, MVT::i32));
7319   return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7320                      DAG.getConstant(1, dl, MVT::i32));
7321 }
7322 
7323 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7324 // from a single input on alternating lanes. For example:
7325 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7326 //             FP_ROUND(EXTRACT_ELT(X, 2),
7327 //             FP_ROUND(EXTRACT_ELT(X, 4), ...)
7328 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7329                                        const ARMSubtarget *ST) {
7330   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7331   if (!ST->hasMVEFloatOps())
7332     return SDValue();
7333 
7334   SDLoc dl(BV);
7335   EVT VT = BV.getValueType();
7336   if (VT != MVT::v4f32)
7337     return SDValue();
7338 
7339   // We are looking for a buildvector of fptext elements, where all the
7340   // elements are alternating lanes from a single source. For example <0,2,4,6>
7341   // or <1,3,5,7>. Check the first two items are valid enough and extract some
7342   // info from them (they are checked properly in the loop below).
7343   if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7344       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7345     return SDValue();
7346   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7347   int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7348   if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7349     return SDValue();
7350 
7351   // Check all the values in the BuildVector line up with our expectations.
7352   for (unsigned i = 1; i < 4; i++) {
7353     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7354       return Trunc.getOpcode() == ISD::FP_EXTEND &&
7355              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7356              Trunc.getOperand(0).getOperand(0) == Op &&
7357              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7358     };
7359     if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7360       return SDValue();
7361   }
7362 
7363   return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7364                      DAG.getConstant(Offset, dl, MVT::i32));
7365 }
7366 
7367 // If N is an integer constant that can be moved into a register in one
7368 // instruction, return an SDValue of such a constant (will become a MOV
7369 // instruction).  Otherwise return null.
7370 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7371                                      const ARMSubtarget *ST, const SDLoc &dl) {
7372   uint64_t Val;
7373   if (!isa<ConstantSDNode>(N))
7374     return SDValue();
7375   Val = cast<ConstantSDNode>(N)->getZExtValue();
7376 
7377   if (ST->isThumb1Only()) {
7378     if (Val <= 255 || ~Val <= 255)
7379       return DAG.getConstant(Val, dl, MVT::i32);
7380   } else {
7381     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7382       return DAG.getConstant(Val, dl, MVT::i32);
7383   }
7384   return SDValue();
7385 }
7386 
7387 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7388                                     const ARMSubtarget *ST) {
7389   SDLoc dl(Op);
7390   EVT VT = Op.getValueType();
7391 
7392   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7393 
7394   unsigned NumElts = VT.getVectorNumElements();
7395   unsigned BoolMask;
7396   unsigned BitsPerBool;
7397   if (NumElts == 4) {
7398     BitsPerBool = 4;
7399     BoolMask = 0xf;
7400   } else if (NumElts == 8) {
7401     BitsPerBool = 2;
7402     BoolMask = 0x3;
7403   } else if (NumElts == 16) {
7404     BitsPerBool = 1;
7405     BoolMask = 0x1;
7406   } else
7407     return SDValue();
7408 
7409   // If this is a single value copied into all lanes (a splat), we can just sign
7410   // extend that single value
7411   SDValue FirstOp = Op.getOperand(0);
7412   if (!isa<ConstantSDNode>(FirstOp) &&
7413       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7414                   [&FirstOp](SDUse &U) {
7415                     return U.get().isUndef() || U.get() == FirstOp;
7416                   })) {
7417     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7418                               DAG.getValueType(MVT::i1));
7419     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7420   }
7421 
7422   // First create base with bits set where known
7423   unsigned Bits32 = 0;
7424   for (unsigned i = 0; i < NumElts; ++i) {
7425     SDValue V = Op.getOperand(i);
7426     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7427       continue;
7428     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7429     if (BitSet)
7430       Bits32 |= BoolMask << (i * BitsPerBool);
7431   }
7432 
7433   // Add in unknown nodes
7434   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7435                              DAG.getConstant(Bits32, dl, MVT::i32));
7436   for (unsigned i = 0; i < NumElts; ++i) {
7437     SDValue V = Op.getOperand(i);
7438     if (isa<ConstantSDNode>(V) || V.isUndef())
7439       continue;
7440     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7441                        DAG.getConstant(i, dl, MVT::i32));
7442   }
7443 
7444   return Base;
7445 }
7446 
7447 // If this is a case we can't handle, return null and let the default
7448 // expansion code take care of it.
7449 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7450                                              const ARMSubtarget *ST) const {
7451   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7452   SDLoc dl(Op);
7453   EVT VT = Op.getValueType();
7454 
7455   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7456     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7457 
7458   APInt SplatBits, SplatUndef;
7459   unsigned SplatBitSize;
7460   bool HasAnyUndefs;
7461   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7462     if (SplatUndef.isAllOnesValue())
7463       return DAG.getUNDEF(VT);
7464 
7465     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7466         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7467       // Check if an immediate VMOV works.
7468       EVT VmovVT;
7469       SDValue Val =
7470           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7471                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7472 
7473       if (Val.getNode()) {
7474         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7475         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7476       }
7477 
7478       // Try an immediate VMVN.
7479       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7480       Val = isVMOVModifiedImm(
7481           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7482           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7483       if (Val.getNode()) {
7484         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7485         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7486       }
7487 
7488       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7489       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7490         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7491         if (ImmVal != -1) {
7492           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7493           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7494         }
7495       }
7496     }
7497   }
7498 
7499   // Scan through the operands to see if only one value is used.
7500   //
7501   // As an optimisation, even if more than one value is used it may be more
7502   // profitable to splat with one value then change some lanes.
7503   //
7504   // Heuristically we decide to do this if the vector has a "dominant" value,
7505   // defined as splatted to more than half of the lanes.
7506   unsigned NumElts = VT.getVectorNumElements();
7507   bool isOnlyLowElement = true;
7508   bool usesOnlyOneValue = true;
7509   bool hasDominantValue = false;
7510   bool isConstant = true;
7511 
7512   // Map of the number of times a particular SDValue appears in the
7513   // element list.
7514   DenseMap<SDValue, unsigned> ValueCounts;
7515   SDValue Value;
7516   for (unsigned i = 0; i < NumElts; ++i) {
7517     SDValue V = Op.getOperand(i);
7518     if (V.isUndef())
7519       continue;
7520     if (i > 0)
7521       isOnlyLowElement = false;
7522     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7523       isConstant = false;
7524 
7525     ValueCounts.insert(std::make_pair(V, 0));
7526     unsigned &Count = ValueCounts[V];
7527 
7528     // Is this value dominant? (takes up more than half of the lanes)
7529     if (++Count > (NumElts / 2)) {
7530       hasDominantValue = true;
7531       Value = V;
7532     }
7533   }
7534   if (ValueCounts.size() != 1)
7535     usesOnlyOneValue = false;
7536   if (!Value.getNode() && !ValueCounts.empty())
7537     Value = ValueCounts.begin()->first;
7538 
7539   if (ValueCounts.empty())
7540     return DAG.getUNDEF(VT);
7541 
7542   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7543   // Keep going if we are hitting this case.
7544   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7545     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7546 
7547   unsigned EltSize = VT.getScalarSizeInBits();
7548 
7549   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7550   // i32 and try again.
7551   if (hasDominantValue && EltSize <= 32) {
7552     if (!isConstant) {
7553       SDValue N;
7554 
7555       // If we are VDUPing a value that comes directly from a vector, that will
7556       // cause an unnecessary move to and from a GPR, where instead we could
7557       // just use VDUPLANE. We can only do this if the lane being extracted
7558       // is at a constant index, as the VDUP from lane instructions only have
7559       // constant-index forms.
7560       ConstantSDNode *constIndex;
7561       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7562           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7563         // We need to create a new undef vector to use for the VDUPLANE if the
7564         // size of the vector from which we get the value is different than the
7565         // size of the vector that we need to create. We will insert the element
7566         // such that the register coalescer will remove unnecessary copies.
7567         if (VT != Value->getOperand(0).getValueType()) {
7568           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7569                              VT.getVectorNumElements();
7570           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7571                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7572                         Value, DAG.getConstant(index, dl, MVT::i32)),
7573                            DAG.getConstant(index, dl, MVT::i32));
7574         } else
7575           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7576                         Value->getOperand(0), Value->getOperand(1));
7577       } else
7578         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7579 
7580       if (!usesOnlyOneValue) {
7581         // The dominant value was splatted as 'N', but we now have to insert
7582         // all differing elements.
7583         for (unsigned I = 0; I < NumElts; ++I) {
7584           if (Op.getOperand(I) == Value)
7585             continue;
7586           SmallVector<SDValue, 3> Ops;
7587           Ops.push_back(N);
7588           Ops.push_back(Op.getOperand(I));
7589           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7590           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7591         }
7592       }
7593       return N;
7594     }
7595     if (VT.getVectorElementType().isFloatingPoint()) {
7596       SmallVector<SDValue, 8> Ops;
7597       MVT FVT = VT.getVectorElementType().getSimpleVT();
7598       assert(FVT == MVT::f32 || FVT == MVT::f16);
7599       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7600       for (unsigned i = 0; i < NumElts; ++i)
7601         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7602                                   Op.getOperand(i)));
7603       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7604       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7605       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7606       if (Val.getNode())
7607         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7608     }
7609     if (usesOnlyOneValue) {
7610       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7611       if (isConstant && Val.getNode())
7612         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7613     }
7614   }
7615 
7616   // If all elements are constants and the case above didn't get hit, fall back
7617   // to the default expansion, which will generate a load from the constant
7618   // pool.
7619   if (isConstant)
7620     return SDValue();
7621 
7622   // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7623   // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7624   // length <= 2.
7625   if (NumElts >= 4)
7626     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7627       return shuffle;
7628 
7629   // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7630   // VCVT's
7631   if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7632     return VCVT;
7633   if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7634     return VCVT;
7635 
7636   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7637     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7638     // into two 64-bit vectors; we might discover a better way to lower it.
7639     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7640     EVT ExtVT = VT.getVectorElementType();
7641     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7642     SDValue Lower =
7643         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7644     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7645       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7646     SDValue Upper = DAG.getBuildVector(
7647         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7648     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7649       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7650     if (Lower && Upper)
7651       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7652   }
7653 
7654   // Vectors with 32- or 64-bit elements can be built by directly assigning
7655   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7656   // will be legalized.
7657   if (EltSize >= 32) {
7658     // Do the expansion with floating-point types, since that is what the VFP
7659     // registers are defined to use, and since i64 is not legal.
7660     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7661     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7662     SmallVector<SDValue, 8> Ops;
7663     for (unsigned i = 0; i < NumElts; ++i)
7664       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7665     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7666     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7667   }
7668 
7669   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7670   // know the default expansion would otherwise fall back on something even
7671   // worse. For a vector with one or two non-undef values, that's
7672   // scalar_to_vector for the elements followed by a shuffle (provided the
7673   // shuffle is valid for the target) and materialization element by element
7674   // on the stack followed by a load for everything else.
7675   if (!isConstant && !usesOnlyOneValue) {
7676     SDValue Vec = DAG.getUNDEF(VT);
7677     for (unsigned i = 0 ; i < NumElts; ++i) {
7678       SDValue V = Op.getOperand(i);
7679       if (V.isUndef())
7680         continue;
7681       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7682       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7683     }
7684     return Vec;
7685   }
7686 
7687   return SDValue();
7688 }
7689 
7690 // Gather data to see if the operation can be modelled as a
7691 // shuffle in combination with VEXTs.
7692 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7693                                               SelectionDAG &DAG) const {
7694   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7695   SDLoc dl(Op);
7696   EVT VT = Op.getValueType();
7697   unsigned NumElts = VT.getVectorNumElements();
7698 
7699   struct ShuffleSourceInfo {
7700     SDValue Vec;
7701     unsigned MinElt = std::numeric_limits<unsigned>::max();
7702     unsigned MaxElt = 0;
7703 
7704     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7705     // be compatible with the shuffle we intend to construct. As a result
7706     // ShuffleVec will be some sliding window into the original Vec.
7707     SDValue ShuffleVec;
7708 
7709     // Code should guarantee that element i in Vec starts at element "WindowBase
7710     // + i * WindowScale in ShuffleVec".
7711     int WindowBase = 0;
7712     int WindowScale = 1;
7713 
7714     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7715 
7716     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7717   };
7718 
7719   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7720   // node.
7721   SmallVector<ShuffleSourceInfo, 2> Sources;
7722   for (unsigned i = 0; i < NumElts; ++i) {
7723     SDValue V = Op.getOperand(i);
7724     if (V.isUndef())
7725       continue;
7726     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7727       // A shuffle can only come from building a vector from various
7728       // elements of other vectors.
7729       return SDValue();
7730     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7731       // Furthermore, shuffles require a constant mask, whereas extractelts
7732       // accept variable indices.
7733       return SDValue();
7734     }
7735 
7736     // Add this element source to the list if it's not already there.
7737     SDValue SourceVec = V.getOperand(0);
7738     auto Source = llvm::find(Sources, SourceVec);
7739     if (Source == Sources.end())
7740       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7741 
7742     // Update the minimum and maximum lane number seen.
7743     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7744     Source->MinElt = std::min(Source->MinElt, EltNo);
7745     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7746   }
7747 
7748   // Currently only do something sane when at most two source vectors
7749   // are involved.
7750   if (Sources.size() > 2)
7751     return SDValue();
7752 
7753   // Find out the smallest element size among result and two sources, and use
7754   // it as element size to build the shuffle_vector.
7755   EVT SmallestEltTy = VT.getVectorElementType();
7756   for (auto &Source : Sources) {
7757     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7758     if (SrcEltTy.bitsLT(SmallestEltTy))
7759       SmallestEltTy = SrcEltTy;
7760   }
7761   unsigned ResMultiplier =
7762       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7763   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7764   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7765 
7766   // If the source vector is too wide or too narrow, we may nevertheless be able
7767   // to construct a compatible shuffle either by concatenating it with UNDEF or
7768   // extracting a suitable range of elements.
7769   for (auto &Src : Sources) {
7770     EVT SrcVT = Src.ShuffleVec.getValueType();
7771 
7772     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7773     uint64_t VTSize = VT.getFixedSizeInBits();
7774     if (SrcVTSize == VTSize)
7775       continue;
7776 
7777     // This stage of the search produces a source with the same element type as
7778     // the original, but with a total width matching the BUILD_VECTOR output.
7779     EVT EltVT = SrcVT.getVectorElementType();
7780     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7781     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7782 
7783     if (SrcVTSize < VTSize) {
7784       if (2 * SrcVTSize != VTSize)
7785         return SDValue();
7786       // We can pad out the smaller vector for free, so if it's part of a
7787       // shuffle...
7788       Src.ShuffleVec =
7789           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7790                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7791       continue;
7792     }
7793 
7794     if (SrcVTSize != 2 * VTSize)
7795       return SDValue();
7796 
7797     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7798       // Span too large for a VEXT to cope
7799       return SDValue();
7800     }
7801 
7802     if (Src.MinElt >= NumSrcElts) {
7803       // The extraction can just take the second half
7804       Src.ShuffleVec =
7805           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7806                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7807       Src.WindowBase = -NumSrcElts;
7808     } else if (Src.MaxElt < NumSrcElts) {
7809       // The extraction can just take the first half
7810       Src.ShuffleVec =
7811           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7812                       DAG.getConstant(0, dl, MVT::i32));
7813     } else {
7814       // An actual VEXT is needed
7815       SDValue VEXTSrc1 =
7816           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7817                       DAG.getConstant(0, dl, MVT::i32));
7818       SDValue VEXTSrc2 =
7819           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7820                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7821 
7822       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7823                                    VEXTSrc2,
7824                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7825       Src.WindowBase = -Src.MinElt;
7826     }
7827   }
7828 
7829   // Another possible incompatibility occurs from the vector element types. We
7830   // can fix this by bitcasting the source vectors to the same type we intend
7831   // for the shuffle.
7832   for (auto &Src : Sources) {
7833     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7834     if (SrcEltTy == SmallestEltTy)
7835       continue;
7836     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7837     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7838     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7839     Src.WindowBase *= Src.WindowScale;
7840   }
7841 
7842   // Final sanity check before we try to actually produce a shuffle.
7843   LLVM_DEBUG(for (auto Src
7844                   : Sources)
7845                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7846 
7847   // The stars all align, our next step is to produce the mask for the shuffle.
7848   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7849   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7850   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7851     SDValue Entry = Op.getOperand(i);
7852     if (Entry.isUndef())
7853       continue;
7854 
7855     auto Src = llvm::find(Sources, Entry.getOperand(0));
7856     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7857 
7858     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7859     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7860     // segment.
7861     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7862     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
7863                                VT.getScalarSizeInBits());
7864     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7865 
7866     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7867     // starting at the appropriate offset.
7868     int *LaneMask = &Mask[i * ResMultiplier];
7869 
7870     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7871     ExtractBase += NumElts * (Src - Sources.begin());
7872     for (int j = 0; j < LanesDefined; ++j)
7873       LaneMask[j] = ExtractBase + j;
7874   }
7875 
7876 
7877   // We can't handle more than two sources. This should have already
7878   // been checked before this point.
7879   assert(Sources.size() <= 2 && "Too many sources!");
7880 
7881   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7882   for (unsigned i = 0; i < Sources.size(); ++i)
7883     ShuffleOps[i] = Sources[i].ShuffleVec;
7884 
7885   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7886                                             ShuffleOps[1], Mask, DAG);
7887   if (!Shuffle)
7888     return SDValue();
7889   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7890 }
7891 
7892 enum ShuffleOpCodes {
7893   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7894   OP_VREV,
7895   OP_VDUP0,
7896   OP_VDUP1,
7897   OP_VDUP2,
7898   OP_VDUP3,
7899   OP_VEXT1,
7900   OP_VEXT2,
7901   OP_VEXT3,
7902   OP_VUZPL, // VUZP, left result
7903   OP_VUZPR, // VUZP, right result
7904   OP_VZIPL, // VZIP, left result
7905   OP_VZIPR, // VZIP, right result
7906   OP_VTRNL, // VTRN, left result
7907   OP_VTRNR  // VTRN, right result
7908 };
7909 
7910 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7911   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7912   switch (OpNum) {
7913   case OP_COPY:
7914   case OP_VREV:
7915   case OP_VDUP0:
7916   case OP_VDUP1:
7917   case OP_VDUP2:
7918   case OP_VDUP3:
7919     return true;
7920   }
7921   return false;
7922 }
7923 
7924 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7925 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7926 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7927 /// are assumed to be legal.
7928 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7929   if (VT.getVectorNumElements() == 4 &&
7930       (VT.is128BitVector() || VT.is64BitVector())) {
7931     unsigned PFIndexes[4];
7932     for (unsigned i = 0; i != 4; ++i) {
7933       if (M[i] < 0)
7934         PFIndexes[i] = 8;
7935       else
7936         PFIndexes[i] = M[i];
7937     }
7938 
7939     // Compute the index in the perfect shuffle table.
7940     unsigned PFTableIndex =
7941       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7942     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7943     unsigned Cost = (PFEntry >> 30);
7944 
7945     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7946       return true;
7947   }
7948 
7949   bool ReverseVEXT, isV_UNDEF;
7950   unsigned Imm, WhichResult;
7951 
7952   unsigned EltSize = VT.getScalarSizeInBits();
7953   if (EltSize >= 32 ||
7954       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7955       ShuffleVectorInst::isIdentityMask(M) ||
7956       isVREVMask(M, VT, 64) ||
7957       isVREVMask(M, VT, 32) ||
7958       isVREVMask(M, VT, 16))
7959     return true;
7960   else if (Subtarget->hasNEON() &&
7961            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7962             isVTBLMask(M, VT) ||
7963             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7964     return true;
7965   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7966            isReverseMask(M, VT))
7967     return true;
7968   else if (Subtarget->hasMVEIntegerOps() &&
7969            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7970     return true;
7971   else
7972     return false;
7973 }
7974 
7975 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7976 /// the specified operations to build the shuffle.
7977 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7978                                       SDValue RHS, SelectionDAG &DAG,
7979                                       const SDLoc &dl) {
7980   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7981   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7982   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7983 
7984   if (OpNum == OP_COPY) {
7985     if (LHSID == (1*9+2)*9+3) return LHS;
7986     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7987     return RHS;
7988   }
7989 
7990   SDValue OpLHS, OpRHS;
7991   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7992   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7993   EVT VT = OpLHS.getValueType();
7994 
7995   switch (OpNum) {
7996   default: llvm_unreachable("Unknown shuffle opcode!");
7997   case OP_VREV:
7998     // VREV divides the vector in half and swaps within the half.
7999     if (VT.getVectorElementType() == MVT::i32 ||
8000         VT.getVectorElementType() == MVT::f32)
8001       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8002     // vrev <4 x i16> -> VREV32
8003     if (VT.getVectorElementType() == MVT::i16)
8004       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8005     // vrev <4 x i8> -> VREV16
8006     assert(VT.getVectorElementType() == MVT::i8);
8007     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8008   case OP_VDUP0:
8009   case OP_VDUP1:
8010   case OP_VDUP2:
8011   case OP_VDUP3:
8012     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8013                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8014   case OP_VEXT1:
8015   case OP_VEXT2:
8016   case OP_VEXT3:
8017     return DAG.getNode(ARMISD::VEXT, dl, VT,
8018                        OpLHS, OpRHS,
8019                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8020   case OP_VUZPL:
8021   case OP_VUZPR:
8022     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8023                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8024   case OP_VZIPL:
8025   case OP_VZIPR:
8026     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8027                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8028   case OP_VTRNL:
8029   case OP_VTRNR:
8030     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8031                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8032   }
8033 }
8034 
8035 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8036                                        ArrayRef<int> ShuffleMask,
8037                                        SelectionDAG &DAG) {
8038   // Check to see if we can use the VTBL instruction.
8039   SDValue V1 = Op.getOperand(0);
8040   SDValue V2 = Op.getOperand(1);
8041   SDLoc DL(Op);
8042 
8043   SmallVector<SDValue, 8> VTBLMask;
8044   for (ArrayRef<int>::iterator
8045          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
8046     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
8047 
8048   if (V2.getNode()->isUndef())
8049     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8050                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8051 
8052   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8053                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8054 }
8055 
8056 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
8057                                                       SelectionDAG &DAG) {
8058   SDLoc DL(Op);
8059   SDValue OpLHS = Op.getOperand(0);
8060   EVT VT = OpLHS.getValueType();
8061 
8062   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
8063          "Expect an v8i16/v16i8 type");
8064   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
8065   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
8066   // extract the first 8 bytes into the top double word and the last 8 bytes
8067   // into the bottom double word. The v8i16 case is similar.
8068   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
8069   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
8070                      DAG.getConstant(ExtractNum, DL, MVT::i32));
8071 }
8072 
8073 static EVT getVectorTyFromPredicateVector(EVT VT) {
8074   switch (VT.getSimpleVT().SimpleTy) {
8075   case MVT::v4i1:
8076     return MVT::v4i32;
8077   case MVT::v8i1:
8078     return MVT::v8i16;
8079   case MVT::v16i1:
8080     return MVT::v16i8;
8081   default:
8082     llvm_unreachable("Unexpected vector predicate type");
8083   }
8084 }
8085 
8086 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8087                                     SelectionDAG &DAG) {
8088   // Converting from boolean predicates to integers involves creating a vector
8089   // of all ones or all zeroes and selecting the lanes based upon the real
8090   // predicate.
8091   SDValue AllOnes =
8092       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8093   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8094 
8095   SDValue AllZeroes =
8096       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8097   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8098 
8099   // Get full vector type from predicate type
8100   EVT NewVT = getVectorTyFromPredicateVector(VT);
8101 
8102   SDValue RecastV1;
8103   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8104   // this to a v16i1. This cannot be done with an ordinary bitcast because the
8105   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8106   // since we know in hardware the sizes are really the same.
8107   if (VT != MVT::v16i1)
8108     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8109   else
8110     RecastV1 = Pred;
8111 
8112   // Select either all ones or zeroes depending upon the real predicate bits.
8113   SDValue PredAsVector =
8114       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8115 
8116   // Recast our new predicate-as-integer v16i8 vector into something
8117   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8118   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8119 }
8120 
8121 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8122                                       const ARMSubtarget *ST) {
8123   EVT VT = Op.getValueType();
8124   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8125   ArrayRef<int> ShuffleMask = SVN->getMask();
8126 
8127   assert(ST->hasMVEIntegerOps() &&
8128          "No support for vector shuffle of boolean predicates");
8129 
8130   SDValue V1 = Op.getOperand(0);
8131   SDLoc dl(Op);
8132   if (isReverseMask(ShuffleMask, VT)) {
8133     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8134     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8135     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8136                               DAG.getConstant(16, dl, MVT::i32));
8137     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8138   }
8139 
8140   // Until we can come up with optimised cases for every single vector
8141   // shuffle in existence we have chosen the least painful strategy. This is
8142   // to essentially promote the boolean predicate to a 8-bit integer, where
8143   // each predicate represents a byte. Then we fall back on a normal integer
8144   // vector shuffle and convert the result back into a predicate vector. In
8145   // many cases the generated code might be even better than scalar code
8146   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8147   // fields in a register into 8 other arbitrary 2-bit fields!
8148   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8149   EVT NewVT = PredAsVector.getValueType();
8150 
8151   // Do the shuffle!
8152   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8153                                           DAG.getUNDEF(NewVT), ShuffleMask);
8154 
8155   // Now return the result of comparing the shuffled vector with zero,
8156   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8157   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8158                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8159 }
8160 
8161 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8162                                             ArrayRef<int> ShuffleMask,
8163                                             SelectionDAG &DAG) {
8164   // Attempt to lower the vector shuffle using as many whole register movs as
8165   // possible. This is useful for types smaller than 32bits, which would
8166   // often otherwise become a series for grp movs.
8167   SDLoc dl(Op);
8168   EVT VT = Op.getValueType();
8169   if (VT.getScalarSizeInBits() >= 32)
8170     return SDValue();
8171 
8172   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8173          "Unexpected vector type");
8174   int NumElts = VT.getVectorNumElements();
8175   int QuarterSize = NumElts / 4;
8176   // The four final parts of the vector, as i32's
8177   SDValue Parts[4];
8178 
8179   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8180   // <u,u,u,u>), returning the vmov lane index
8181   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8182     // Detect which mov lane this would be from the first non-undef element.
8183     int MovIdx = -1;
8184     for (int i = 0; i < Length; i++) {
8185       if (ShuffleMask[Start + i] >= 0) {
8186         if (ShuffleMask[Start + i] % Length != i)
8187           return -1;
8188         MovIdx = ShuffleMask[Start + i] / Length;
8189         break;
8190       }
8191     }
8192     // If all items are undef, leave this for other combines
8193     if (MovIdx == -1)
8194       return -1;
8195     // Check the remaining values are the correct part of the same mov
8196     for (int i = 1; i < Length; i++) {
8197       if (ShuffleMask[Start + i] >= 0 &&
8198           (ShuffleMask[Start + i] / Length != MovIdx ||
8199            ShuffleMask[Start + i] % Length != i))
8200         return -1;
8201     }
8202     return MovIdx;
8203   };
8204 
8205   for (int Part = 0; Part < 4; ++Part) {
8206     // Does this part look like a mov
8207     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8208     if (Elt != -1) {
8209       SDValue Input = Op->getOperand(0);
8210       if (Elt >= 4) {
8211         Input = Op->getOperand(1);
8212         Elt -= 4;
8213       }
8214       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
8215       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
8216                                 DAG.getConstant(Elt, dl, MVT::i32));
8217     }
8218   }
8219 
8220   // Nothing interesting found, just return
8221   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8222     return SDValue();
8223 
8224   // The other parts need to be built with the old shuffle vector, cast to a
8225   // v4i32 and extract_vector_elts
8226   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8227     SmallVector<int, 16> NewShuffleMask;
8228     for (int Part = 0; Part < 4; ++Part)
8229       for (int i = 0; i < QuarterSize; i++)
8230         NewShuffleMask.push_back(
8231             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8232     SDValue NewShuffle = DAG.getVectorShuffle(
8233         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8234     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
8235 
8236     for (int Part = 0; Part < 4; ++Part)
8237       if (!Parts[Part])
8238         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8239                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
8240   }
8241   // Build a vector out of the various parts and bitcast it back to the original
8242   // type.
8243   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
8244   return DAG.getBitcast(VT, NewVec);
8245 }
8246 
8247 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8248                                    const ARMSubtarget *ST) {
8249   SDValue V1 = Op.getOperand(0);
8250   SDValue V2 = Op.getOperand(1);
8251   SDLoc dl(Op);
8252   EVT VT = Op.getValueType();
8253   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8254   unsigned EltSize = VT.getScalarSizeInBits();
8255 
8256   if (ST->hasMVEIntegerOps() && EltSize == 1)
8257     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8258 
8259   // Convert shuffles that are directly supported on NEON to target-specific
8260   // DAG nodes, instead of keeping them as shuffles and matching them again
8261   // during code selection.  This is more efficient and avoids the possibility
8262   // of inconsistencies between legalization and selection.
8263   // FIXME: floating-point vectors should be canonicalized to integer vectors
8264   // of the same time so that they get CSEd properly.
8265   ArrayRef<int> ShuffleMask = SVN->getMask();
8266 
8267   if (EltSize <= 32) {
8268     if (SVN->isSplat()) {
8269       int Lane = SVN->getSplatIndex();
8270       // If this is undef splat, generate it via "just" vdup, if possible.
8271       if (Lane == -1) Lane = 0;
8272 
8273       // Test if V1 is a SCALAR_TO_VECTOR.
8274       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8275         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8276       }
8277       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8278       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8279       // reaches it).
8280       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8281           !isa<ConstantSDNode>(V1.getOperand(0))) {
8282         bool IsScalarToVector = true;
8283         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8284           if (!V1.getOperand(i).isUndef()) {
8285             IsScalarToVector = false;
8286             break;
8287           }
8288         if (IsScalarToVector)
8289           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8290       }
8291       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8292                          DAG.getConstant(Lane, dl, MVT::i32));
8293     }
8294 
8295     bool ReverseVEXT = false;
8296     unsigned Imm = 0;
8297     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8298       if (ReverseVEXT)
8299         std::swap(V1, V2);
8300       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8301                          DAG.getConstant(Imm, dl, MVT::i32));
8302     }
8303 
8304     if (isVREVMask(ShuffleMask, VT, 64))
8305       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8306     if (isVREVMask(ShuffleMask, VT, 32))
8307       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8308     if (isVREVMask(ShuffleMask, VT, 16))
8309       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8310 
8311     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8312       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8313                          DAG.getConstant(Imm, dl, MVT::i32));
8314     }
8315 
8316     // Check for Neon shuffles that modify both input vectors in place.
8317     // If both results are used, i.e., if there are two shuffles with the same
8318     // source operands and with masks corresponding to both results of one of
8319     // these operations, DAG memoization will ensure that a single node is
8320     // used for both shuffles.
8321     unsigned WhichResult = 0;
8322     bool isV_UNDEF = false;
8323     if (ST->hasNEON()) {
8324       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8325               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8326         if (isV_UNDEF)
8327           V2 = V1;
8328         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8329             .getValue(WhichResult);
8330       }
8331     }
8332     if (ST->hasMVEIntegerOps()) {
8333       if (isVMOVNMask(ShuffleMask, VT, 0))
8334         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8335                            DAG.getConstant(0, dl, MVT::i32));
8336       if (isVMOVNMask(ShuffleMask, VT, 1))
8337         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8338                            DAG.getConstant(1, dl, MVT::i32));
8339     }
8340 
8341     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8342     // shuffles that produce a result larger than their operands with:
8343     //   shuffle(concat(v1, undef), concat(v2, undef))
8344     // ->
8345     //   shuffle(concat(v1, v2), undef)
8346     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8347     //
8348     // This is useful in the general case, but there are special cases where
8349     // native shuffles produce larger results: the two-result ops.
8350     //
8351     // Look through the concat when lowering them:
8352     //   shuffle(concat(v1, v2), undef)
8353     // ->
8354     //   concat(VZIP(v1, v2):0, :1)
8355     //
8356     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8357       SDValue SubV1 = V1->getOperand(0);
8358       SDValue SubV2 = V1->getOperand(1);
8359       EVT SubVT = SubV1.getValueType();
8360 
8361       // We expect these to have been canonicalized to -1.
8362       assert(llvm::all_of(ShuffleMask, [&](int i) {
8363         return i < (int)VT.getVectorNumElements();
8364       }) && "Unexpected shuffle index into UNDEF operand!");
8365 
8366       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8367               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8368         if (isV_UNDEF)
8369           SubV2 = SubV1;
8370         assert((WhichResult == 0) &&
8371                "In-place shuffle of concat can only have one result!");
8372         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8373                                   SubV1, SubV2);
8374         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8375                            Res.getValue(1));
8376       }
8377     }
8378   }
8379 
8380   // If the shuffle is not directly supported and it has 4 elements, use
8381   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8382   unsigned NumElts = VT.getVectorNumElements();
8383   if (NumElts == 4) {
8384     unsigned PFIndexes[4];
8385     for (unsigned i = 0; i != 4; ++i) {
8386       if (ShuffleMask[i] < 0)
8387         PFIndexes[i] = 8;
8388       else
8389         PFIndexes[i] = ShuffleMask[i];
8390     }
8391 
8392     // Compute the index in the perfect shuffle table.
8393     unsigned PFTableIndex =
8394       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8395     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8396     unsigned Cost = (PFEntry >> 30);
8397 
8398     if (Cost <= 4) {
8399       if (ST->hasNEON())
8400         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8401       else if (isLegalMVEShuffleOp(PFEntry)) {
8402         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8403         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8404         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8405         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8406         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8407           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8408       }
8409     }
8410   }
8411 
8412   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8413   if (EltSize >= 32) {
8414     // Do the expansion with floating-point types, since that is what the VFP
8415     // registers are defined to use, and since i64 is not legal.
8416     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8417     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8418     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8419     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8420     SmallVector<SDValue, 8> Ops;
8421     for (unsigned i = 0; i < NumElts; ++i) {
8422       if (ShuffleMask[i] < 0)
8423         Ops.push_back(DAG.getUNDEF(EltVT));
8424       else
8425         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8426                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8427                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8428                                                   dl, MVT::i32)));
8429     }
8430     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8431     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8432   }
8433 
8434   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8435     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8436 
8437   if (ST->hasNEON() && VT == MVT::v8i8)
8438     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8439       return NewOp;
8440 
8441   if (ST->hasMVEIntegerOps())
8442     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8443       return NewOp;
8444 
8445   return SDValue();
8446 }
8447 
8448 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8449                                          const ARMSubtarget *ST) {
8450   EVT VecVT = Op.getOperand(0).getValueType();
8451   SDLoc dl(Op);
8452 
8453   assert(ST->hasMVEIntegerOps() &&
8454          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8455 
8456   SDValue Conv =
8457       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8458   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8459   unsigned LaneWidth =
8460       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8461   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8462   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8463                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8464   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8465                             DAG.getConstant(~Mask, dl, MVT::i32));
8466   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8467 }
8468 
8469 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8470                                                   SelectionDAG &DAG) const {
8471   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8472   SDValue Lane = Op.getOperand(2);
8473   if (!isa<ConstantSDNode>(Lane))
8474     return SDValue();
8475 
8476   SDValue Elt = Op.getOperand(1);
8477   EVT EltVT = Elt.getValueType();
8478 
8479   if (Subtarget->hasMVEIntegerOps() &&
8480       Op.getValueType().getScalarSizeInBits() == 1)
8481     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8482 
8483   if (getTypeAction(*DAG.getContext(), EltVT) ==
8484       TargetLowering::TypePromoteFloat) {
8485     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8486     // but the type system will try to do that if we don't intervene.
8487     // Reinterpret any such vector-element insertion as one with the
8488     // corresponding integer types.
8489 
8490     SDLoc dl(Op);
8491 
8492     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8493     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8494            TargetLowering::TypePromoteFloat);
8495 
8496     SDValue VecIn = Op.getOperand(0);
8497     EVT VecVT = VecIn.getValueType();
8498     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8499                                   VecVT.getVectorNumElements());
8500 
8501     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8502     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8503     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8504                                   IVecIn, IElt, Lane);
8505     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8506   }
8507 
8508   return Op;
8509 }
8510 
8511 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8512                                           const ARMSubtarget *ST) {
8513   EVT VecVT = Op.getOperand(0).getValueType();
8514   SDLoc dl(Op);
8515 
8516   assert(ST->hasMVEIntegerOps() &&
8517          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8518 
8519   SDValue Conv =
8520       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8521   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8522   unsigned LaneWidth =
8523       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8524   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8525                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8526   return Shift;
8527 }
8528 
8529 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8530                                        const ARMSubtarget *ST) {
8531   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8532   SDValue Lane = Op.getOperand(1);
8533   if (!isa<ConstantSDNode>(Lane))
8534     return SDValue();
8535 
8536   SDValue Vec = Op.getOperand(0);
8537   EVT VT = Vec.getValueType();
8538 
8539   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8540     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8541 
8542   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8543     SDLoc dl(Op);
8544     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8545   }
8546 
8547   return Op;
8548 }
8549 
8550 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8551                                       const ARMSubtarget *ST) {
8552   SDValue V1 = Op.getOperand(0);
8553   SDValue V2 = Op.getOperand(1);
8554   SDLoc dl(Op);
8555   EVT VT = Op.getValueType();
8556   EVT Op1VT = V1.getValueType();
8557   EVT Op2VT = V2.getValueType();
8558   unsigned NumElts = VT.getVectorNumElements();
8559 
8560   assert(Op1VT == Op2VT && "Operand types don't match!");
8561   assert(VT.getScalarSizeInBits() == 1 &&
8562          "Unexpected custom CONCAT_VECTORS lowering");
8563   assert(ST->hasMVEIntegerOps() &&
8564          "CONCAT_VECTORS lowering only supported for MVE");
8565 
8566   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8567   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8568 
8569   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8570   // promoted to v8i16, etc.
8571 
8572   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8573 
8574   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8575   // to be the right size for the destination. For example, if Op1 is v4i1 then
8576   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8577   // which when promoted is v8i16. That means each i32 element from Op1 needs
8578   // truncating to i16 and inserting in the result.
8579   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8580   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8581   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8582     EVT NewVT = NewV.getValueType();
8583     EVT ConcatVT = ConVec.getValueType();
8584     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8585       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8586                                 DAG.getIntPtrConstant(i, dl));
8587       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8588                            DAG.getConstant(j, dl, MVT::i32));
8589     }
8590     return ConVec;
8591   };
8592   unsigned j = 0;
8593   ConVec = ExractInto(NewV1, ConVec, j);
8594   ConVec = ExractInto(NewV2, ConVec, j);
8595 
8596   // Now return the result of comparing the subvector with zero,
8597   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8598   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8599                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8600 }
8601 
8602 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8603                                    const ARMSubtarget *ST) {
8604   EVT VT = Op->getValueType(0);
8605   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8606     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8607 
8608   // The only time a CONCAT_VECTORS operation can have legal types is when
8609   // two 64-bit vectors are concatenated to a 128-bit vector.
8610   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8611          "unexpected CONCAT_VECTORS");
8612   SDLoc dl(Op);
8613   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8614   SDValue Op0 = Op.getOperand(0);
8615   SDValue Op1 = Op.getOperand(1);
8616   if (!Op0.isUndef())
8617     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8618                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8619                       DAG.getIntPtrConstant(0, dl));
8620   if (!Op1.isUndef())
8621     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8622                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8623                       DAG.getIntPtrConstant(1, dl));
8624   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8625 }
8626 
8627 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8628                                       const ARMSubtarget *ST) {
8629   SDValue V1 = Op.getOperand(0);
8630   SDValue V2 = Op.getOperand(1);
8631   SDLoc dl(Op);
8632   EVT VT = Op.getValueType();
8633   EVT Op1VT = V1.getValueType();
8634   unsigned NumElts = VT.getVectorNumElements();
8635   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8636 
8637   assert(VT.getScalarSizeInBits() == 1 &&
8638          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8639   assert(ST->hasMVEIntegerOps() &&
8640          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8641 
8642   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8643 
8644   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8645   // promoted to v8i16, etc.
8646 
8647   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8648 
8649   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8650   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8651   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8652     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8653                               DAG.getIntPtrConstant(i, dl));
8654     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8655                          DAG.getConstant(j, dl, MVT::i32));
8656   }
8657 
8658   // Now return the result of comparing the subvector with zero,
8659   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8660   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8661                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8662 }
8663 
8664 // Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
8665 static SDValue LowerTruncatei1(SDValue N, SelectionDAG &DAG,
8666                                const ARMSubtarget *ST) {
8667   assert(ST->hasMVEIntegerOps() && "Expected MVE!");
8668   EVT VT = N.getValueType();
8669   assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
8670          "Expected a vector i1 type!");
8671   SDValue Op = N.getOperand(0);
8672   EVT FromVT = Op.getValueType();
8673   SDLoc DL(N);
8674 
8675   SDValue And =
8676       DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
8677   return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
8678                      DAG.getCondCode(ISD::SETNE));
8679 }
8680 
8681 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8682 /// element has been zero/sign-extended, depending on the isSigned parameter,
8683 /// from an integer type half its size.
8684 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8685                                    bool isSigned) {
8686   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8687   EVT VT = N->getValueType(0);
8688   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8689     SDNode *BVN = N->getOperand(0).getNode();
8690     if (BVN->getValueType(0) != MVT::v4i32 ||
8691         BVN->getOpcode() != ISD::BUILD_VECTOR)
8692       return false;
8693     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8694     unsigned HiElt = 1 - LoElt;
8695     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8696     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8697     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8698     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8699     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8700       return false;
8701     if (isSigned) {
8702       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8703           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8704         return true;
8705     } else {
8706       if (Hi0->isNullValue() && Hi1->isNullValue())
8707         return true;
8708     }
8709     return false;
8710   }
8711 
8712   if (N->getOpcode() != ISD::BUILD_VECTOR)
8713     return false;
8714 
8715   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8716     SDNode *Elt = N->getOperand(i).getNode();
8717     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8718       unsigned EltSize = VT.getScalarSizeInBits();
8719       unsigned HalfSize = EltSize / 2;
8720       if (isSigned) {
8721         if (!isIntN(HalfSize, C->getSExtValue()))
8722           return false;
8723       } else {
8724         if (!isUIntN(HalfSize, C->getZExtValue()))
8725           return false;
8726       }
8727       continue;
8728     }
8729     return false;
8730   }
8731 
8732   return true;
8733 }
8734 
8735 /// isSignExtended - Check if a node is a vector value that is sign-extended
8736 /// or a constant BUILD_VECTOR with sign-extended elements.
8737 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8738   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8739     return true;
8740   if (isExtendedBUILD_VECTOR(N, DAG, true))
8741     return true;
8742   return false;
8743 }
8744 
8745 /// isZeroExtended - Check if a node is a vector value that is zero-extended (or
8746 /// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
8747 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8748   if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
8749       ISD::isZEXTLoad(N))
8750     return true;
8751   if (isExtendedBUILD_VECTOR(N, DAG, false))
8752     return true;
8753   return false;
8754 }
8755 
8756 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8757   if (OrigVT.getSizeInBits() >= 64)
8758     return OrigVT;
8759 
8760   assert(OrigVT.isSimple() && "Expecting a simple value type");
8761 
8762   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8763   switch (OrigSimpleTy) {
8764   default: llvm_unreachable("Unexpected Vector Type");
8765   case MVT::v2i8:
8766   case MVT::v2i16:
8767      return MVT::v2i32;
8768   case MVT::v4i8:
8769     return  MVT::v4i16;
8770   }
8771 }
8772 
8773 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8774 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8775 /// We insert the required extension here to get the vector to fill a D register.
8776 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8777                                             const EVT &OrigTy,
8778                                             const EVT &ExtTy,
8779                                             unsigned ExtOpcode) {
8780   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8781   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8782   // 64-bits we need to insert a new extension so that it will be 64-bits.
8783   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8784   if (OrigTy.getSizeInBits() >= 64)
8785     return N;
8786 
8787   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8788   EVT NewVT = getExtensionTo64Bits(OrigTy);
8789 
8790   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8791 }
8792 
8793 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8794 /// does not do any sign/zero extension. If the original vector is less
8795 /// than 64 bits, an appropriate extension will be added after the load to
8796 /// reach a total size of 64 bits. We have to add the extension separately
8797 /// because ARM does not have a sign/zero extending load for vectors.
8798 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8799   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8800 
8801   // The load already has the right type.
8802   if (ExtendedTy == LD->getMemoryVT())
8803     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8804                        LD->getBasePtr(), LD->getPointerInfo(),
8805                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8806 
8807   // We need to create a zextload/sextload. We cannot just create a load
8808   // followed by a zext/zext node because LowerMUL is also run during normal
8809   // operation legalization where we can't create illegal types.
8810   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8811                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8812                         LD->getMemoryVT(), LD->getAlignment(),
8813                         LD->getMemOperand()->getFlags());
8814 }
8815 
8816 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8817 /// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
8818 /// the unextended value. The unextended vector should be 64 bits so that it can
8819 /// be used as an operand to a VMULL instruction. If the original vector size
8820 /// before extension is less than 64 bits we add a an extension to resize
8821 /// the vector to 64 bits.
8822 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8823   if (N->getOpcode() == ISD::SIGN_EXTEND ||
8824       N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
8825     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8826                                         N->getOperand(0)->getValueType(0),
8827                                         N->getValueType(0),
8828                                         N->getOpcode());
8829 
8830   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8831     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8832            "Expected extending load");
8833 
8834     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8835     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8836     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8837     SDValue extLoad =
8838         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8839     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8840 
8841     return newLoad;
8842   }
8843 
8844   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8845   // have been legalized as a BITCAST from v4i32.
8846   if (N->getOpcode() == ISD::BITCAST) {
8847     SDNode *BVN = N->getOperand(0).getNode();
8848     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8849            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8850     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8851     return DAG.getBuildVector(
8852         MVT::v2i32, SDLoc(N),
8853         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8854   }
8855   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8856   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8857   EVT VT = N->getValueType(0);
8858   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8859   unsigned NumElts = VT.getVectorNumElements();
8860   MVT TruncVT = MVT::getIntegerVT(EltSize);
8861   SmallVector<SDValue, 8> Ops;
8862   SDLoc dl(N);
8863   for (unsigned i = 0; i != NumElts; ++i) {
8864     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8865     const APInt &CInt = C->getAPIntValue();
8866     // Element types smaller than 32 bits are not legal, so use i32 elements.
8867     // The values are implicitly truncated so sext vs. zext doesn't matter.
8868     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8869   }
8870   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8871 }
8872 
8873 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8874   unsigned Opcode = N->getOpcode();
8875   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8876     SDNode *N0 = N->getOperand(0).getNode();
8877     SDNode *N1 = N->getOperand(1).getNode();
8878     return N0->hasOneUse() && N1->hasOneUse() &&
8879       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8880   }
8881   return false;
8882 }
8883 
8884 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8885   unsigned Opcode = N->getOpcode();
8886   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8887     SDNode *N0 = N->getOperand(0).getNode();
8888     SDNode *N1 = N->getOperand(1).getNode();
8889     return N0->hasOneUse() && N1->hasOneUse() &&
8890       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8891   }
8892   return false;
8893 }
8894 
8895 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8896   // Multiplications are only custom-lowered for 128-bit vectors so that
8897   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8898   EVT VT = Op.getValueType();
8899   assert(VT.is128BitVector() && VT.isInteger() &&
8900          "unexpected type for custom-lowering ISD::MUL");
8901   SDNode *N0 = Op.getOperand(0).getNode();
8902   SDNode *N1 = Op.getOperand(1).getNode();
8903   unsigned NewOpc = 0;
8904   bool isMLA = false;
8905   bool isN0SExt = isSignExtended(N0, DAG);
8906   bool isN1SExt = isSignExtended(N1, DAG);
8907   if (isN0SExt && isN1SExt)
8908     NewOpc = ARMISD::VMULLs;
8909   else {
8910     bool isN0ZExt = isZeroExtended(N0, DAG);
8911     bool isN1ZExt = isZeroExtended(N1, DAG);
8912     if (isN0ZExt && isN1ZExt)
8913       NewOpc = ARMISD::VMULLu;
8914     else if (isN1SExt || isN1ZExt) {
8915       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8916       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8917       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8918         NewOpc = ARMISD::VMULLs;
8919         isMLA = true;
8920       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8921         NewOpc = ARMISD::VMULLu;
8922         isMLA = true;
8923       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8924         std::swap(N0, N1);
8925         NewOpc = ARMISD::VMULLu;
8926         isMLA = true;
8927       }
8928     }
8929 
8930     if (!NewOpc) {
8931       if (VT == MVT::v2i64)
8932         // Fall through to expand this.  It is not legal.
8933         return SDValue();
8934       else
8935         // Other vector multiplications are legal.
8936         return Op;
8937     }
8938   }
8939 
8940   // Legalize to a VMULL instruction.
8941   SDLoc DL(Op);
8942   SDValue Op0;
8943   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8944   if (!isMLA) {
8945     Op0 = SkipExtensionForVMULL(N0, DAG);
8946     assert(Op0.getValueType().is64BitVector() &&
8947            Op1.getValueType().is64BitVector() &&
8948            "unexpected types for extended operands to VMULL");
8949     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8950   }
8951 
8952   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8953   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8954   //   vmull q0, d4, d6
8955   //   vmlal q0, d5, d6
8956   // is faster than
8957   //   vaddl q0, d4, d5
8958   //   vmovl q1, d6
8959   //   vmul  q0, q0, q1
8960   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8961   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8962   EVT Op1VT = Op1.getValueType();
8963   return DAG.getNode(N0->getOpcode(), DL, VT,
8964                      DAG.getNode(NewOpc, DL, VT,
8965                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8966                      DAG.getNode(NewOpc, DL, VT,
8967                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8968 }
8969 
8970 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8971                               SelectionDAG &DAG) {
8972   // TODO: Should this propagate fast-math-flags?
8973 
8974   // Convert to float
8975   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8976   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8977   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8978   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8979   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8980   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8981   // Get reciprocal estimate.
8982   // float4 recip = vrecpeq_f32(yf);
8983   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8984                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8985                    Y);
8986   // Because char has a smaller range than uchar, we can actually get away
8987   // without any newton steps.  This requires that we use a weird bias
8988   // of 0xb000, however (again, this has been exhaustively tested).
8989   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8990   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8991   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8992   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8993   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8994   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8995   // Convert back to short.
8996   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8997   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8998   return X;
8999 }
9000 
9001 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9002                                SelectionDAG &DAG) {
9003   // TODO: Should this propagate fast-math-flags?
9004 
9005   SDValue N2;
9006   // Convert to float.
9007   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9008   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9009   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9010   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9011   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9012   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9013 
9014   // Use reciprocal estimate and one refinement step.
9015   // float4 recip = vrecpeq_f32(yf);
9016   // recip *= vrecpsq_f32(yf, recip);
9017   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9018                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9019                    N1);
9020   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9021                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9022                    N1, N2);
9023   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9024   // Because short has a smaller range than ushort, we can actually get away
9025   // with only a single newton step.  This requires that we use a weird bias
9026   // of 89, however (again, this has been exhaustively tested).
9027   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9028   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9029   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9030   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9031   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9032   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9033   // Convert back to integer and return.
9034   // return vmovn_s32(vcvt_s32_f32(result));
9035   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9036   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9037   return N0;
9038 }
9039 
9040 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9041                          const ARMSubtarget *ST) {
9042   EVT VT = Op.getValueType();
9043   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9044          "unexpected type for custom-lowering ISD::SDIV");
9045 
9046   SDLoc dl(Op);
9047   SDValue N0 = Op.getOperand(0);
9048   SDValue N1 = Op.getOperand(1);
9049   SDValue N2, N3;
9050 
9051   if (VT == MVT::v8i8) {
9052     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9053     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9054 
9055     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9056                      DAG.getIntPtrConstant(4, dl));
9057     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9058                      DAG.getIntPtrConstant(4, dl));
9059     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9060                      DAG.getIntPtrConstant(0, dl));
9061     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9062                      DAG.getIntPtrConstant(0, dl));
9063 
9064     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9065     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9066 
9067     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9068     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9069 
9070     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9071     return N0;
9072   }
9073   return LowerSDIV_v4i16(N0, N1, dl, DAG);
9074 }
9075 
9076 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9077                          const ARMSubtarget *ST) {
9078   // TODO: Should this propagate fast-math-flags?
9079   EVT VT = Op.getValueType();
9080   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9081          "unexpected type for custom-lowering ISD::UDIV");
9082 
9083   SDLoc dl(Op);
9084   SDValue N0 = Op.getOperand(0);
9085   SDValue N1 = Op.getOperand(1);
9086   SDValue N2, N3;
9087 
9088   if (VT == MVT::v8i8) {
9089     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9090     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9091 
9092     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9093                      DAG.getIntPtrConstant(4, dl));
9094     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9095                      DAG.getIntPtrConstant(4, dl));
9096     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9097                      DAG.getIntPtrConstant(0, dl));
9098     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9099                      DAG.getIntPtrConstant(0, dl));
9100 
9101     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9102     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9103 
9104     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9105     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9106 
9107     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9108                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9109                                      MVT::i32),
9110                      N0);
9111     return N0;
9112   }
9113 
9114   // v4i16 sdiv ... Convert to float.
9115   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9116   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9117   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9118   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9119   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9120   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9121 
9122   // Use reciprocal estimate and two refinement steps.
9123   // float4 recip = vrecpeq_f32(yf);
9124   // recip *= vrecpsq_f32(yf, recip);
9125   // recip *= vrecpsq_f32(yf, recip);
9126   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9127                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9128                    BN1);
9129   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9130                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9131                    BN1, N2);
9132   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9133   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9134                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9135                    BN1, N2);
9136   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9137   // Simply multiplying by the reciprocal estimate can leave us a few ulps
9138   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9139   // and that it will never cause us to return an answer too large).
9140   // float4 result = as_float4(as_int4(xf*recip) + 2);
9141   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9142   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9143   N1 = DAG.getConstant(2, dl, MVT::v4i32);
9144   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9145   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9146   // Convert back to integer and return.
9147   // return vmovn_u32(vcvt_s32_f32(result));
9148   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9149   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9150   return N0;
9151 }
9152 
9153 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9154   SDNode *N = Op.getNode();
9155   EVT VT = N->getValueType(0);
9156   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9157 
9158   SDValue Carry = Op.getOperand(2);
9159 
9160   SDLoc DL(Op);
9161 
9162   SDValue Result;
9163   if (Op.getOpcode() == ISD::ADDCARRY) {
9164     // This converts the boolean value carry into the carry flag.
9165     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9166 
9167     // Do the addition proper using the carry flag we wanted.
9168     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9169                          Op.getOperand(1), Carry);
9170 
9171     // Now convert the carry flag into a boolean value.
9172     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9173   } else {
9174     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9175     // have to invert the carry first.
9176     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9177                         DAG.getConstant(1, DL, MVT::i32), Carry);
9178     // This converts the boolean value carry into the carry flag.
9179     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9180 
9181     // Do the subtraction proper using the carry flag we wanted.
9182     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9183                          Op.getOperand(1), Carry);
9184 
9185     // Now convert the carry flag into a boolean value.
9186     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9187     // But the carry returned by ARMISD::SUBE is not a borrow as expected
9188     // by ISD::SUBCARRY, so compute 1 - C.
9189     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9190                         DAG.getConstant(1, DL, MVT::i32), Carry);
9191   }
9192 
9193   // Return both values.
9194   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9195 }
9196 
9197 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9198   assert(Subtarget->isTargetDarwin());
9199 
9200   // For iOS, we want to call an alternative entry point: __sincos_stret,
9201   // return values are passed via sret.
9202   SDLoc dl(Op);
9203   SDValue Arg = Op.getOperand(0);
9204   EVT ArgVT = Arg.getValueType();
9205   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9206   auto PtrVT = getPointerTy(DAG.getDataLayout());
9207 
9208   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9210 
9211   // Pair of floats / doubles used to pass the result.
9212   Type *RetTy = StructType::get(ArgTy, ArgTy);
9213   auto &DL = DAG.getDataLayout();
9214 
9215   ArgListTy Args;
9216   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9217   SDValue SRet;
9218   if (ShouldUseSRet) {
9219     // Create stack object for sret.
9220     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9221     const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9222     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9223     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9224 
9225     ArgListEntry Entry;
9226     Entry.Node = SRet;
9227     Entry.Ty = RetTy->getPointerTo();
9228     Entry.IsSExt = false;
9229     Entry.IsZExt = false;
9230     Entry.IsSRet = true;
9231     Args.push_back(Entry);
9232     RetTy = Type::getVoidTy(*DAG.getContext());
9233   }
9234 
9235   ArgListEntry Entry;
9236   Entry.Node = Arg;
9237   Entry.Ty = ArgTy;
9238   Entry.IsSExt = false;
9239   Entry.IsZExt = false;
9240   Args.push_back(Entry);
9241 
9242   RTLIB::Libcall LC =
9243       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9244   const char *LibcallName = getLibcallName(LC);
9245   CallingConv::ID CC = getLibcallCallingConv(LC);
9246   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9247 
9248   TargetLowering::CallLoweringInfo CLI(DAG);
9249   CLI.setDebugLoc(dl)
9250       .setChain(DAG.getEntryNode())
9251       .setCallee(CC, RetTy, Callee, std::move(Args))
9252       .setDiscardResult(ShouldUseSRet);
9253   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9254 
9255   if (!ShouldUseSRet)
9256     return CallResult.first;
9257 
9258   SDValue LoadSin =
9259       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9260 
9261   // Address of cos field.
9262   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9263                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9264   SDValue LoadCos =
9265       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9266 
9267   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9268   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9269                      LoadSin.getValue(0), LoadCos.getValue(0));
9270 }
9271 
9272 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9273                                                   bool Signed,
9274                                                   SDValue &Chain) const {
9275   EVT VT = Op.getValueType();
9276   assert((VT == MVT::i32 || VT == MVT::i64) &&
9277          "unexpected type for custom lowering DIV");
9278   SDLoc dl(Op);
9279 
9280   const auto &DL = DAG.getDataLayout();
9281   const auto &TLI = DAG.getTargetLoweringInfo();
9282 
9283   const char *Name = nullptr;
9284   if (Signed)
9285     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9286   else
9287     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9288 
9289   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9290 
9291   ARMTargetLowering::ArgListTy Args;
9292 
9293   for (auto AI : {1, 0}) {
9294     ArgListEntry Arg;
9295     Arg.Node = Op.getOperand(AI);
9296     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9297     Args.push_back(Arg);
9298   }
9299 
9300   CallLoweringInfo CLI(DAG);
9301   CLI.setDebugLoc(dl)
9302     .setChain(Chain)
9303     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9304                ES, std::move(Args));
9305 
9306   return LowerCallTo(CLI).first;
9307 }
9308 
9309 // This is a code size optimisation: return the original SDIV node to
9310 // DAGCombiner when we don't want to expand SDIV into a sequence of
9311 // instructions, and an empty node otherwise which will cause the
9312 // SDIV to be expanded in DAGCombine.
9313 SDValue
9314 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9315                                  SelectionDAG &DAG,
9316                                  SmallVectorImpl<SDNode *> &Created) const {
9317   // TODO: Support SREM
9318   if (N->getOpcode() != ISD::SDIV)
9319     return SDValue();
9320 
9321   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9322   const bool MinSize = ST.hasMinSize();
9323   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9324                                       : ST.hasDivideInARMMode();
9325 
9326   // Don't touch vector types; rewriting this may lead to scalarizing
9327   // the int divs.
9328   if (N->getOperand(0).getValueType().isVector())
9329     return SDValue();
9330 
9331   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9332   // hwdiv support for this to be really profitable.
9333   if (!(MinSize && HasDivide))
9334     return SDValue();
9335 
9336   // ARM mode is a bit simpler than Thumb: we can handle large power
9337   // of 2 immediates with 1 mov instruction; no further checks required,
9338   // just return the sdiv node.
9339   if (!ST.isThumb())
9340     return SDValue(N, 0);
9341 
9342   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9343   // and thus lose the code size benefits of a MOVS that requires only 2.
9344   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9345   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9346   if (Divisor.sgt(128))
9347     return SDValue();
9348 
9349   return SDValue(N, 0);
9350 }
9351 
9352 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9353                                             bool Signed) const {
9354   assert(Op.getValueType() == MVT::i32 &&
9355          "unexpected type for custom lowering DIV");
9356   SDLoc dl(Op);
9357 
9358   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9359                                DAG.getEntryNode(), Op.getOperand(1));
9360 
9361   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9362 }
9363 
9364 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9365   SDLoc DL(N);
9366   SDValue Op = N->getOperand(1);
9367   if (N->getValueType(0) == MVT::i32)
9368     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9369   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9370                            DAG.getConstant(0, DL, MVT::i32));
9371   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9372                            DAG.getConstant(1, DL, MVT::i32));
9373   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9374                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9375 }
9376 
9377 void ARMTargetLowering::ExpandDIV_Windows(
9378     SDValue Op, SelectionDAG &DAG, bool Signed,
9379     SmallVectorImpl<SDValue> &Results) const {
9380   const auto &DL = DAG.getDataLayout();
9381   const auto &TLI = DAG.getTargetLoweringInfo();
9382 
9383   assert(Op.getValueType() == MVT::i64 &&
9384          "unexpected type for custom lowering DIV");
9385   SDLoc dl(Op);
9386 
9387   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9388 
9389   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9390 
9391   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9392   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9393                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9394   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9395 
9396   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9397 }
9398 
9399 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9400   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9401   EVT MemVT = LD->getMemoryVT();
9402   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9403          "Expected a predicate type!");
9404   assert(MemVT == Op.getValueType());
9405   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9406          "Expected a non-extending load");
9407   assert(LD->isUnindexed() && "Expected a unindexed load");
9408 
9409   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9410   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9411   // need to make sure that 8/4 bits are actually loaded into the correct
9412   // place, which means loading the value and then shuffling the values into
9413   // the bottom bits of the predicate.
9414   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9415   // for BE).
9416 
9417   SDLoc dl(Op);
9418   SDValue Load = DAG.getExtLoad(
9419       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9420       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9421       LD->getMemOperand());
9422   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9423   if (MemVT != MVT::v16i1)
9424     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9425                        DAG.getConstant(0, dl, MVT::i32));
9426   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9427 }
9428 
9429 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9430                                   SelectionDAG &DAG) const {
9431   LoadSDNode *LD = cast<LoadSDNode>(N);
9432   EVT MemVT = LD->getMemoryVT();
9433   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9434 
9435   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9436       !Subtarget->isThumb1Only() && LD->isVolatile()) {
9437     SDLoc dl(N);
9438     SDValue Result = DAG.getMemIntrinsicNode(
9439         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9440         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9441     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9442     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9443     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9444     Results.append({Pair, Result.getValue(2)});
9445   }
9446 }
9447 
9448 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9449   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9450   EVT MemVT = ST->getMemoryVT();
9451   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9452          "Expected a predicate type!");
9453   assert(MemVT == ST->getValue().getValueType());
9454   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9455   assert(ST->isUnindexed() && "Expected a unindexed store");
9456 
9457   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9458   // unset and a scalar store.
9459   SDLoc dl(Op);
9460   SDValue Build = ST->getValue();
9461   if (MemVT != MVT::v16i1) {
9462     SmallVector<SDValue, 16> Ops;
9463     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9464       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9465                                 DAG.getConstant(I, dl, MVT::i32)));
9466     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9467       Ops.push_back(DAG.getUNDEF(MVT::i32));
9468     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9469   }
9470   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9471   return DAG.getTruncStore(
9472       ST->getChain(), dl, GRP, ST->getBasePtr(),
9473       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9474       ST->getMemOperand());
9475 }
9476 
9477 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9478                           const ARMSubtarget *Subtarget) {
9479   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9480   EVT MemVT = ST->getMemoryVT();
9481   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9482 
9483   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9484       !Subtarget->isThumb1Only() && ST->isVolatile()) {
9485     SDNode *N = Op.getNode();
9486     SDLoc dl(N);
9487 
9488     SDValue Lo = DAG.getNode(
9489         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9490         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9491                               MVT::i32));
9492     SDValue Hi = DAG.getNode(
9493         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9494         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9495                               MVT::i32));
9496 
9497     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9498                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9499                                    MemVT, ST->getMemOperand());
9500   } else if (Subtarget->hasMVEIntegerOps() &&
9501              ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9502                MemVT == MVT::v16i1))) {
9503     return LowerPredicateStore(Op, DAG);
9504   }
9505 
9506   return SDValue();
9507 }
9508 
9509 static bool isZeroVector(SDValue N) {
9510   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9511           (N->getOpcode() == ARMISD::VMOVIMM &&
9512            isNullConstant(N->getOperand(0))));
9513 }
9514 
9515 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9516   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9517   MVT VT = Op.getSimpleValueType();
9518   SDValue Mask = N->getMask();
9519   SDValue PassThru = N->getPassThru();
9520   SDLoc dl(Op);
9521 
9522   if (isZeroVector(PassThru))
9523     return Op;
9524 
9525   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9526   // zero too, and other values are lowered to a select.
9527   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9528                                 DAG.getTargetConstant(0, dl, MVT::i32));
9529   SDValue NewLoad = DAG.getMaskedLoad(
9530       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9531       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9532       N->getExtensionType(), N->isExpandingLoad());
9533   SDValue Combo = NewLoad;
9534   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9535                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9536                             isZeroVector(PassThru->getOperand(0));
9537   if (!PassThru.isUndef() && !PassThruIsCastZero)
9538     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9539   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9540 }
9541 
9542 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
9543                               const ARMSubtarget *ST) {
9544   if (!ST->hasMVEIntegerOps())
9545     return SDValue();
9546 
9547   SDLoc dl(Op);
9548   unsigned BaseOpcode = 0;
9549   switch (Op->getOpcode()) {
9550   default: llvm_unreachable("Expected VECREDUCE opcode");
9551   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
9552   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
9553   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
9554   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
9555   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
9556   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
9557   case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
9558   case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
9559   }
9560 
9561   SDValue Op0 = Op->getOperand(0);
9562   EVT VT = Op0.getValueType();
9563   EVT EltVT = VT.getVectorElementType();
9564   unsigned NumElts = VT.getVectorNumElements();
9565   unsigned NumActiveLanes = NumElts;
9566 
9567   assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
9568           NumActiveLanes == 2) &&
9569          "Only expected a power 2 vector size");
9570 
9571   // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
9572   // allows us to easily extract vector elements from the lanes.
9573   while (NumActiveLanes > 4) {
9574     unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
9575     SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
9576     Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
9577     NumActiveLanes /= 2;
9578   }
9579 
9580   SDValue Res;
9581   if (NumActiveLanes == 4) {
9582     // The remaining 4 elements are summed sequentially
9583     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9584                               DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
9585     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9586                               DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
9587     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9588                               DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
9589     SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9590                               DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
9591     SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9592     SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
9593     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
9594   } else {
9595     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9596                               DAG.getConstant(0, dl, MVT::i32));
9597     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9598                               DAG.getConstant(1, dl, MVT::i32));
9599     Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9600   }
9601 
9602   // Result type may be wider than element type.
9603   if (EltVT != Op->getValueType(0))
9604     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
9605   return Res;
9606 }
9607 
9608 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
9609                                const ARMSubtarget *ST) {
9610   if (!ST->hasMVEFloatOps())
9611     return SDValue();
9612   return LowerVecReduce(Op, DAG, ST);
9613 }
9614 
9615 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9616   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9617     // Acquire/Release load/store is not legal for targets without a dmb or
9618     // equivalent available.
9619     return SDValue();
9620 
9621   // Monotonic load/store is legal for all targets.
9622   return Op;
9623 }
9624 
9625 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9626                                     SmallVectorImpl<SDValue> &Results,
9627                                     SelectionDAG &DAG,
9628                                     const ARMSubtarget *Subtarget) {
9629   SDLoc DL(N);
9630   // Under Power Management extensions, the cycle-count is:
9631   //    mrc p15, #0, <Rt>, c9, c13, #0
9632   SDValue Ops[] = { N->getOperand(0), // Chain
9633                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9634                     DAG.getTargetConstant(15, DL, MVT::i32),
9635                     DAG.getTargetConstant(0, DL, MVT::i32),
9636                     DAG.getTargetConstant(9, DL, MVT::i32),
9637                     DAG.getTargetConstant(13, DL, MVT::i32),
9638                     DAG.getTargetConstant(0, DL, MVT::i32)
9639   };
9640 
9641   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9642                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9643   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9644                                 DAG.getConstant(0, DL, MVT::i32)));
9645   Results.push_back(Cycles32.getValue(1));
9646 }
9647 
9648 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9649   SDLoc dl(V.getNode());
9650   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9651   SDValue VHi = DAG.getAnyExtOrTrunc(
9652       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9653       dl, MVT::i32);
9654   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9655   if (isBigEndian)
9656     std::swap (VLo, VHi);
9657   SDValue RegClass =
9658       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9659   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9660   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9661   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9662   return SDValue(
9663       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9664 }
9665 
9666 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9667                                        SmallVectorImpl<SDValue> & Results,
9668                                        SelectionDAG &DAG) {
9669   assert(N->getValueType(0) == MVT::i64 &&
9670          "AtomicCmpSwap on types less than 64 should be legal");
9671   SDValue Ops[] = {N->getOperand(1),
9672                    createGPRPairNode(DAG, N->getOperand(2)),
9673                    createGPRPairNode(DAG, N->getOperand(3)),
9674                    N->getOperand(0)};
9675   SDNode *CmpSwap = DAG.getMachineNode(
9676       ARM::CMP_SWAP_64, SDLoc(N),
9677       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9678 
9679   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9680   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9681 
9682   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9683 
9684   SDValue Lo =
9685       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9686                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9687   SDValue Hi =
9688       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9689                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9690   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9691   Results.push_back(SDValue(CmpSwap, 2));
9692 }
9693 
9694 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9695   SDLoc dl(Op);
9696   EVT VT = Op.getValueType();
9697   SDValue Chain = Op.getOperand(0);
9698   SDValue LHS = Op.getOperand(1);
9699   SDValue RHS = Op.getOperand(2);
9700   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9701   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9702 
9703   // If we don't have instructions of this float type then soften to a libcall
9704   // and use SETCC instead.
9705   if (isUnsupportedFloatingType(LHS.getValueType())) {
9706     DAG.getTargetLoweringInfo().softenSetCCOperands(
9707       DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9708     if (!RHS.getNode()) {
9709       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9710       CC = ISD::SETNE;
9711     }
9712     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9713                                  DAG.getCondCode(CC));
9714     return DAG.getMergeValues({Result, Chain}, dl);
9715   }
9716 
9717   ARMCC::CondCodes CondCode, CondCode2;
9718   FPCCToARMCC(CC, CondCode, CondCode2);
9719 
9720   // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9721   // in CMPFP and CMPFPE, but instead it should be made explicit by these
9722   // instructions using a chain instead of glue. This would also fix the problem
9723   // here (and also in LowerSELECT_CC) where we generate two comparisons when
9724   // CondCode2 != AL.
9725   SDValue True = DAG.getConstant(1, dl, VT);
9726   SDValue False =  DAG.getConstant(0, dl, VT);
9727   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9728   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9729   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9730   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9731   if (CondCode2 != ARMCC::AL) {
9732     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9733     Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9734     Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9735   }
9736   return DAG.getMergeValues({Result, Chain}, dl);
9737 }
9738 
9739 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9740   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9741   switch (Op.getOpcode()) {
9742   default: llvm_unreachable("Don't know how to custom lower this!");
9743   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9744   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9745   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9746   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9747   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9748   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9749   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9750   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9751   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9752   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9753   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9754   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9755   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9756   case ISD::SINT_TO_FP:
9757   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9758   case ISD::STRICT_FP_TO_SINT:
9759   case ISD::STRICT_FP_TO_UINT:
9760   case ISD::FP_TO_SINT:
9761   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9762   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9763   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9764   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9765   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9766   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9767   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9768   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9769   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9770                                                                Subtarget);
9771   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9772   case ISD::SHL:
9773   case ISD::SRL:
9774   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9775   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9776   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9777   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9778   case ISD::SRL_PARTS:
9779   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9780   case ISD::CTTZ:
9781   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9782   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9783   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9784   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9785   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9786   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9787   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9788   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9789   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9790   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9791   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9792   case ISD::TRUNCATE:      return LowerTruncatei1(Op, DAG, Subtarget);
9793   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9794   case ISD::MUL:           return LowerMUL(Op, DAG);
9795   case ISD::SDIV:
9796     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9797       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9798     return LowerSDIV(Op, DAG, Subtarget);
9799   case ISD::UDIV:
9800     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9801       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9802     return LowerUDIV(Op, DAG, Subtarget);
9803   case ISD::ADDCARRY:
9804   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9805   case ISD::SADDO:
9806   case ISD::SSUBO:
9807     return LowerSignedALUO(Op, DAG);
9808   case ISD::UADDO:
9809   case ISD::USUBO:
9810     return LowerUnsignedALUO(Op, DAG);
9811   case ISD::SADDSAT:
9812   case ISD::SSUBSAT:
9813     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9814   case ISD::LOAD:
9815     return LowerPredicateLoad(Op, DAG);
9816   case ISD::STORE:
9817     return LowerSTORE(Op, DAG, Subtarget);
9818   case ISD::MLOAD:
9819     return LowerMLOAD(Op, DAG);
9820   case ISD::VECREDUCE_MUL:
9821   case ISD::VECREDUCE_AND:
9822   case ISD::VECREDUCE_OR:
9823   case ISD::VECREDUCE_XOR:
9824     return LowerVecReduce(Op, DAG, Subtarget);
9825   case ISD::VECREDUCE_FADD:
9826   case ISD::VECREDUCE_FMUL:
9827   case ISD::VECREDUCE_FMIN:
9828   case ISD::VECREDUCE_FMAX:
9829     return LowerVecReduceF(Op, DAG, Subtarget);
9830   case ISD::ATOMIC_LOAD:
9831   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9832   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9833   case ISD::SDIVREM:
9834   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9835   case ISD::DYNAMIC_STACKALLOC:
9836     if (Subtarget->isTargetWindows())
9837       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9838     llvm_unreachable("Don't know how to custom lower this!");
9839   case ISD::STRICT_FP_ROUND:
9840   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9841   case ISD::STRICT_FP_EXTEND:
9842   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9843   case ISD::STRICT_FSETCC:
9844   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9845   case ARMISD::WIN__DBZCHK: return SDValue();
9846   }
9847 }
9848 
9849 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9850                                  SelectionDAG &DAG) {
9851   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9852   unsigned Opc = 0;
9853   if (IntNo == Intrinsic::arm_smlald)
9854     Opc = ARMISD::SMLALD;
9855   else if (IntNo == Intrinsic::arm_smlaldx)
9856     Opc = ARMISD::SMLALDX;
9857   else if (IntNo == Intrinsic::arm_smlsld)
9858     Opc = ARMISD::SMLSLD;
9859   else if (IntNo == Intrinsic::arm_smlsldx)
9860     Opc = ARMISD::SMLSLDX;
9861   else
9862     return;
9863 
9864   SDLoc dl(N);
9865   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9866                            N->getOperand(3),
9867                            DAG.getConstant(0, dl, MVT::i32));
9868   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9869                            N->getOperand(3),
9870                            DAG.getConstant(1, dl, MVT::i32));
9871 
9872   SDValue LongMul = DAG.getNode(Opc, dl,
9873                                 DAG.getVTList(MVT::i32, MVT::i32),
9874                                 N->getOperand(1), N->getOperand(2),
9875                                 Lo, Hi);
9876   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9877                                 LongMul.getValue(0), LongMul.getValue(1)));
9878 }
9879 
9880 /// ReplaceNodeResults - Replace the results of node with an illegal result
9881 /// type with new values built out of custom code.
9882 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9883                                            SmallVectorImpl<SDValue> &Results,
9884                                            SelectionDAG &DAG) const {
9885   SDValue Res;
9886   switch (N->getOpcode()) {
9887   default:
9888     llvm_unreachable("Don't know how to custom expand this!");
9889   case ISD::READ_REGISTER:
9890     ExpandREAD_REGISTER(N, Results, DAG);
9891     break;
9892   case ISD::BITCAST:
9893     Res = ExpandBITCAST(N, DAG, Subtarget);
9894     break;
9895   case ISD::SRL:
9896   case ISD::SRA:
9897   case ISD::SHL:
9898     Res = Expand64BitShift(N, DAG, Subtarget);
9899     break;
9900   case ISD::SREM:
9901   case ISD::UREM:
9902     Res = LowerREM(N, DAG);
9903     break;
9904   case ISD::SDIVREM:
9905   case ISD::UDIVREM:
9906     Res = LowerDivRem(SDValue(N, 0), DAG);
9907     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9908     Results.push_back(Res.getValue(0));
9909     Results.push_back(Res.getValue(1));
9910     return;
9911   case ISD::SADDSAT:
9912   case ISD::SSUBSAT:
9913     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9914     break;
9915   case ISD::READCYCLECOUNTER:
9916     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9917     return;
9918   case ISD::UDIV:
9919   case ISD::SDIV:
9920     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9921     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9922                              Results);
9923   case ISD::ATOMIC_CMP_SWAP:
9924     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9925     return;
9926   case ISD::INTRINSIC_WO_CHAIN:
9927     return ReplaceLongIntrinsic(N, Results, DAG);
9928   case ISD::ABS:
9929      lowerABS(N, Results, DAG);
9930      return ;
9931   case ISD::LOAD:
9932     LowerLOAD(N, Results, DAG);
9933     break;
9934   }
9935   if (Res.getNode())
9936     Results.push_back(Res);
9937 }
9938 
9939 //===----------------------------------------------------------------------===//
9940 //                           ARM Scheduler Hooks
9941 //===----------------------------------------------------------------------===//
9942 
9943 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9944 /// registers the function context.
9945 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9946                                                MachineBasicBlock *MBB,
9947                                                MachineBasicBlock *DispatchBB,
9948                                                int FI) const {
9949   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9950          "ROPI/RWPI not currently supported with SjLj");
9951   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9952   DebugLoc dl = MI.getDebugLoc();
9953   MachineFunction *MF = MBB->getParent();
9954   MachineRegisterInfo *MRI = &MF->getRegInfo();
9955   MachineConstantPool *MCP = MF->getConstantPool();
9956   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9957   const Function &F = MF->getFunction();
9958 
9959   bool isThumb = Subtarget->isThumb();
9960   bool isThumb2 = Subtarget->isThumb2();
9961 
9962   unsigned PCLabelId = AFI->createPICLabelUId();
9963   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9964   ARMConstantPoolValue *CPV =
9965     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9966   unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
9967 
9968   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9969                                            : &ARM::GPRRegClass;
9970 
9971   // Grab constant pool and fixed stack memory operands.
9972   MachineMemOperand *CPMMO =
9973       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9974                                MachineMemOperand::MOLoad, 4, Align(4));
9975 
9976   MachineMemOperand *FIMMOSt =
9977       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9978                                MachineMemOperand::MOStore, 4, Align(4));
9979 
9980   // Load the address of the dispatch MBB into the jump buffer.
9981   if (isThumb2) {
9982     // Incoming value: jbuf
9983     //   ldr.n  r5, LCPI1_1
9984     //   orr    r5, r5, #1
9985     //   add    r5, pc
9986     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9987     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9988     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9989         .addConstantPoolIndex(CPI)
9990         .addMemOperand(CPMMO)
9991         .add(predOps(ARMCC::AL));
9992     // Set the low bit because of thumb mode.
9993     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9994     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9995         .addReg(NewVReg1, RegState::Kill)
9996         .addImm(0x01)
9997         .add(predOps(ARMCC::AL))
9998         .add(condCodeOp());
9999     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10000     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10001       .addReg(NewVReg2, RegState::Kill)
10002       .addImm(PCLabelId);
10003     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10004         .addReg(NewVReg3, RegState::Kill)
10005         .addFrameIndex(FI)
10006         .addImm(36) // &jbuf[1] :: pc
10007         .addMemOperand(FIMMOSt)
10008         .add(predOps(ARMCC::AL));
10009   } else if (isThumb) {
10010     // Incoming value: jbuf
10011     //   ldr.n  r1, LCPI1_4
10012     //   add    r1, pc
10013     //   mov    r2, #1
10014     //   orrs   r1, r2
10015     //   add    r2, $jbuf, #+4 ; &jbuf[1]
10016     //   str    r1, [r2]
10017     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10018     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10019         .addConstantPoolIndex(CPI)
10020         .addMemOperand(CPMMO)
10021         .add(predOps(ARMCC::AL));
10022     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10023     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10024       .addReg(NewVReg1, RegState::Kill)
10025       .addImm(PCLabelId);
10026     // Set the low bit because of thumb mode.
10027     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10028     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10029         .addReg(ARM::CPSR, RegState::Define)
10030         .addImm(1)
10031         .add(predOps(ARMCC::AL));
10032     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10033     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10034         .addReg(ARM::CPSR, RegState::Define)
10035         .addReg(NewVReg2, RegState::Kill)
10036         .addReg(NewVReg3, RegState::Kill)
10037         .add(predOps(ARMCC::AL));
10038     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10039     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10040             .addFrameIndex(FI)
10041             .addImm(36); // &jbuf[1] :: pc
10042     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10043         .addReg(NewVReg4, RegState::Kill)
10044         .addReg(NewVReg5, RegState::Kill)
10045         .addImm(0)
10046         .addMemOperand(FIMMOSt)
10047         .add(predOps(ARMCC::AL));
10048   } else {
10049     // Incoming value: jbuf
10050     //   ldr  r1, LCPI1_1
10051     //   add  r1, pc, r1
10052     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
10053     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10054     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10055         .addConstantPoolIndex(CPI)
10056         .addImm(0)
10057         .addMemOperand(CPMMO)
10058         .add(predOps(ARMCC::AL));
10059     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10060     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10061         .addReg(NewVReg1, RegState::Kill)
10062         .addImm(PCLabelId)
10063         .add(predOps(ARMCC::AL));
10064     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10065         .addReg(NewVReg2, RegState::Kill)
10066         .addFrameIndex(FI)
10067         .addImm(36) // &jbuf[1] :: pc
10068         .addMemOperand(FIMMOSt)
10069         .add(predOps(ARMCC::AL));
10070   }
10071 }
10072 
10073 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10074                                               MachineBasicBlock *MBB) const {
10075   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10076   DebugLoc dl = MI.getDebugLoc();
10077   MachineFunction *MF = MBB->getParent();
10078   MachineRegisterInfo *MRI = &MF->getRegInfo();
10079   MachineFrameInfo &MFI = MF->getFrameInfo();
10080   int FI = MFI.getFunctionContextIndex();
10081 
10082   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10083                                                         : &ARM::GPRnopcRegClass;
10084 
10085   // Get a mapping of the call site numbers to all of the landing pads they're
10086   // associated with.
10087   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10088   unsigned MaxCSNum = 0;
10089   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
10090        ++BB) {
10091     if (!BB->isEHPad()) continue;
10092 
10093     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10094     // pad.
10095     for (MachineBasicBlock::iterator
10096            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
10097       if (!II->isEHLabel()) continue;
10098 
10099       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
10100       if (!MF->hasCallSiteLandingPad(Sym)) continue;
10101 
10102       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10103       for (SmallVectorImpl<unsigned>::iterator
10104              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
10105            CSI != CSE; ++CSI) {
10106         CallSiteNumToLPad[*CSI].push_back(&*BB);
10107         MaxCSNum = std::max(MaxCSNum, *CSI);
10108       }
10109       break;
10110     }
10111   }
10112 
10113   // Get an ordered list of the machine basic blocks for the jump table.
10114   std::vector<MachineBasicBlock*> LPadList;
10115   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10116   LPadList.reserve(CallSiteNumToLPad.size());
10117   for (unsigned I = 1; I <= MaxCSNum; ++I) {
10118     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10119     for (SmallVectorImpl<MachineBasicBlock*>::iterator
10120            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
10121       LPadList.push_back(*II);
10122       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
10123     }
10124   }
10125 
10126   assert(!LPadList.empty() &&
10127          "No landing pad destinations for the dispatch jump table!");
10128 
10129   // Create the jump table and associated information.
10130   MachineJumpTableInfo *JTI =
10131     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10132   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10133 
10134   // Create the MBBs for the dispatch code.
10135 
10136   // Shove the dispatch's address into the return slot in the function context.
10137   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10138   DispatchBB->setIsEHPad();
10139 
10140   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10141   unsigned trap_opcode;
10142   if (Subtarget->isThumb())
10143     trap_opcode = ARM::tTRAP;
10144   else
10145     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10146 
10147   BuildMI(TrapBB, dl, TII->get(trap_opcode));
10148   DispatchBB->addSuccessor(TrapBB);
10149 
10150   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10151   DispatchBB->addSuccessor(DispContBB);
10152 
10153   // Insert and MBBs.
10154   MF->insert(MF->end(), DispatchBB);
10155   MF->insert(MF->end(), DispContBB);
10156   MF->insert(MF->end(), TrapBB);
10157 
10158   // Insert code into the entry block that creates and registers the function
10159   // context.
10160   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10161 
10162   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10163       MachinePointerInfo::getFixedStack(*MF, FI),
10164       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10165 
10166   MachineInstrBuilder MIB;
10167   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10168 
10169   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10170   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10171 
10172   // Add a register mask with no preserved registers.  This results in all
10173   // registers being marked as clobbered. This can't work if the dispatch block
10174   // is in a Thumb1 function and is linked with ARM code which uses the FP
10175   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10176   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10177 
10178   bool IsPositionIndependent = isPositionIndependent();
10179   unsigned NumLPads = LPadList.size();
10180   if (Subtarget->isThumb2()) {
10181     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10182     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10183         .addFrameIndex(FI)
10184         .addImm(4)
10185         .addMemOperand(FIMMOLd)
10186         .add(predOps(ARMCC::AL));
10187 
10188     if (NumLPads < 256) {
10189       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10190           .addReg(NewVReg1)
10191           .addImm(LPadList.size())
10192           .add(predOps(ARMCC::AL));
10193     } else {
10194       Register VReg1 = MRI->createVirtualRegister(TRC);
10195       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10196           .addImm(NumLPads & 0xFFFF)
10197           .add(predOps(ARMCC::AL));
10198 
10199       unsigned VReg2 = VReg1;
10200       if ((NumLPads & 0xFFFF0000) != 0) {
10201         VReg2 = MRI->createVirtualRegister(TRC);
10202         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10203             .addReg(VReg1)
10204             .addImm(NumLPads >> 16)
10205             .add(predOps(ARMCC::AL));
10206       }
10207 
10208       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10209           .addReg(NewVReg1)
10210           .addReg(VReg2)
10211           .add(predOps(ARMCC::AL));
10212     }
10213 
10214     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10215       .addMBB(TrapBB)
10216       .addImm(ARMCC::HI)
10217       .addReg(ARM::CPSR);
10218 
10219     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10220     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10221         .addJumpTableIndex(MJTI)
10222         .add(predOps(ARMCC::AL));
10223 
10224     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10225     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10226         .addReg(NewVReg3, RegState::Kill)
10227         .addReg(NewVReg1)
10228         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10229         .add(predOps(ARMCC::AL))
10230         .add(condCodeOp());
10231 
10232     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10233       .addReg(NewVReg4, RegState::Kill)
10234       .addReg(NewVReg1)
10235       .addJumpTableIndex(MJTI);
10236   } else if (Subtarget->isThumb()) {
10237     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10238     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10239         .addFrameIndex(FI)
10240         .addImm(1)
10241         .addMemOperand(FIMMOLd)
10242         .add(predOps(ARMCC::AL));
10243 
10244     if (NumLPads < 256) {
10245       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10246           .addReg(NewVReg1)
10247           .addImm(NumLPads)
10248           .add(predOps(ARMCC::AL));
10249     } else {
10250       MachineConstantPool *ConstantPool = MF->getConstantPool();
10251       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10252       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10253 
10254       // MachineConstantPool wants an explicit alignment.
10255       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10256       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10257 
10258       Register VReg1 = MRI->createVirtualRegister(TRC);
10259       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10260           .addReg(VReg1, RegState::Define)
10261           .addConstantPoolIndex(Idx)
10262           .add(predOps(ARMCC::AL));
10263       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10264           .addReg(NewVReg1)
10265           .addReg(VReg1)
10266           .add(predOps(ARMCC::AL));
10267     }
10268 
10269     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10270       .addMBB(TrapBB)
10271       .addImm(ARMCC::HI)
10272       .addReg(ARM::CPSR);
10273 
10274     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10275     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10276         .addReg(ARM::CPSR, RegState::Define)
10277         .addReg(NewVReg1)
10278         .addImm(2)
10279         .add(predOps(ARMCC::AL));
10280 
10281     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10282     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10283         .addJumpTableIndex(MJTI)
10284         .add(predOps(ARMCC::AL));
10285 
10286     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10287     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10288         .addReg(ARM::CPSR, RegState::Define)
10289         .addReg(NewVReg2, RegState::Kill)
10290         .addReg(NewVReg3)
10291         .add(predOps(ARMCC::AL));
10292 
10293     MachineMemOperand *JTMMOLd =
10294         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10295                                  MachineMemOperand::MOLoad, 4, Align(4));
10296 
10297     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10298     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10299         .addReg(NewVReg4, RegState::Kill)
10300         .addImm(0)
10301         .addMemOperand(JTMMOLd)
10302         .add(predOps(ARMCC::AL));
10303 
10304     unsigned NewVReg6 = NewVReg5;
10305     if (IsPositionIndependent) {
10306       NewVReg6 = MRI->createVirtualRegister(TRC);
10307       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10308           .addReg(ARM::CPSR, RegState::Define)
10309           .addReg(NewVReg5, RegState::Kill)
10310           .addReg(NewVReg3)
10311           .add(predOps(ARMCC::AL));
10312     }
10313 
10314     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10315       .addReg(NewVReg6, RegState::Kill)
10316       .addJumpTableIndex(MJTI);
10317   } else {
10318     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10319     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10320         .addFrameIndex(FI)
10321         .addImm(4)
10322         .addMemOperand(FIMMOLd)
10323         .add(predOps(ARMCC::AL));
10324 
10325     if (NumLPads < 256) {
10326       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10327           .addReg(NewVReg1)
10328           .addImm(NumLPads)
10329           .add(predOps(ARMCC::AL));
10330     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10331       Register VReg1 = MRI->createVirtualRegister(TRC);
10332       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10333           .addImm(NumLPads & 0xFFFF)
10334           .add(predOps(ARMCC::AL));
10335 
10336       unsigned VReg2 = VReg1;
10337       if ((NumLPads & 0xFFFF0000) != 0) {
10338         VReg2 = MRI->createVirtualRegister(TRC);
10339         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10340             .addReg(VReg1)
10341             .addImm(NumLPads >> 16)
10342             .add(predOps(ARMCC::AL));
10343       }
10344 
10345       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10346           .addReg(NewVReg1)
10347           .addReg(VReg2)
10348           .add(predOps(ARMCC::AL));
10349     } else {
10350       MachineConstantPool *ConstantPool = MF->getConstantPool();
10351       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10352       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10353 
10354       // MachineConstantPool wants an explicit alignment.
10355       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10356       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10357 
10358       Register VReg1 = MRI->createVirtualRegister(TRC);
10359       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10360           .addReg(VReg1, RegState::Define)
10361           .addConstantPoolIndex(Idx)
10362           .addImm(0)
10363           .add(predOps(ARMCC::AL));
10364       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10365           .addReg(NewVReg1)
10366           .addReg(VReg1, RegState::Kill)
10367           .add(predOps(ARMCC::AL));
10368     }
10369 
10370     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10371       .addMBB(TrapBB)
10372       .addImm(ARMCC::HI)
10373       .addReg(ARM::CPSR);
10374 
10375     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10376     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10377         .addReg(NewVReg1)
10378         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10379         .add(predOps(ARMCC::AL))
10380         .add(condCodeOp());
10381     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10382     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10383         .addJumpTableIndex(MJTI)
10384         .add(predOps(ARMCC::AL));
10385 
10386     MachineMemOperand *JTMMOLd =
10387         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10388                                  MachineMemOperand::MOLoad, 4, Align(4));
10389     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10390     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10391         .addReg(NewVReg3, RegState::Kill)
10392         .addReg(NewVReg4)
10393         .addImm(0)
10394         .addMemOperand(JTMMOLd)
10395         .add(predOps(ARMCC::AL));
10396 
10397     if (IsPositionIndependent) {
10398       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10399         .addReg(NewVReg5, RegState::Kill)
10400         .addReg(NewVReg4)
10401         .addJumpTableIndex(MJTI);
10402     } else {
10403       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10404         .addReg(NewVReg5, RegState::Kill)
10405         .addJumpTableIndex(MJTI);
10406     }
10407   }
10408 
10409   // Add the jump table entries as successors to the MBB.
10410   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10411   for (std::vector<MachineBasicBlock*>::iterator
10412          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10413     MachineBasicBlock *CurMBB = *I;
10414     if (SeenMBBs.insert(CurMBB).second)
10415       DispContBB->addSuccessor(CurMBB);
10416   }
10417 
10418   // N.B. the order the invoke BBs are processed in doesn't matter here.
10419   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10420   SmallVector<MachineBasicBlock*, 64> MBBLPads;
10421   for (MachineBasicBlock *BB : InvokeBBs) {
10422 
10423     // Remove the landing pad successor from the invoke block and replace it
10424     // with the new dispatch block.
10425     SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
10426     while (!Successors.empty()) {
10427       MachineBasicBlock *SMBB = Successors.pop_back_val();
10428       if (SMBB->isEHPad()) {
10429         BB->removeSuccessor(SMBB);
10430         MBBLPads.push_back(SMBB);
10431       }
10432     }
10433 
10434     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10435     BB->normalizeSuccProbs();
10436 
10437     // Find the invoke call and mark all of the callee-saved registers as
10438     // 'implicit defined' so that they're spilled. This prevents code from
10439     // moving instructions to before the EH block, where they will never be
10440     // executed.
10441     for (MachineBasicBlock::reverse_iterator
10442            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10443       if (!II->isCall()) continue;
10444 
10445       DenseMap<unsigned, bool> DefRegs;
10446       for (MachineInstr::mop_iterator
10447              OI = II->operands_begin(), OE = II->operands_end();
10448            OI != OE; ++OI) {
10449         if (!OI->isReg()) continue;
10450         DefRegs[OI->getReg()] = true;
10451       }
10452 
10453       MachineInstrBuilder MIB(*MF, &*II);
10454 
10455       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10456         unsigned Reg = SavedRegs[i];
10457         if (Subtarget->isThumb2() &&
10458             !ARM::tGPRRegClass.contains(Reg) &&
10459             !ARM::hGPRRegClass.contains(Reg))
10460           continue;
10461         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10462           continue;
10463         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10464           continue;
10465         if (!DefRegs[Reg])
10466           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10467       }
10468 
10469       break;
10470     }
10471   }
10472 
10473   // Mark all former landing pads as non-landing pads. The dispatch is the only
10474   // landing pad now.
10475   for (SmallVectorImpl<MachineBasicBlock*>::iterator
10476          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10477     (*I)->setIsEHPad(false);
10478 
10479   // The instruction is gone now.
10480   MI.eraseFromParent();
10481 }
10482 
10483 static
10484 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10485   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10486        E = MBB->succ_end(); I != E; ++I)
10487     if (*I != Succ)
10488       return *I;
10489   llvm_unreachable("Expecting a BB with two successors!");
10490 }
10491 
10492 /// Return the load opcode for a given load size. If load size >= 8,
10493 /// neon opcode will be returned.
10494 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10495   if (LdSize >= 8)
10496     return LdSize == 16 ? ARM::VLD1q32wb_fixed
10497                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10498   if (IsThumb1)
10499     return LdSize == 4 ? ARM::tLDRi
10500                        : LdSize == 2 ? ARM::tLDRHi
10501                                      : LdSize == 1 ? ARM::tLDRBi : 0;
10502   if (IsThumb2)
10503     return LdSize == 4 ? ARM::t2LDR_POST
10504                        : LdSize == 2 ? ARM::t2LDRH_POST
10505                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10506   return LdSize == 4 ? ARM::LDR_POST_IMM
10507                      : LdSize == 2 ? ARM::LDRH_POST
10508                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10509 }
10510 
10511 /// Return the store opcode for a given store size. If store size >= 8,
10512 /// neon opcode will be returned.
10513 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10514   if (StSize >= 8)
10515     return StSize == 16 ? ARM::VST1q32wb_fixed
10516                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10517   if (IsThumb1)
10518     return StSize == 4 ? ARM::tSTRi
10519                        : StSize == 2 ? ARM::tSTRHi
10520                                      : StSize == 1 ? ARM::tSTRBi : 0;
10521   if (IsThumb2)
10522     return StSize == 4 ? ARM::t2STR_POST
10523                        : StSize == 2 ? ARM::t2STRH_POST
10524                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
10525   return StSize == 4 ? ARM::STR_POST_IMM
10526                      : StSize == 2 ? ARM::STRH_POST
10527                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10528 }
10529 
10530 /// Emit a post-increment load operation with given size. The instructions
10531 /// will be added to BB at Pos.
10532 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10533                        const TargetInstrInfo *TII, const DebugLoc &dl,
10534                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10535                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10536   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10537   assert(LdOpc != 0 && "Should have a load opcode");
10538   if (LdSize >= 8) {
10539     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10540         .addReg(AddrOut, RegState::Define)
10541         .addReg(AddrIn)
10542         .addImm(0)
10543         .add(predOps(ARMCC::AL));
10544   } else if (IsThumb1) {
10545     // load + update AddrIn
10546     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10547         .addReg(AddrIn)
10548         .addImm(0)
10549         .add(predOps(ARMCC::AL));
10550     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10551         .add(t1CondCodeOp())
10552         .addReg(AddrIn)
10553         .addImm(LdSize)
10554         .add(predOps(ARMCC::AL));
10555   } else if (IsThumb2) {
10556     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10557         .addReg(AddrOut, RegState::Define)
10558         .addReg(AddrIn)
10559         .addImm(LdSize)
10560         .add(predOps(ARMCC::AL));
10561   } else { // arm
10562     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10563         .addReg(AddrOut, RegState::Define)
10564         .addReg(AddrIn)
10565         .addReg(0)
10566         .addImm(LdSize)
10567         .add(predOps(ARMCC::AL));
10568   }
10569 }
10570 
10571 /// Emit a post-increment store operation with given size. The instructions
10572 /// will be added to BB at Pos.
10573 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10574                        const TargetInstrInfo *TII, const DebugLoc &dl,
10575                        unsigned StSize, unsigned Data, unsigned AddrIn,
10576                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10577   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10578   assert(StOpc != 0 && "Should have a store opcode");
10579   if (StSize >= 8) {
10580     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10581         .addReg(AddrIn)
10582         .addImm(0)
10583         .addReg(Data)
10584         .add(predOps(ARMCC::AL));
10585   } else if (IsThumb1) {
10586     // store + update AddrIn
10587     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10588         .addReg(Data)
10589         .addReg(AddrIn)
10590         .addImm(0)
10591         .add(predOps(ARMCC::AL));
10592     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10593         .add(t1CondCodeOp())
10594         .addReg(AddrIn)
10595         .addImm(StSize)
10596         .add(predOps(ARMCC::AL));
10597   } else if (IsThumb2) {
10598     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10599         .addReg(Data)
10600         .addReg(AddrIn)
10601         .addImm(StSize)
10602         .add(predOps(ARMCC::AL));
10603   } else { // arm
10604     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10605         .addReg(Data)
10606         .addReg(AddrIn)
10607         .addReg(0)
10608         .addImm(StSize)
10609         .add(predOps(ARMCC::AL));
10610   }
10611 }
10612 
10613 MachineBasicBlock *
10614 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10615                                    MachineBasicBlock *BB) const {
10616   // This pseudo instruction has 3 operands: dst, src, size
10617   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10618   // Otherwise, we will generate unrolled scalar copies.
10619   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10620   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10621   MachineFunction::iterator It = ++BB->getIterator();
10622 
10623   Register dest = MI.getOperand(0).getReg();
10624   Register src = MI.getOperand(1).getReg();
10625   unsigned SizeVal = MI.getOperand(2).getImm();
10626   unsigned Alignment = MI.getOperand(3).getImm();
10627   DebugLoc dl = MI.getDebugLoc();
10628 
10629   MachineFunction *MF = BB->getParent();
10630   MachineRegisterInfo &MRI = MF->getRegInfo();
10631   unsigned UnitSize = 0;
10632   const TargetRegisterClass *TRC = nullptr;
10633   const TargetRegisterClass *VecTRC = nullptr;
10634 
10635   bool IsThumb1 = Subtarget->isThumb1Only();
10636   bool IsThumb2 = Subtarget->isThumb2();
10637   bool IsThumb = Subtarget->isThumb();
10638 
10639   if (Alignment & 1) {
10640     UnitSize = 1;
10641   } else if (Alignment & 2) {
10642     UnitSize = 2;
10643   } else {
10644     // Check whether we can use NEON instructions.
10645     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10646         Subtarget->hasNEON()) {
10647       if ((Alignment % 16 == 0) && SizeVal >= 16)
10648         UnitSize = 16;
10649       else if ((Alignment % 8 == 0) && SizeVal >= 8)
10650         UnitSize = 8;
10651     }
10652     // Can't use NEON instructions.
10653     if (UnitSize == 0)
10654       UnitSize = 4;
10655   }
10656 
10657   // Select the correct opcode and register class for unit size load/store
10658   bool IsNeon = UnitSize >= 8;
10659   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10660   if (IsNeon)
10661     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10662                             : UnitSize == 8 ? &ARM::DPRRegClass
10663                                             : nullptr;
10664 
10665   unsigned BytesLeft = SizeVal % UnitSize;
10666   unsigned LoopSize = SizeVal - BytesLeft;
10667 
10668   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10669     // Use LDR and STR to copy.
10670     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10671     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10672     unsigned srcIn = src;
10673     unsigned destIn = dest;
10674     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10675       Register srcOut = MRI.createVirtualRegister(TRC);
10676       Register destOut = MRI.createVirtualRegister(TRC);
10677       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10678       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10679                  IsThumb1, IsThumb2);
10680       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10681                  IsThumb1, IsThumb2);
10682       srcIn = srcOut;
10683       destIn = destOut;
10684     }
10685 
10686     // Handle the leftover bytes with LDRB and STRB.
10687     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10688     // [destOut] = STRB_POST(scratch, destIn, 1)
10689     for (unsigned i = 0; i < BytesLeft; i++) {
10690       Register srcOut = MRI.createVirtualRegister(TRC);
10691       Register destOut = MRI.createVirtualRegister(TRC);
10692       Register scratch = MRI.createVirtualRegister(TRC);
10693       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10694                  IsThumb1, IsThumb2);
10695       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10696                  IsThumb1, IsThumb2);
10697       srcIn = srcOut;
10698       destIn = destOut;
10699     }
10700     MI.eraseFromParent(); // The instruction is gone now.
10701     return BB;
10702   }
10703 
10704   // Expand the pseudo op to a loop.
10705   // thisMBB:
10706   //   ...
10707   //   movw varEnd, # --> with thumb2
10708   //   movt varEnd, #
10709   //   ldrcp varEnd, idx --> without thumb2
10710   //   fallthrough --> loopMBB
10711   // loopMBB:
10712   //   PHI varPhi, varEnd, varLoop
10713   //   PHI srcPhi, src, srcLoop
10714   //   PHI destPhi, dst, destLoop
10715   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10716   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10717   //   subs varLoop, varPhi, #UnitSize
10718   //   bne loopMBB
10719   //   fallthrough --> exitMBB
10720   // exitMBB:
10721   //   epilogue to handle left-over bytes
10722   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10723   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10724   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10725   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10726   MF->insert(It, loopMBB);
10727   MF->insert(It, exitMBB);
10728 
10729   // Transfer the remainder of BB and its successor edges to exitMBB.
10730   exitMBB->splice(exitMBB->begin(), BB,
10731                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10732   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10733 
10734   // Load an immediate to varEnd.
10735   Register varEnd = MRI.createVirtualRegister(TRC);
10736   if (Subtarget->useMovt()) {
10737     unsigned Vtmp = varEnd;
10738     if ((LoopSize & 0xFFFF0000) != 0)
10739       Vtmp = MRI.createVirtualRegister(TRC);
10740     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10741         .addImm(LoopSize & 0xFFFF)
10742         .add(predOps(ARMCC::AL));
10743 
10744     if ((LoopSize & 0xFFFF0000) != 0)
10745       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10746           .addReg(Vtmp)
10747           .addImm(LoopSize >> 16)
10748           .add(predOps(ARMCC::AL));
10749   } else {
10750     MachineConstantPool *ConstantPool = MF->getConstantPool();
10751     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10752     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10753 
10754     // MachineConstantPool wants an explicit alignment.
10755     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10756     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10757     MachineMemOperand *CPMMO =
10758         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10759                                  MachineMemOperand::MOLoad, 4, Align(4));
10760 
10761     if (IsThumb)
10762       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10763           .addReg(varEnd, RegState::Define)
10764           .addConstantPoolIndex(Idx)
10765           .add(predOps(ARMCC::AL))
10766           .addMemOperand(CPMMO);
10767     else
10768       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10769           .addReg(varEnd, RegState::Define)
10770           .addConstantPoolIndex(Idx)
10771           .addImm(0)
10772           .add(predOps(ARMCC::AL))
10773           .addMemOperand(CPMMO);
10774   }
10775   BB->addSuccessor(loopMBB);
10776 
10777   // Generate the loop body:
10778   //   varPhi = PHI(varLoop, varEnd)
10779   //   srcPhi = PHI(srcLoop, src)
10780   //   destPhi = PHI(destLoop, dst)
10781   MachineBasicBlock *entryBB = BB;
10782   BB = loopMBB;
10783   Register varLoop = MRI.createVirtualRegister(TRC);
10784   Register varPhi = MRI.createVirtualRegister(TRC);
10785   Register srcLoop = MRI.createVirtualRegister(TRC);
10786   Register srcPhi = MRI.createVirtualRegister(TRC);
10787   Register destLoop = MRI.createVirtualRegister(TRC);
10788   Register destPhi = MRI.createVirtualRegister(TRC);
10789 
10790   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10791     .addReg(varLoop).addMBB(loopMBB)
10792     .addReg(varEnd).addMBB(entryBB);
10793   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10794     .addReg(srcLoop).addMBB(loopMBB)
10795     .addReg(src).addMBB(entryBB);
10796   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10797     .addReg(destLoop).addMBB(loopMBB)
10798     .addReg(dest).addMBB(entryBB);
10799 
10800   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10801   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10802   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10803   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10804              IsThumb1, IsThumb2);
10805   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10806              IsThumb1, IsThumb2);
10807 
10808   // Decrement loop variable by UnitSize.
10809   if (IsThumb1) {
10810     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10811         .add(t1CondCodeOp())
10812         .addReg(varPhi)
10813         .addImm(UnitSize)
10814         .add(predOps(ARMCC::AL));
10815   } else {
10816     MachineInstrBuilder MIB =
10817         BuildMI(*BB, BB->end(), dl,
10818                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10819     MIB.addReg(varPhi)
10820         .addImm(UnitSize)
10821         .add(predOps(ARMCC::AL))
10822         .add(condCodeOp());
10823     MIB->getOperand(5).setReg(ARM::CPSR);
10824     MIB->getOperand(5).setIsDef(true);
10825   }
10826   BuildMI(*BB, BB->end(), dl,
10827           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10828       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10829 
10830   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10831   BB->addSuccessor(loopMBB);
10832   BB->addSuccessor(exitMBB);
10833 
10834   // Add epilogue to handle BytesLeft.
10835   BB = exitMBB;
10836   auto StartOfExit = exitMBB->begin();
10837 
10838   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10839   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10840   unsigned srcIn = srcLoop;
10841   unsigned destIn = destLoop;
10842   for (unsigned i = 0; i < BytesLeft; i++) {
10843     Register srcOut = MRI.createVirtualRegister(TRC);
10844     Register destOut = MRI.createVirtualRegister(TRC);
10845     Register scratch = MRI.createVirtualRegister(TRC);
10846     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10847                IsThumb1, IsThumb2);
10848     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10849                IsThumb1, IsThumb2);
10850     srcIn = srcOut;
10851     destIn = destOut;
10852   }
10853 
10854   MI.eraseFromParent(); // The instruction is gone now.
10855   return BB;
10856 }
10857 
10858 MachineBasicBlock *
10859 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10860                                        MachineBasicBlock *MBB) const {
10861   const TargetMachine &TM = getTargetMachine();
10862   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10863   DebugLoc DL = MI.getDebugLoc();
10864 
10865   assert(Subtarget->isTargetWindows() &&
10866          "__chkstk is only supported on Windows");
10867   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10868 
10869   // __chkstk takes the number of words to allocate on the stack in R4, and
10870   // returns the stack adjustment in number of bytes in R4.  This will not
10871   // clober any other registers (other than the obvious lr).
10872   //
10873   // Although, technically, IP should be considered a register which may be
10874   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10875   // thumb-2 environment, so there is no interworking required.  As a result, we
10876   // do not expect a veneer to be emitted by the linker, clobbering IP.
10877   //
10878   // Each module receives its own copy of __chkstk, so no import thunk is
10879   // required, again, ensuring that IP is not clobbered.
10880   //
10881   // Finally, although some linkers may theoretically provide a trampoline for
10882   // out of range calls (which is quite common due to a 32M range limitation of
10883   // branches for Thumb), we can generate the long-call version via
10884   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10885   // IP.
10886 
10887   switch (TM.getCodeModel()) {
10888   case CodeModel::Tiny:
10889     llvm_unreachable("Tiny code model not available on ARM.");
10890   case CodeModel::Small:
10891   case CodeModel::Medium:
10892   case CodeModel::Kernel:
10893     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10894         .add(predOps(ARMCC::AL))
10895         .addExternalSymbol("__chkstk")
10896         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10897         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10898         .addReg(ARM::R12,
10899                 RegState::Implicit | RegState::Define | RegState::Dead)
10900         .addReg(ARM::CPSR,
10901                 RegState::Implicit | RegState::Define | RegState::Dead);
10902     break;
10903   case CodeModel::Large: {
10904     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10905     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10906 
10907     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10908       .addExternalSymbol("__chkstk");
10909     BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent())))
10910         .add(predOps(ARMCC::AL))
10911         .addReg(Reg, RegState::Kill)
10912         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10913         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10914         .addReg(ARM::R12,
10915                 RegState::Implicit | RegState::Define | RegState::Dead)
10916         .addReg(ARM::CPSR,
10917                 RegState::Implicit | RegState::Define | RegState::Dead);
10918     break;
10919   }
10920   }
10921 
10922   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10923       .addReg(ARM::SP, RegState::Kill)
10924       .addReg(ARM::R4, RegState::Kill)
10925       .setMIFlags(MachineInstr::FrameSetup)
10926       .add(predOps(ARMCC::AL))
10927       .add(condCodeOp());
10928 
10929   MI.eraseFromParent();
10930   return MBB;
10931 }
10932 
10933 MachineBasicBlock *
10934 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10935                                        MachineBasicBlock *MBB) const {
10936   DebugLoc DL = MI.getDebugLoc();
10937   MachineFunction *MF = MBB->getParent();
10938   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10939 
10940   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10941   MF->insert(++MBB->getIterator(), ContBB);
10942   ContBB->splice(ContBB->begin(), MBB,
10943                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10944   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10945   MBB->addSuccessor(ContBB);
10946 
10947   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10948   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10949   MF->push_back(TrapBB);
10950   MBB->addSuccessor(TrapBB);
10951 
10952   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10953       .addReg(MI.getOperand(0).getReg())
10954       .addImm(0)
10955       .add(predOps(ARMCC::AL));
10956   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10957       .addMBB(TrapBB)
10958       .addImm(ARMCC::EQ)
10959       .addReg(ARM::CPSR);
10960 
10961   MI.eraseFromParent();
10962   return ContBB;
10963 }
10964 
10965 // The CPSR operand of SelectItr might be missing a kill marker
10966 // because there were multiple uses of CPSR, and ISel didn't know
10967 // which to mark. Figure out whether SelectItr should have had a
10968 // kill marker, and set it if it should. Returns the correct kill
10969 // marker value.
10970 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10971                                    MachineBasicBlock* BB,
10972                                    const TargetRegisterInfo* TRI) {
10973   // Scan forward through BB for a use/def of CPSR.
10974   MachineBasicBlock::iterator miI(std::next(SelectItr));
10975   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10976     const MachineInstr& mi = *miI;
10977     if (mi.readsRegister(ARM::CPSR))
10978       return false;
10979     if (mi.definesRegister(ARM::CPSR))
10980       break; // Should have kill-flag - update below.
10981   }
10982 
10983   // If we hit the end of the block, check whether CPSR is live into a
10984   // successor.
10985   if (miI == BB->end()) {
10986     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10987                                           sEnd = BB->succ_end();
10988          sItr != sEnd; ++sItr) {
10989       MachineBasicBlock* succ = *sItr;
10990       if (succ->isLiveIn(ARM::CPSR))
10991         return false;
10992     }
10993   }
10994 
10995   // We found a def, or hit the end of the basic block and CPSR wasn't live
10996   // out. SelectMI should have a kill flag on CPSR.
10997   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10998   return true;
10999 }
11000 
11001 MachineBasicBlock *
11002 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11003                                                MachineBasicBlock *BB) const {
11004   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11005   DebugLoc dl = MI.getDebugLoc();
11006   bool isThumb2 = Subtarget->isThumb2();
11007   switch (MI.getOpcode()) {
11008   default: {
11009     MI.print(errs());
11010     llvm_unreachable("Unexpected instr type to insert");
11011   }
11012 
11013   // Thumb1 post-indexed loads are really just single-register LDMs.
11014   case ARM::tLDR_postidx: {
11015     MachineOperand Def(MI.getOperand(1));
11016     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11017         .add(Def)  // Rn_wb
11018         .add(MI.getOperand(2))  // Rn
11019         .add(MI.getOperand(3))  // PredImm
11020         .add(MI.getOperand(4))  // PredReg
11021         .add(MI.getOperand(0))  // Rt
11022         .cloneMemRefs(MI);
11023     MI.eraseFromParent();
11024     return BB;
11025   }
11026 
11027   // The Thumb2 pre-indexed stores have the same MI operands, they just
11028   // define them differently in the .td files from the isel patterns, so
11029   // they need pseudos.
11030   case ARM::t2STR_preidx:
11031     MI.setDesc(TII->get(ARM::t2STR_PRE));
11032     return BB;
11033   case ARM::t2STRB_preidx:
11034     MI.setDesc(TII->get(ARM::t2STRB_PRE));
11035     return BB;
11036   case ARM::t2STRH_preidx:
11037     MI.setDesc(TII->get(ARM::t2STRH_PRE));
11038     return BB;
11039 
11040   case ARM::STRi_preidx:
11041   case ARM::STRBi_preidx: {
11042     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11043                                                          : ARM::STRB_PRE_IMM;
11044     // Decode the offset.
11045     unsigned Offset = MI.getOperand(4).getImm();
11046     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11047     Offset = ARM_AM::getAM2Offset(Offset);
11048     if (isSub)
11049       Offset = -Offset;
11050 
11051     MachineMemOperand *MMO = *MI.memoperands_begin();
11052     BuildMI(*BB, MI, dl, TII->get(NewOpc))
11053         .add(MI.getOperand(0)) // Rn_wb
11054         .add(MI.getOperand(1)) // Rt
11055         .add(MI.getOperand(2)) // Rn
11056         .addImm(Offset)        // offset (skip GPR==zero_reg)
11057         .add(MI.getOperand(5)) // pred
11058         .add(MI.getOperand(6))
11059         .addMemOperand(MMO);
11060     MI.eraseFromParent();
11061     return BB;
11062   }
11063   case ARM::STRr_preidx:
11064   case ARM::STRBr_preidx:
11065   case ARM::STRH_preidx: {
11066     unsigned NewOpc;
11067     switch (MI.getOpcode()) {
11068     default: llvm_unreachable("unexpected opcode!");
11069     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11070     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11071     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11072     }
11073     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11074     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
11075       MIB.add(MI.getOperand(i));
11076     MI.eraseFromParent();
11077     return BB;
11078   }
11079 
11080   case ARM::tMOVCCr_pseudo: {
11081     // To "insert" a SELECT_CC instruction, we actually have to insert the
11082     // diamond control-flow pattern.  The incoming instruction knows the
11083     // destination vreg to set, the condition code register to branch on, the
11084     // true/false values to select between, and a branch opcode to use.
11085     const BasicBlock *LLVM_BB = BB->getBasicBlock();
11086     MachineFunction::iterator It = ++BB->getIterator();
11087 
11088     //  thisMBB:
11089     //  ...
11090     //   TrueVal = ...
11091     //   cmpTY ccX, r1, r2
11092     //   bCC copy1MBB
11093     //   fallthrough --> copy0MBB
11094     MachineBasicBlock *thisMBB  = BB;
11095     MachineFunction *F = BB->getParent();
11096     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11097     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
11098     F->insert(It, copy0MBB);
11099     F->insert(It, sinkMBB);
11100 
11101     // Check whether CPSR is live past the tMOVCCr_pseudo.
11102     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11103     if (!MI.killsRegister(ARM::CPSR) &&
11104         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11105       copy0MBB->addLiveIn(ARM::CPSR);
11106       sinkMBB->addLiveIn(ARM::CPSR);
11107     }
11108 
11109     // Transfer the remainder of BB and its successor edges to sinkMBB.
11110     sinkMBB->splice(sinkMBB->begin(), BB,
11111                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11112     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11113 
11114     BB->addSuccessor(copy0MBB);
11115     BB->addSuccessor(sinkMBB);
11116 
11117     BuildMI(BB, dl, TII->get(ARM::tBcc))
11118         .addMBB(sinkMBB)
11119         .addImm(MI.getOperand(3).getImm())
11120         .addReg(MI.getOperand(4).getReg());
11121 
11122     //  copy0MBB:
11123     //   %FalseValue = ...
11124     //   # fallthrough to sinkMBB
11125     BB = copy0MBB;
11126 
11127     // Update machine-CFG edges
11128     BB->addSuccessor(sinkMBB);
11129 
11130     //  sinkMBB:
11131     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11132     //  ...
11133     BB = sinkMBB;
11134     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11135         .addReg(MI.getOperand(1).getReg())
11136         .addMBB(copy0MBB)
11137         .addReg(MI.getOperand(2).getReg())
11138         .addMBB(thisMBB);
11139 
11140     MI.eraseFromParent(); // The pseudo instruction is gone now.
11141     return BB;
11142   }
11143 
11144   case ARM::BCCi64:
11145   case ARM::BCCZi64: {
11146     // If there is an unconditional branch to the other successor, remove it.
11147     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11148 
11149     // Compare both parts that make up the double comparison separately for
11150     // equality.
11151     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11152 
11153     Register LHS1 = MI.getOperand(1).getReg();
11154     Register LHS2 = MI.getOperand(2).getReg();
11155     if (RHSisZero) {
11156       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11157           .addReg(LHS1)
11158           .addImm(0)
11159           .add(predOps(ARMCC::AL));
11160       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11161         .addReg(LHS2).addImm(0)
11162         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11163     } else {
11164       Register RHS1 = MI.getOperand(3).getReg();
11165       Register RHS2 = MI.getOperand(4).getReg();
11166       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11167           .addReg(LHS1)
11168           .addReg(RHS1)
11169           .add(predOps(ARMCC::AL));
11170       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11171         .addReg(LHS2).addReg(RHS2)
11172         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11173     }
11174 
11175     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
11176     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
11177     if (MI.getOperand(0).getImm() == ARMCC::NE)
11178       std::swap(destMBB, exitMBB);
11179 
11180     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
11181       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
11182     if (isThumb2)
11183       BuildMI(BB, dl, TII->get(ARM::t2B))
11184           .addMBB(exitMBB)
11185           .add(predOps(ARMCC::AL));
11186     else
11187       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
11188 
11189     MI.eraseFromParent(); // The pseudo instruction is gone now.
11190     return BB;
11191   }
11192 
11193   case ARM::Int_eh_sjlj_setjmp:
11194   case ARM::Int_eh_sjlj_setjmp_nofp:
11195   case ARM::tInt_eh_sjlj_setjmp:
11196   case ARM::t2Int_eh_sjlj_setjmp:
11197   case ARM::t2Int_eh_sjlj_setjmp_nofp:
11198     return BB;
11199 
11200   case ARM::Int_eh_sjlj_setup_dispatch:
11201     EmitSjLjDispatchBlock(MI, BB);
11202     return BB;
11203 
11204   case ARM::ABS:
11205   case ARM::t2ABS: {
11206     // To insert an ABS instruction, we have to insert the
11207     // diamond control-flow pattern.  The incoming instruction knows the
11208     // source vreg to test against 0, the destination vreg to set,
11209     // the condition code register to branch on, the
11210     // true/false values to select between, and a branch opcode to use.
11211     // It transforms
11212     //     V1 = ABS V0
11213     // into
11214     //     V2 = MOVS V0
11215     //     BCC                      (branch to SinkBB if V0 >= 0)
11216     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
11217     //     SinkBB: V1 = PHI(V2, V3)
11218     const BasicBlock *LLVM_BB = BB->getBasicBlock();
11219     MachineFunction::iterator BBI = ++BB->getIterator();
11220     MachineFunction *Fn = BB->getParent();
11221     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11222     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
11223     Fn->insert(BBI, RSBBB);
11224     Fn->insert(BBI, SinkBB);
11225 
11226     Register ABSSrcReg = MI.getOperand(1).getReg();
11227     Register ABSDstReg = MI.getOperand(0).getReg();
11228     bool ABSSrcKIll = MI.getOperand(1).isKill();
11229     bool isThumb2 = Subtarget->isThumb2();
11230     MachineRegisterInfo &MRI = Fn->getRegInfo();
11231     // In Thumb mode S must not be specified if source register is the SP or
11232     // PC and if destination register is the SP, so restrict register class
11233     Register NewRsbDstReg = MRI.createVirtualRegister(
11234         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
11235 
11236     // Transfer the remainder of BB and its successor edges to sinkMBB.
11237     SinkBB->splice(SinkBB->begin(), BB,
11238                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
11239     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
11240 
11241     BB->addSuccessor(RSBBB);
11242     BB->addSuccessor(SinkBB);
11243 
11244     // fall through to SinkMBB
11245     RSBBB->addSuccessor(SinkBB);
11246 
11247     // insert a cmp at the end of BB
11248     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11249         .addReg(ABSSrcReg)
11250         .addImm(0)
11251         .add(predOps(ARMCC::AL));
11252 
11253     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
11254     BuildMI(BB, dl,
11255       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
11256       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
11257 
11258     // insert rsbri in RSBBB
11259     // Note: BCC and rsbri will be converted into predicated rsbmi
11260     // by if-conversion pass
11261     BuildMI(*RSBBB, RSBBB->begin(), dl,
11262             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
11263         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
11264         .addImm(0)
11265         .add(predOps(ARMCC::AL))
11266         .add(condCodeOp());
11267 
11268     // insert PHI in SinkBB,
11269     // reuse ABSDstReg to not change uses of ABS instruction
11270     BuildMI(*SinkBB, SinkBB->begin(), dl,
11271       TII->get(ARM::PHI), ABSDstReg)
11272       .addReg(NewRsbDstReg).addMBB(RSBBB)
11273       .addReg(ABSSrcReg).addMBB(BB);
11274 
11275     // remove ABS instruction
11276     MI.eraseFromParent();
11277 
11278     // return last added BB
11279     return SinkBB;
11280   }
11281   case ARM::COPY_STRUCT_BYVAL_I32:
11282     ++NumLoopByVals;
11283     return EmitStructByval(MI, BB);
11284   case ARM::WIN__CHKSTK:
11285     return EmitLowered__chkstk(MI, BB);
11286   case ARM::WIN__DBZCHK:
11287     return EmitLowered__dbzchk(MI, BB);
11288   case ARM::t2DoLoopStart:
11289     // We are just here to set a register allocation hint, prefering lr for the
11290     // input register to make it more likely to be movable and removable, later
11291     // in the pipeline.
11292     Register R = MI.getOperand(1).getReg();
11293     MachineFunction *MF = MI.getParent()->getParent();
11294     MF->getRegInfo().setRegAllocationHint(R, ARMRI::RegLR, 0);
11295     return BB;
11296   }
11297 }
11298 
11299 /// Attaches vregs to MEMCPY that it will use as scratch registers
11300 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
11301 /// instead of as a custom inserter because we need the use list from the SDNode.
11302 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
11303                                     MachineInstr &MI, const SDNode *Node) {
11304   bool isThumb1 = Subtarget->isThumb1Only();
11305 
11306   DebugLoc DL = MI.getDebugLoc();
11307   MachineFunction *MF = MI.getParent()->getParent();
11308   MachineRegisterInfo &MRI = MF->getRegInfo();
11309   MachineInstrBuilder MIB(*MF, MI);
11310 
11311   // If the new dst/src is unused mark it as dead.
11312   if (!Node->hasAnyUseOfValue(0)) {
11313     MI.getOperand(0).setIsDead(true);
11314   }
11315   if (!Node->hasAnyUseOfValue(1)) {
11316     MI.getOperand(1).setIsDead(true);
11317   }
11318 
11319   // The MEMCPY both defines and kills the scratch registers.
11320   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
11321     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
11322                                                          : &ARM::GPRRegClass);
11323     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
11324   }
11325 }
11326 
11327 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11328                                                       SDNode *Node) const {
11329   if (MI.getOpcode() == ARM::MEMCPY) {
11330     attachMEMCPYScratchRegs(Subtarget, MI, Node);
11331     return;
11332   }
11333 
11334   const MCInstrDesc *MCID = &MI.getDesc();
11335   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
11336   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
11337   // operand is still set to noreg. If needed, set the optional operand's
11338   // register to CPSR, and remove the redundant implicit def.
11339   //
11340   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
11341 
11342   // Rename pseudo opcodes.
11343   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
11344   unsigned ccOutIdx;
11345   if (NewOpc) {
11346     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
11347     MCID = &TII->get(NewOpc);
11348 
11349     assert(MCID->getNumOperands() ==
11350            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
11351         && "converted opcode should be the same except for cc_out"
11352            " (and, on Thumb1, pred)");
11353 
11354     MI.setDesc(*MCID);
11355 
11356     // Add the optional cc_out operand
11357     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
11358 
11359     // On Thumb1, move all input operands to the end, then add the predicate
11360     if (Subtarget->isThumb1Only()) {
11361       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
11362         MI.addOperand(MI.getOperand(1));
11363         MI.RemoveOperand(1);
11364       }
11365 
11366       // Restore the ties
11367       for (unsigned i = MI.getNumOperands(); i--;) {
11368         const MachineOperand& op = MI.getOperand(i);
11369         if (op.isReg() && op.isUse()) {
11370           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
11371           if (DefIdx != -1)
11372             MI.tieOperands(DefIdx, i);
11373         }
11374       }
11375 
11376       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
11377       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
11378       ccOutIdx = 1;
11379     } else
11380       ccOutIdx = MCID->getNumOperands() - 1;
11381   } else
11382     ccOutIdx = MCID->getNumOperands() - 1;
11383 
11384   // Any ARM instruction that sets the 's' bit should specify an optional
11385   // "cc_out" operand in the last operand position.
11386   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
11387     assert(!NewOpc && "Optional cc_out operand required");
11388     return;
11389   }
11390   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
11391   // since we already have an optional CPSR def.
11392   bool definesCPSR = false;
11393   bool deadCPSR = false;
11394   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
11395        ++i) {
11396     const MachineOperand &MO = MI.getOperand(i);
11397     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
11398       definesCPSR = true;
11399       if (MO.isDead())
11400         deadCPSR = true;
11401       MI.RemoveOperand(i);
11402       break;
11403     }
11404   }
11405   if (!definesCPSR) {
11406     assert(!NewOpc && "Optional cc_out operand required");
11407     return;
11408   }
11409   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
11410   if (deadCPSR) {
11411     assert(!MI.getOperand(ccOutIdx).getReg() &&
11412            "expect uninitialized optional cc_out operand");
11413     // Thumb1 instructions must have the S bit even if the CPSR is dead.
11414     if (!Subtarget->isThumb1Only())
11415       return;
11416   }
11417 
11418   // If this instruction was defined with an optional CPSR def and its dag node
11419   // had a live implicit CPSR def, then activate the optional CPSR def.
11420   MachineOperand &MO = MI.getOperand(ccOutIdx);
11421   MO.setReg(ARM::CPSR);
11422   MO.setIsDef(true);
11423 }
11424 
11425 //===----------------------------------------------------------------------===//
11426 //                           ARM Optimization Hooks
11427 //===----------------------------------------------------------------------===//
11428 
11429 // Helper function that checks if N is a null or all ones constant.
11430 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11431   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11432 }
11433 
11434 // Return true if N is conditionally 0 or all ones.
11435 // Detects these expressions where cc is an i1 value:
11436 //
11437 //   (select cc 0, y)   [AllOnes=0]
11438 //   (select cc y, 0)   [AllOnes=0]
11439 //   (zext cc)          [AllOnes=0]
11440 //   (sext cc)          [AllOnes=0/1]
11441 //   (select cc -1, y)  [AllOnes=1]
11442 //   (select cc y, -1)  [AllOnes=1]
11443 //
11444 // Invert is set when N is the null/all ones constant when CC is false.
11445 // OtherOp is set to the alternative value of N.
11446 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11447                                        SDValue &CC, bool &Invert,
11448                                        SDValue &OtherOp,
11449                                        SelectionDAG &DAG) {
11450   switch (N->getOpcode()) {
11451   default: return false;
11452   case ISD::SELECT: {
11453     CC = N->getOperand(0);
11454     SDValue N1 = N->getOperand(1);
11455     SDValue N2 = N->getOperand(2);
11456     if (isZeroOrAllOnes(N1, AllOnes)) {
11457       Invert = false;
11458       OtherOp = N2;
11459       return true;
11460     }
11461     if (isZeroOrAllOnes(N2, AllOnes)) {
11462       Invert = true;
11463       OtherOp = N1;
11464       return true;
11465     }
11466     return false;
11467   }
11468   case ISD::ZERO_EXTEND:
11469     // (zext cc) can never be the all ones value.
11470     if (AllOnes)
11471       return false;
11472     LLVM_FALLTHROUGH;
11473   case ISD::SIGN_EXTEND: {
11474     SDLoc dl(N);
11475     EVT VT = N->getValueType(0);
11476     CC = N->getOperand(0);
11477     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11478       return false;
11479     Invert = !AllOnes;
11480     if (AllOnes)
11481       // When looking for an AllOnes constant, N is an sext, and the 'other'
11482       // value is 0.
11483       OtherOp = DAG.getConstant(0, dl, VT);
11484     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11485       // When looking for a 0 constant, N can be zext or sext.
11486       OtherOp = DAG.getConstant(1, dl, VT);
11487     else
11488       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11489                                 VT);
11490     return true;
11491   }
11492   }
11493 }
11494 
11495 // Combine a constant select operand into its use:
11496 //
11497 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
11498 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
11499 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
11500 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
11501 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
11502 //
11503 // The transform is rejected if the select doesn't have a constant operand that
11504 // is null, or all ones when AllOnes is set.
11505 //
11506 // Also recognize sext/zext from i1:
11507 //
11508 //   (add (zext cc), x) -> (select cc (add x, 1), x)
11509 //   (add (sext cc), x) -> (select cc (add x, -1), x)
11510 //
11511 // These transformations eventually create predicated instructions.
11512 //
11513 // @param N       The node to transform.
11514 // @param Slct    The N operand that is a select.
11515 // @param OtherOp The other N operand (x above).
11516 // @param DCI     Context.
11517 // @param AllOnes Require the select constant to be all ones instead of null.
11518 // @returns The new node, or SDValue() on failure.
11519 static
11520 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11521                             TargetLowering::DAGCombinerInfo &DCI,
11522                             bool AllOnes = false) {
11523   SelectionDAG &DAG = DCI.DAG;
11524   EVT VT = N->getValueType(0);
11525   SDValue NonConstantVal;
11526   SDValue CCOp;
11527   bool SwapSelectOps;
11528   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11529                                   NonConstantVal, DAG))
11530     return SDValue();
11531 
11532   // Slct is now know to be the desired identity constant when CC is true.
11533   SDValue TrueVal = OtherOp;
11534   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11535                                  OtherOp, NonConstantVal);
11536   // Unless SwapSelectOps says CC should be false.
11537   if (SwapSelectOps)
11538     std::swap(TrueVal, FalseVal);
11539 
11540   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11541                      CCOp, TrueVal, FalseVal);
11542 }
11543 
11544 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11545 static
11546 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11547                                        TargetLowering::DAGCombinerInfo &DCI) {
11548   SDValue N0 = N->getOperand(0);
11549   SDValue N1 = N->getOperand(1);
11550   if (N0.getNode()->hasOneUse())
11551     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11552       return Result;
11553   if (N1.getNode()->hasOneUse())
11554     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11555       return Result;
11556   return SDValue();
11557 }
11558 
11559 static bool IsVUZPShuffleNode(SDNode *N) {
11560   // VUZP shuffle node.
11561   if (N->getOpcode() == ARMISD::VUZP)
11562     return true;
11563 
11564   // "VUZP" on i32 is an alias for VTRN.
11565   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11566     return true;
11567 
11568   return false;
11569 }
11570 
11571 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11572                                  TargetLowering::DAGCombinerInfo &DCI,
11573                                  const ARMSubtarget *Subtarget) {
11574   // Look for ADD(VUZP.0, VUZP.1).
11575   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11576       N0 == N1)
11577    return SDValue();
11578 
11579   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11580   if (!N->getValueType(0).is64BitVector())
11581     return SDValue();
11582 
11583   // Generate vpadd.
11584   SelectionDAG &DAG = DCI.DAG;
11585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11586   SDLoc dl(N);
11587   SDNode *Unzip = N0.getNode();
11588   EVT VT = N->getValueType(0);
11589 
11590   SmallVector<SDValue, 8> Ops;
11591   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11592                                 TLI.getPointerTy(DAG.getDataLayout())));
11593   Ops.push_back(Unzip->getOperand(0));
11594   Ops.push_back(Unzip->getOperand(1));
11595 
11596   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11597 }
11598 
11599 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11600                                       TargetLowering::DAGCombinerInfo &DCI,
11601                                       const ARMSubtarget *Subtarget) {
11602   // Check for two extended operands.
11603   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11604         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11605       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11606         N1.getOpcode() == ISD::ZERO_EXTEND))
11607     return SDValue();
11608 
11609   SDValue N00 = N0.getOperand(0);
11610   SDValue N10 = N1.getOperand(0);
11611 
11612   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11613   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11614       N00 == N10)
11615     return SDValue();
11616 
11617   // We only recognize Q register paddl here; this can't be reached until
11618   // after type legalization.
11619   if (!N00.getValueType().is64BitVector() ||
11620       !N0.getValueType().is128BitVector())
11621     return SDValue();
11622 
11623   // Generate vpaddl.
11624   SelectionDAG &DAG = DCI.DAG;
11625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11626   SDLoc dl(N);
11627   EVT VT = N->getValueType(0);
11628 
11629   SmallVector<SDValue, 8> Ops;
11630   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11631   unsigned Opcode;
11632   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11633     Opcode = Intrinsic::arm_neon_vpaddls;
11634   else
11635     Opcode = Intrinsic::arm_neon_vpaddlu;
11636   Ops.push_back(DAG.getConstant(Opcode, dl,
11637                                 TLI.getPointerTy(DAG.getDataLayout())));
11638   EVT ElemTy = N00.getValueType().getVectorElementType();
11639   unsigned NumElts = VT.getVectorNumElements();
11640   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11641   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11642                                N00.getOperand(0), N00.getOperand(1));
11643   Ops.push_back(Concat);
11644 
11645   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11646 }
11647 
11648 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11649 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11650 // much easier to match.
11651 static SDValue
11652 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11653                                TargetLowering::DAGCombinerInfo &DCI,
11654                                const ARMSubtarget *Subtarget) {
11655   // Only perform optimization if after legalize, and if NEON is available. We
11656   // also expected both operands to be BUILD_VECTORs.
11657   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11658       || N0.getOpcode() != ISD::BUILD_VECTOR
11659       || N1.getOpcode() != ISD::BUILD_VECTOR)
11660     return SDValue();
11661 
11662   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11663   EVT VT = N->getValueType(0);
11664   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11665     return SDValue();
11666 
11667   // Check that the vector operands are of the right form.
11668   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11669   // operands, where N is the size of the formed vector.
11670   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11671   // index such that we have a pair wise add pattern.
11672 
11673   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11674   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11675     return SDValue();
11676   SDValue Vec = N0->getOperand(0)->getOperand(0);
11677   SDNode *V = Vec.getNode();
11678   unsigned nextIndex = 0;
11679 
11680   // For each operands to the ADD which are BUILD_VECTORs,
11681   // check to see if each of their operands are an EXTRACT_VECTOR with
11682   // the same vector and appropriate index.
11683   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11684     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11685         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11686 
11687       SDValue ExtVec0 = N0->getOperand(i);
11688       SDValue ExtVec1 = N1->getOperand(i);
11689 
11690       // First operand is the vector, verify its the same.
11691       if (V != ExtVec0->getOperand(0).getNode() ||
11692           V != ExtVec1->getOperand(0).getNode())
11693         return SDValue();
11694 
11695       // Second is the constant, verify its correct.
11696       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11697       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11698 
11699       // For the constant, we want to see all the even or all the odd.
11700       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11701           || C1->getZExtValue() != nextIndex+1)
11702         return SDValue();
11703 
11704       // Increment index.
11705       nextIndex+=2;
11706     } else
11707       return SDValue();
11708   }
11709 
11710   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11711   // we're using the entire input vector, otherwise there's a size/legality
11712   // mismatch somewhere.
11713   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11714       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11715     return SDValue();
11716 
11717   // Create VPADDL node.
11718   SelectionDAG &DAG = DCI.DAG;
11719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11720 
11721   SDLoc dl(N);
11722 
11723   // Build operand list.
11724   SmallVector<SDValue, 8> Ops;
11725   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11726                                 TLI.getPointerTy(DAG.getDataLayout())));
11727 
11728   // Input is the vector.
11729   Ops.push_back(Vec);
11730 
11731   // Get widened type and narrowed type.
11732   MVT widenType;
11733   unsigned numElem = VT.getVectorNumElements();
11734 
11735   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11736   switch (inputLaneType.getSimpleVT().SimpleTy) {
11737     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11738     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11739     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11740     default:
11741       llvm_unreachable("Invalid vector element type for padd optimization.");
11742   }
11743 
11744   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11745   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11746   return DAG.getNode(ExtOp, dl, VT, tmp);
11747 }
11748 
11749 static SDValue findMUL_LOHI(SDValue V) {
11750   if (V->getOpcode() == ISD::UMUL_LOHI ||
11751       V->getOpcode() == ISD::SMUL_LOHI)
11752     return V;
11753   return SDValue();
11754 }
11755 
11756 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11757                                         TargetLowering::DAGCombinerInfo &DCI,
11758                                         const ARMSubtarget *Subtarget) {
11759   if (!Subtarget->hasBaseDSP())
11760     return SDValue();
11761 
11762   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11763   // accumulates the product into a 64-bit value. The 16-bit values will
11764   // be sign extended somehow or SRA'd into 32-bit values
11765   // (addc (adde (mul 16bit, 16bit), lo), hi)
11766   SDValue Mul = AddcNode->getOperand(0);
11767   SDValue Lo = AddcNode->getOperand(1);
11768   if (Mul.getOpcode() != ISD::MUL) {
11769     Lo = AddcNode->getOperand(0);
11770     Mul = AddcNode->getOperand(1);
11771     if (Mul.getOpcode() != ISD::MUL)
11772       return SDValue();
11773   }
11774 
11775   SDValue SRA = AddeNode->getOperand(0);
11776   SDValue Hi = AddeNode->getOperand(1);
11777   if (SRA.getOpcode() != ISD::SRA) {
11778     SRA = AddeNode->getOperand(1);
11779     Hi = AddeNode->getOperand(0);
11780     if (SRA.getOpcode() != ISD::SRA)
11781       return SDValue();
11782   }
11783   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11784     if (Const->getZExtValue() != 31)
11785       return SDValue();
11786   } else
11787     return SDValue();
11788 
11789   if (SRA.getOperand(0) != Mul)
11790     return SDValue();
11791 
11792   SelectionDAG &DAG = DCI.DAG;
11793   SDLoc dl(AddcNode);
11794   unsigned Opcode = 0;
11795   SDValue Op0;
11796   SDValue Op1;
11797 
11798   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11799     Opcode = ARMISD::SMLALBB;
11800     Op0 = Mul.getOperand(0);
11801     Op1 = Mul.getOperand(1);
11802   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11803     Opcode = ARMISD::SMLALBT;
11804     Op0 = Mul.getOperand(0);
11805     Op1 = Mul.getOperand(1).getOperand(0);
11806   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11807     Opcode = ARMISD::SMLALTB;
11808     Op0 = Mul.getOperand(0).getOperand(0);
11809     Op1 = Mul.getOperand(1);
11810   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11811     Opcode = ARMISD::SMLALTT;
11812     Op0 = Mul->getOperand(0).getOperand(0);
11813     Op1 = Mul->getOperand(1).getOperand(0);
11814   }
11815 
11816   if (!Op0 || !Op1)
11817     return SDValue();
11818 
11819   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11820                               Op0, Op1, Lo, Hi);
11821   // Replace the ADDs' nodes uses by the MLA node's values.
11822   SDValue HiMLALResult(SMLAL.getNode(), 1);
11823   SDValue LoMLALResult(SMLAL.getNode(), 0);
11824 
11825   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11826   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11827 
11828   // Return original node to notify the driver to stop replacing.
11829   SDValue resNode(AddcNode, 0);
11830   return resNode;
11831 }
11832 
11833 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11834                                      TargetLowering::DAGCombinerInfo &DCI,
11835                                      const ARMSubtarget *Subtarget) {
11836   // Look for multiply add opportunities.
11837   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11838   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11839   // a glue link from the first add to the second add.
11840   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11841   // a S/UMLAL instruction.
11842   //                  UMUL_LOHI
11843   //                 / :lo    \ :hi
11844   //                V          \          [no multiline comment]
11845   //    loAdd ->  ADDC         |
11846   //                 \ :carry /
11847   //                  V      V
11848   //                    ADDE   <- hiAdd
11849   //
11850   // In the special case where only the higher part of a signed result is used
11851   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11852   // a constant with the exact value of 0x80000000, we recognize we are dealing
11853   // with a "rounded multiply and add" (or subtract) and transform it into
11854   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11855 
11856   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11857           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11858          "Expect an ADDE or SUBE");
11859 
11860   assert(AddeSubeNode->getNumOperands() == 3 &&
11861          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11862          "ADDE node has the wrong inputs");
11863 
11864   // Check that we are chained to the right ADDC or SUBC node.
11865   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11866   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11867        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11868       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11869        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11870     return SDValue();
11871 
11872   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11873   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11874 
11875   // Check if the two operands are from the same mul_lohi node.
11876   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11877     return SDValue();
11878 
11879   assert(AddcSubcNode->getNumValues() == 2 &&
11880          AddcSubcNode->getValueType(0) == MVT::i32 &&
11881          "Expect ADDC with two result values. First: i32");
11882 
11883   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11884   // maybe a SMLAL which multiplies two 16-bit values.
11885   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11886       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11887       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11888       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11889       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11890     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11891 
11892   // Check for the triangle shape.
11893   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11894   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11895 
11896   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11897   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11898     return SDValue();
11899 
11900   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11901   bool IsLeftOperandMUL = false;
11902   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11903   if (MULOp == SDValue())
11904     MULOp = findMUL_LOHI(AddeSubeOp1);
11905   else
11906     IsLeftOperandMUL = true;
11907   if (MULOp == SDValue())
11908     return SDValue();
11909 
11910   // Figure out the right opcode.
11911   unsigned Opc = MULOp->getOpcode();
11912   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11913 
11914   // Figure out the high and low input values to the MLAL node.
11915   SDValue *HiAddSub = nullptr;
11916   SDValue *LoMul = nullptr;
11917   SDValue *LowAddSub = nullptr;
11918 
11919   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11920   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11921     return SDValue();
11922 
11923   if (IsLeftOperandMUL)
11924     HiAddSub = &AddeSubeOp1;
11925   else
11926     HiAddSub = &AddeSubeOp0;
11927 
11928   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11929   // whose low result is fed to the ADDC/SUBC we are checking.
11930 
11931   if (AddcSubcOp0 == MULOp.getValue(0)) {
11932     LoMul = &AddcSubcOp0;
11933     LowAddSub = &AddcSubcOp1;
11934   }
11935   if (AddcSubcOp1 == MULOp.getValue(0)) {
11936     LoMul = &AddcSubcOp1;
11937     LowAddSub = &AddcSubcOp0;
11938   }
11939 
11940   if (!LoMul)
11941     return SDValue();
11942 
11943   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11944   // the replacement below will create a cycle.
11945   if (AddcSubcNode == HiAddSub->getNode() ||
11946       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11947     return SDValue();
11948 
11949   // Create the merged node.
11950   SelectionDAG &DAG = DCI.DAG;
11951 
11952   // Start building operand list.
11953   SmallVector<SDValue, 8> Ops;
11954   Ops.push_back(LoMul->getOperand(0));
11955   Ops.push_back(LoMul->getOperand(1));
11956 
11957   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11958   // the case, we must be doing signed multiplication and only use the higher
11959   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11960   // addition or subtraction with the value of 0x800000.
11961   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11962       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11963       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11964       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11965           0x80000000) {
11966     Ops.push_back(*HiAddSub);
11967     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11968       FinalOpc = ARMISD::SMMLSR;
11969     } else {
11970       FinalOpc = ARMISD::SMMLAR;
11971     }
11972     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11973     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11974 
11975     return SDValue(AddeSubeNode, 0);
11976   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11977     // SMMLS is generated during instruction selection and the rest of this
11978     // function can not handle the case where AddcSubcNode is a SUBC.
11979     return SDValue();
11980 
11981   // Finish building the operand list for {U/S}MLAL
11982   Ops.push_back(*LowAddSub);
11983   Ops.push_back(*HiAddSub);
11984 
11985   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11986                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11987 
11988   // Replace the ADDs' nodes uses by the MLA node's values.
11989   SDValue HiMLALResult(MLALNode.getNode(), 1);
11990   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11991 
11992   SDValue LoMLALResult(MLALNode.getNode(), 0);
11993   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11994 
11995   // Return original node to notify the driver to stop replacing.
11996   return SDValue(AddeSubeNode, 0);
11997 }
11998 
11999 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
12000                                       TargetLowering::DAGCombinerInfo &DCI,
12001                                       const ARMSubtarget *Subtarget) {
12002   // UMAAL is similar to UMLAL except that it adds two unsigned values.
12003   // While trying to combine for the other MLAL nodes, first search for the
12004   // chance to use UMAAL. Check if Addc uses a node which has already
12005   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12006   // as the addend, and it's handled in PerformUMLALCombine.
12007 
12008   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12009     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12010 
12011   // Check that we have a glued ADDC node.
12012   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12013   if (AddcNode->getOpcode() != ARMISD::ADDC)
12014     return SDValue();
12015 
12016   // Find the converted UMAAL or quit if it doesn't exist.
12017   SDNode *UmlalNode = nullptr;
12018   SDValue AddHi;
12019   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12020     UmlalNode = AddcNode->getOperand(0).getNode();
12021     AddHi = AddcNode->getOperand(1);
12022   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12023     UmlalNode = AddcNode->getOperand(1).getNode();
12024     AddHi = AddcNode->getOperand(0);
12025   } else {
12026     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12027   }
12028 
12029   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12030   // the ADDC as well as Zero.
12031   if (!isNullConstant(UmlalNode->getOperand(3)))
12032     return SDValue();
12033 
12034   if ((isNullConstant(AddeNode->getOperand(0)) &&
12035        AddeNode->getOperand(1).getNode() == UmlalNode) ||
12036       (AddeNode->getOperand(0).getNode() == UmlalNode &&
12037        isNullConstant(AddeNode->getOperand(1)))) {
12038     SelectionDAG &DAG = DCI.DAG;
12039     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12040                       UmlalNode->getOperand(2), AddHi };
12041     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12042                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
12043 
12044     // Replace the ADDs' nodes uses by the UMAAL node's values.
12045     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12046     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12047 
12048     // Return original node to notify the driver to stop replacing.
12049     return SDValue(AddeNode, 0);
12050   }
12051   return SDValue();
12052 }
12053 
12054 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12055                                    const ARMSubtarget *Subtarget) {
12056   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12057     return SDValue();
12058 
12059   // Check that we have a pair of ADDC and ADDE as operands.
12060   // Both addends of the ADDE must be zero.
12061   SDNode* AddcNode = N->getOperand(2).getNode();
12062   SDNode* AddeNode = N->getOperand(3).getNode();
12063   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12064       (AddeNode->getOpcode() == ARMISD::ADDE) &&
12065       isNullConstant(AddeNode->getOperand(0)) &&
12066       isNullConstant(AddeNode->getOperand(1)) &&
12067       (AddeNode->getOperand(2).getNode() == AddcNode))
12068     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12069                        DAG.getVTList(MVT::i32, MVT::i32),
12070                        {N->getOperand(0), N->getOperand(1),
12071                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
12072   else
12073     return SDValue();
12074 }
12075 
12076 static SDValue PerformAddcSubcCombine(SDNode *N,
12077                                       TargetLowering::DAGCombinerInfo &DCI,
12078                                       const ARMSubtarget *Subtarget) {
12079   SelectionDAG &DAG(DCI.DAG);
12080 
12081   if (N->getOpcode() == ARMISD::SUBC) {
12082     // (SUBC (ADDE 0, 0, C), 1) -> C
12083     SDValue LHS = N->getOperand(0);
12084     SDValue RHS = N->getOperand(1);
12085     if (LHS->getOpcode() == ARMISD::ADDE &&
12086         isNullConstant(LHS->getOperand(0)) &&
12087         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12088       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12089     }
12090   }
12091 
12092   if (Subtarget->isThumb1Only()) {
12093     SDValue RHS = N->getOperand(1);
12094     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12095       int32_t imm = C->getSExtValue();
12096       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12097         SDLoc DL(N);
12098         RHS = DAG.getConstant(-imm, DL, MVT::i32);
12099         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12100                                                            : ARMISD::ADDC;
12101         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12102       }
12103     }
12104   }
12105 
12106   return SDValue();
12107 }
12108 
12109 static SDValue PerformAddeSubeCombine(SDNode *N,
12110                                       TargetLowering::DAGCombinerInfo &DCI,
12111                                       const ARMSubtarget *Subtarget) {
12112   if (Subtarget->isThumb1Only()) {
12113     SelectionDAG &DAG = DCI.DAG;
12114     SDValue RHS = N->getOperand(1);
12115     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12116       int64_t imm = C->getSExtValue();
12117       if (imm < 0) {
12118         SDLoc DL(N);
12119 
12120         // The with-carry-in form matches bitwise not instead of the negation.
12121         // Effectively, the inverse interpretation of the carry flag already
12122         // accounts for part of the negation.
12123         RHS = DAG.getConstant(~imm, DL, MVT::i32);
12124 
12125         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12126                                                            : ARMISD::ADDE;
12127         return DAG.getNode(Opcode, DL, N->getVTList(),
12128                            N->getOperand(0), RHS, N->getOperand(2));
12129       }
12130     }
12131   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12132     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12133   }
12134   return SDValue();
12135 }
12136 
12137 static SDValue PerformSELECTCombine(SDNode *N,
12138                                     TargetLowering::DAGCombinerInfo &DCI,
12139                                     const ARMSubtarget *Subtarget) {
12140   if (!Subtarget->hasMVEIntegerOps())
12141     return SDValue();
12142 
12143   SDLoc dl(N);
12144   SDValue SetCC;
12145   SDValue LHS;
12146   SDValue RHS;
12147   ISD::CondCode CC;
12148   SDValue TrueVal;
12149   SDValue FalseVal;
12150 
12151   if (N->getOpcode() == ISD::SELECT &&
12152       N->getOperand(0)->getOpcode() == ISD::SETCC) {
12153     SetCC = N->getOperand(0);
12154     LHS = SetCC->getOperand(0);
12155     RHS = SetCC->getOperand(1);
12156     CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
12157     TrueVal = N->getOperand(1);
12158     FalseVal = N->getOperand(2);
12159   } else if (N->getOpcode() == ISD::SELECT_CC) {
12160     LHS = N->getOperand(0);
12161     RHS = N->getOperand(1);
12162     CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
12163     TrueVal = N->getOperand(2);
12164     FalseVal = N->getOperand(3);
12165   } else {
12166     return SDValue();
12167   }
12168 
12169   unsigned int Opcode = 0;
12170   if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
12171        FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
12172       (CC == ISD::SETULT || CC == ISD::SETUGT)) {
12173     Opcode = ARMISD::VMINVu;
12174     if (CC == ISD::SETUGT)
12175       std::swap(TrueVal, FalseVal);
12176   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
12177               FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
12178              (CC == ISD::SETLT || CC == ISD::SETGT)) {
12179     Opcode = ARMISD::VMINVs;
12180     if (CC == ISD::SETGT)
12181       std::swap(TrueVal, FalseVal);
12182   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
12183               FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
12184              (CC == ISD::SETUGT || CC == ISD::SETULT)) {
12185     Opcode = ARMISD::VMAXVu;
12186     if (CC == ISD::SETULT)
12187       std::swap(TrueVal, FalseVal);
12188   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
12189               FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
12190              (CC == ISD::SETGT || CC == ISD::SETLT)) {
12191     Opcode = ARMISD::VMAXVs;
12192     if (CC == ISD::SETLT)
12193       std::swap(TrueVal, FalseVal);
12194   } else
12195     return SDValue();
12196 
12197   // Normalise to the right hand side being the vector reduction
12198   switch (TrueVal->getOpcode()) {
12199   case ISD::VECREDUCE_UMIN:
12200   case ISD::VECREDUCE_SMIN:
12201   case ISD::VECREDUCE_UMAX:
12202   case ISD::VECREDUCE_SMAX:
12203     std::swap(LHS, RHS);
12204     std::swap(TrueVal, FalseVal);
12205     break;
12206   }
12207 
12208   EVT VectorType = FalseVal->getOperand(0).getValueType();
12209 
12210   if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
12211       VectorType != MVT::v4i32)
12212     return SDValue();
12213 
12214   EVT VectorScalarType = VectorType.getVectorElementType();
12215 
12216   // The values being selected must also be the ones being compared
12217   if (TrueVal != LHS || FalseVal != RHS)
12218     return SDValue();
12219 
12220   EVT LeftType = LHS->getValueType(0);
12221   EVT RightType = RHS->getValueType(0);
12222 
12223   // The types must match the reduced type too
12224   if (LeftType != VectorScalarType || RightType != VectorScalarType)
12225     return SDValue();
12226 
12227   // Legalise the scalar to an i32
12228   if (VectorScalarType != MVT::i32)
12229     LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12230 
12231   // Generate the reduction as an i32 for legalisation purposes
12232   auto Reduction =
12233       DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
12234 
12235   // The result isn't actually an i32 so truncate it back to its original type
12236   if (VectorScalarType != MVT::i32)
12237     Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
12238 
12239   return Reduction;
12240 }
12241 
12242 // A special combine for the vqdmulh family of instructions. This is one of the
12243 // potential set of patterns that could patch this instruction. The base pattern
12244 // you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
12245 // This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
12246 // which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
12247 // the max is unnecessary.
12248 static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
12249   EVT VT = N->getValueType(0);
12250   SDValue Shft;
12251   ConstantSDNode *Clamp;
12252 
12253   if (N->getOpcode() == ISD::SMIN) {
12254     Shft = N->getOperand(0);
12255     Clamp = isConstOrConstSplat(N->getOperand(1));
12256   } else if (N->getOpcode() == ISD::VSELECT) {
12257     // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
12258     SDValue Cmp = N->getOperand(0);
12259     if (Cmp.getOpcode() != ISD::SETCC ||
12260         cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
12261         Cmp.getOperand(0) != N->getOperand(1) ||
12262         Cmp.getOperand(1) != N->getOperand(2))
12263       return SDValue();
12264     Shft = N->getOperand(1);
12265     Clamp = isConstOrConstSplat(N->getOperand(2));
12266   } else
12267     return SDValue();
12268 
12269   if (!Clamp)
12270     return SDValue();
12271 
12272   MVT ScalarType;
12273   int ShftAmt = 0;
12274   switch (Clamp->getSExtValue()) {
12275   case (1 << 7) - 1:
12276     ScalarType = MVT::i8;
12277     ShftAmt = 7;
12278     break;
12279   case (1 << 15) - 1:
12280     ScalarType = MVT::i16;
12281     ShftAmt = 15;
12282     break;
12283   case (1ULL << 31) - 1:
12284     ScalarType = MVT::i32;
12285     ShftAmt = 31;
12286     break;
12287   default:
12288     return SDValue();
12289   }
12290 
12291   if (Shft.getOpcode() != ISD::SRA)
12292     return SDValue();
12293   ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
12294   if (!N1 || N1->getSExtValue() != ShftAmt)
12295     return SDValue();
12296 
12297   SDValue Mul = Shft.getOperand(0);
12298   if (Mul.getOpcode() != ISD::MUL)
12299     return SDValue();
12300 
12301   SDValue Ext0 = Mul.getOperand(0);
12302   SDValue Ext1 = Mul.getOperand(1);
12303   if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
12304       Ext1.getOpcode() != ISD::SIGN_EXTEND)
12305     return SDValue();
12306   EVT VecVT = Ext0.getOperand(0).getValueType();
12307   if (VecVT != MVT::v4i32 && VecVT != MVT::v8i16 && VecVT != MVT::v16i8)
12308     return SDValue();
12309   if (Ext1.getOperand(0).getValueType() != VecVT ||
12310       VecVT.getScalarType() != ScalarType ||
12311       VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
12312     return SDValue();
12313 
12314   SDLoc DL(Mul);
12315   SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, VecVT, Ext0.getOperand(0),
12316                                 Ext1.getOperand(0));
12317   return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, VQDMULH);
12318 }
12319 
12320 static SDValue PerformVSELECTCombine(SDNode *N,
12321                                      TargetLowering::DAGCombinerInfo &DCI,
12322                                      const ARMSubtarget *Subtarget) {
12323   if (!Subtarget->hasMVEIntegerOps())
12324     return SDValue();
12325 
12326   if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
12327     return V;
12328 
12329   // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
12330   //
12331   // We need to re-implement this optimization here as the implementation in the
12332   // Target-Independent DAGCombiner does not handle the kind of constant we make
12333   // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
12334   // good reason, allowing truncation there would break other targets).
12335   //
12336   // Currently, this is only done for MVE, as it's the only target that benefits
12337   // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
12338   if (N->getOperand(0).getOpcode() != ISD::XOR)
12339     return SDValue();
12340   SDValue XOR = N->getOperand(0);
12341 
12342   // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
12343   // It is important to check with truncation allowed as the BUILD_VECTORs we
12344   // generate in those situations will truncate their operands.
12345   ConstantSDNode *Const =
12346       isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
12347                           /*AllowTruncation*/ true);
12348   if (!Const || !Const->isOne())
12349     return SDValue();
12350 
12351   // Rewrite into vselect(cond, rhs, lhs).
12352   SDValue Cond = XOR->getOperand(0);
12353   SDValue LHS = N->getOperand(1);
12354   SDValue RHS = N->getOperand(2);
12355   EVT Type = N->getValueType(0);
12356   return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
12357 }
12358 
12359 static SDValue PerformABSCombine(SDNode *N,
12360                                   TargetLowering::DAGCombinerInfo &DCI,
12361                                   const ARMSubtarget *Subtarget) {
12362   SDValue res;
12363   SelectionDAG &DAG = DCI.DAG;
12364   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12365 
12366   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
12367     return SDValue();
12368 
12369   if (!TLI.expandABS(N, res, DAG))
12370       return SDValue();
12371 
12372   return res;
12373 }
12374 
12375 /// PerformADDECombine - Target-specific dag combine transform from
12376 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
12377 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
12378 static SDValue PerformADDECombine(SDNode *N,
12379                                   TargetLowering::DAGCombinerInfo &DCI,
12380                                   const ARMSubtarget *Subtarget) {
12381   // Only ARM and Thumb2 support UMLAL/SMLAL.
12382   if (Subtarget->isThumb1Only())
12383     return PerformAddeSubeCombine(N, DCI, Subtarget);
12384 
12385   // Only perform the checks after legalize when the pattern is available.
12386   if (DCI.isBeforeLegalize()) return SDValue();
12387 
12388   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
12389 }
12390 
12391 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
12392 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
12393 /// called with the default operands, and if that fails, with commuted
12394 /// operands.
12395 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
12396                                           TargetLowering::DAGCombinerInfo &DCI,
12397                                           const ARMSubtarget *Subtarget){
12398   // Attempt to create vpadd for this add.
12399   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
12400     return Result;
12401 
12402   // Attempt to create vpaddl for this add.
12403   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
12404     return Result;
12405   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
12406                                                       Subtarget))
12407     return Result;
12408 
12409   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12410   if (N0.getNode()->hasOneUse())
12411     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
12412       return Result;
12413   return SDValue();
12414 }
12415 
12416 static SDValue PerformADDVecReduce(SDNode *N,
12417                                    TargetLowering::DAGCombinerInfo &DCI,
12418                                    const ARMSubtarget *Subtarget) {
12419   if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
12420     return SDValue();
12421 
12422   SDValue N0 = N->getOperand(0);
12423   SDValue N1 = N->getOperand(1);
12424 
12425   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
12426   // will look like:
12427   //   t1: i32,i32 = ARMISD::VADDLVs x
12428   //   t2: i64 = build_pair t1, t1:1
12429   //   t3: i64 = add t2, y
12430   // We also need to check for sext / zext and commutitive adds.
12431   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
12432                            SDValue NB) {
12433     if (NB->getOpcode() != ISD::BUILD_PAIR)
12434       return SDValue();
12435     SDValue VecRed = NB->getOperand(0);
12436     if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
12437         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
12438       return SDValue();
12439 
12440     SDLoc dl(N);
12441     SmallVector<SDValue, 4> Ops;
12442     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12443                                   DCI.DAG.getConstant(0, dl, MVT::i32)));
12444     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12445                                   DCI.DAG.getConstant(1, dl, MVT::i32)));
12446     for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
12447       Ops.push_back(VecRed->getOperand(i));
12448     SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
12449                                   DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
12450     return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
12451                            SDValue(Red.getNode(), 1));
12452   };
12453 
12454   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
12455     return M;
12456   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
12457     return M;
12458   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
12459     return M;
12460   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
12461     return M;
12462   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
12463     return M;
12464   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
12465     return M;
12466   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
12467     return M;
12468   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
12469     return M;
12470   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
12471     return M;
12472   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
12473     return M;
12474   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
12475     return M;
12476   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
12477     return M;
12478   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
12479     return M;
12480   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
12481     return M;
12482   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
12483     return M;
12484   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
12485     return M;
12486   return SDValue();
12487 }
12488 
12489 bool
12490 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
12491                                                  CombineLevel Level) const {
12492   if (Level == BeforeLegalizeTypes)
12493     return true;
12494 
12495   if (N->getOpcode() != ISD::SHL)
12496     return true;
12497 
12498   if (Subtarget->isThumb1Only()) {
12499     // Avoid making expensive immediates by commuting shifts. (This logic
12500     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
12501     // for free.)
12502     if (N->getOpcode() != ISD::SHL)
12503       return true;
12504     SDValue N1 = N->getOperand(0);
12505     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
12506         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
12507       return true;
12508     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
12509       if (Const->getAPIntValue().ult(256))
12510         return false;
12511       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
12512           Const->getAPIntValue().sgt(-256))
12513         return false;
12514     }
12515     return true;
12516   }
12517 
12518   // Turn off commute-with-shift transform after legalization, so it doesn't
12519   // conflict with PerformSHLSimplify.  (We could try to detect when
12520   // PerformSHLSimplify would trigger more precisely, but it isn't
12521   // really necessary.)
12522   return false;
12523 }
12524 
12525 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
12526     const SDNode *N, CombineLevel Level) const {
12527   if (!Subtarget->isThumb1Only())
12528     return true;
12529 
12530   if (Level == BeforeLegalizeTypes)
12531     return true;
12532 
12533   return false;
12534 }
12535 
12536 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12537   if (!Subtarget->hasNEON()) {
12538     if (Subtarget->isThumb1Only())
12539       return VT.getScalarSizeInBits() <= 32;
12540     return true;
12541   }
12542   return VT.isScalarInteger();
12543 }
12544 
12545 static SDValue PerformSHLSimplify(SDNode *N,
12546                                 TargetLowering::DAGCombinerInfo &DCI,
12547                                 const ARMSubtarget *ST) {
12548   // Allow the generic combiner to identify potential bswaps.
12549   if (DCI.isBeforeLegalize())
12550     return SDValue();
12551 
12552   // DAG combiner will fold:
12553   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
12554   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
12555   // Other code patterns that can be also be modified have the following form:
12556   // b + ((a << 1) | 510)
12557   // b + ((a << 1) & 510)
12558   // b + ((a << 1) ^ 510)
12559   // b + ((a << 1) + 510)
12560 
12561   // Many instructions can  perform the shift for free, but it requires both
12562   // the operands to be registers. If c1 << c2 is too large, a mov immediate
12563   // instruction will needed. So, unfold back to the original pattern if:
12564   // - if c1 and c2 are small enough that they don't require mov imms.
12565   // - the user(s) of the node can perform an shl
12566 
12567   // No shifted operands for 16-bit instructions.
12568   if (ST->isThumb() && ST->isThumb1Only())
12569     return SDValue();
12570 
12571   // Check that all the users could perform the shl themselves.
12572   for (auto U : N->uses()) {
12573     switch(U->getOpcode()) {
12574     default:
12575       return SDValue();
12576     case ISD::SUB:
12577     case ISD::ADD:
12578     case ISD::AND:
12579     case ISD::OR:
12580     case ISD::XOR:
12581     case ISD::SETCC:
12582     case ARMISD::CMP:
12583       // Check that the user isn't already using a constant because there
12584       // aren't any instructions that support an immediate operand and a
12585       // shifted operand.
12586       if (isa<ConstantSDNode>(U->getOperand(0)) ||
12587           isa<ConstantSDNode>(U->getOperand(1)))
12588         return SDValue();
12589 
12590       // Check that it's not already using a shift.
12591       if (U->getOperand(0).getOpcode() == ISD::SHL ||
12592           U->getOperand(1).getOpcode() == ISD::SHL)
12593         return SDValue();
12594       break;
12595     }
12596   }
12597 
12598   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
12599       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
12600     return SDValue();
12601 
12602   if (N->getOperand(0).getOpcode() != ISD::SHL)
12603     return SDValue();
12604 
12605   SDValue SHL = N->getOperand(0);
12606 
12607   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
12608   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
12609   if (!C1ShlC2 || !C2)
12610     return SDValue();
12611 
12612   APInt C2Int = C2->getAPIntValue();
12613   APInt C1Int = C1ShlC2->getAPIntValue();
12614 
12615   // Check that performing a lshr will not lose any information.
12616   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
12617                                      C2Int.getBitWidth() - C2->getZExtValue());
12618   if ((C1Int & Mask) != C1Int)
12619     return SDValue();
12620 
12621   // Shift the first constant.
12622   C1Int.lshrInPlace(C2Int);
12623 
12624   // The immediates are encoded as an 8-bit value that can be rotated.
12625   auto LargeImm = [](const APInt &Imm) {
12626     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
12627     return Imm.getBitWidth() - Zeros > 8;
12628   };
12629 
12630   if (LargeImm(C1Int) || LargeImm(C2Int))
12631     return SDValue();
12632 
12633   SelectionDAG &DAG = DCI.DAG;
12634   SDLoc dl(N);
12635   SDValue X = SHL.getOperand(0);
12636   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
12637                               DAG.getConstant(C1Int, dl, MVT::i32));
12638   // Shift left to compensate for the lshr of C1Int.
12639   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
12640 
12641   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
12642              SHL.dump(); N->dump());
12643   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
12644   return Res;
12645 }
12646 
12647 
12648 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12649 ///
12650 static SDValue PerformADDCombine(SDNode *N,
12651                                  TargetLowering::DAGCombinerInfo &DCI,
12652                                  const ARMSubtarget *Subtarget) {
12653   SDValue N0 = N->getOperand(0);
12654   SDValue N1 = N->getOperand(1);
12655 
12656   // Only works one way, because it needs an immediate operand.
12657   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12658     return Result;
12659 
12660   if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12661     return Result;
12662 
12663   // First try with the default operand order.
12664   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12665     return Result;
12666 
12667   // If that didn't work, try again with the operands commuted.
12668   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12669 }
12670 
12671 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12672 ///
12673 static SDValue PerformSUBCombine(SDNode *N,
12674                                  TargetLowering::DAGCombinerInfo &DCI,
12675                                  const ARMSubtarget *Subtarget) {
12676   SDValue N0 = N->getOperand(0);
12677   SDValue N1 = N->getOperand(1);
12678 
12679   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12680   if (N1.getNode()->hasOneUse())
12681     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12682       return Result;
12683 
12684   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12685     return SDValue();
12686 
12687   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12688   // so that we can readily pattern match more mve instructions which can use
12689   // a scalar operand.
12690   SDValue VDup = N->getOperand(1);
12691   if (VDup->getOpcode() != ARMISD::VDUP)
12692     return SDValue();
12693 
12694   SDValue VMov = N->getOperand(0);
12695   if (VMov->getOpcode() == ISD::BITCAST)
12696     VMov = VMov->getOperand(0);
12697 
12698   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12699     return SDValue();
12700 
12701   SDLoc dl(N);
12702   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12703                                    DCI.DAG.getConstant(0, dl, MVT::i32),
12704                                    VDup->getOperand(0));
12705   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12706 }
12707 
12708 /// PerformVMULCombine
12709 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12710 /// special multiplier accumulator forwarding.
12711 ///   vmul d3, d0, d2
12712 ///   vmla d3, d1, d2
12713 /// is faster than
12714 ///   vadd d3, d0, d1
12715 ///   vmul d3, d3, d2
12716 //  However, for (A + B) * (A + B),
12717 //    vadd d2, d0, d1
12718 //    vmul d3, d0, d2
12719 //    vmla d3, d1, d2
12720 //  is slower than
12721 //    vadd d2, d0, d1
12722 //    vmul d3, d2, d2
12723 static SDValue PerformVMULCombine(SDNode *N,
12724                                   TargetLowering::DAGCombinerInfo &DCI,
12725                                   const ARMSubtarget *Subtarget) {
12726   if (!Subtarget->hasVMLxForwarding())
12727     return SDValue();
12728 
12729   SelectionDAG &DAG = DCI.DAG;
12730   SDValue N0 = N->getOperand(0);
12731   SDValue N1 = N->getOperand(1);
12732   unsigned Opcode = N0.getOpcode();
12733   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12734       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12735     Opcode = N1.getOpcode();
12736     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12737         Opcode != ISD::FADD && Opcode != ISD::FSUB)
12738       return SDValue();
12739     std::swap(N0, N1);
12740   }
12741 
12742   if (N0 == N1)
12743     return SDValue();
12744 
12745   EVT VT = N->getValueType(0);
12746   SDLoc DL(N);
12747   SDValue N00 = N0->getOperand(0);
12748   SDValue N01 = N0->getOperand(1);
12749   return DAG.getNode(Opcode, DL, VT,
12750                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12751                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12752 }
12753 
12754 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12755                                       const ARMSubtarget *Subtarget) {
12756   EVT VT = N->getValueType(0);
12757   if (VT != MVT::v2i64)
12758     return SDValue();
12759 
12760   SDValue N0 = N->getOperand(0);
12761   SDValue N1 = N->getOperand(1);
12762 
12763   auto IsSignExt = [&](SDValue Op) {
12764     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12765       return SDValue();
12766     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12767     if (VT.getScalarSizeInBits() == 32)
12768       return Op->getOperand(0);
12769     return SDValue();
12770   };
12771   auto IsZeroExt = [&](SDValue Op) {
12772     // Zero extends are a little more awkward. At the point we are matching
12773     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12774     // That might be before of after a bitcast depending on how the and is
12775     // placed. Because this has to look through bitcasts, it is currently only
12776     // supported on LE.
12777     if (!Subtarget->isLittle())
12778       return SDValue();
12779 
12780     SDValue And = Op;
12781     if (And->getOpcode() == ISD::BITCAST)
12782       And = And->getOperand(0);
12783     if (And->getOpcode() != ISD::AND)
12784       return SDValue();
12785     SDValue Mask = And->getOperand(1);
12786     if (Mask->getOpcode() == ISD::BITCAST)
12787       Mask = Mask->getOperand(0);
12788 
12789     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12790         Mask.getValueType() != MVT::v4i32)
12791       return SDValue();
12792     if (isAllOnesConstant(Mask->getOperand(0)) &&
12793         isNullConstant(Mask->getOperand(1)) &&
12794         isAllOnesConstant(Mask->getOperand(2)) &&
12795         isNullConstant(Mask->getOperand(3)))
12796       return And->getOperand(0);
12797     return SDValue();
12798   };
12799 
12800   SDLoc dl(N);
12801   if (SDValue Op0 = IsSignExt(N0)) {
12802     if (SDValue Op1 = IsSignExt(N1)) {
12803       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12804       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12805       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12806     }
12807   }
12808   if (SDValue Op0 = IsZeroExt(N0)) {
12809     if (SDValue Op1 = IsZeroExt(N1)) {
12810       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12811       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12812       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12813     }
12814   }
12815 
12816   return SDValue();
12817 }
12818 
12819 static SDValue PerformMULCombine(SDNode *N,
12820                                  TargetLowering::DAGCombinerInfo &DCI,
12821                                  const ARMSubtarget *Subtarget) {
12822   SelectionDAG &DAG = DCI.DAG;
12823 
12824   EVT VT = N->getValueType(0);
12825   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12826     return PerformMVEVMULLCombine(N, DAG, Subtarget);
12827 
12828   if (Subtarget->isThumb1Only())
12829     return SDValue();
12830 
12831   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12832     return SDValue();
12833 
12834   if (VT.is64BitVector() || VT.is128BitVector())
12835     return PerformVMULCombine(N, DCI, Subtarget);
12836   if (VT != MVT::i32)
12837     return SDValue();
12838 
12839   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12840   if (!C)
12841     return SDValue();
12842 
12843   int64_t MulAmt = C->getSExtValue();
12844   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12845 
12846   ShiftAmt = ShiftAmt & (32 - 1);
12847   SDValue V = N->getOperand(0);
12848   SDLoc DL(N);
12849 
12850   SDValue Res;
12851   MulAmt >>= ShiftAmt;
12852 
12853   if (MulAmt >= 0) {
12854     if (isPowerOf2_32(MulAmt - 1)) {
12855       // (mul x, 2^N + 1) => (add (shl x, N), x)
12856       Res = DAG.getNode(ISD::ADD, DL, VT,
12857                         V,
12858                         DAG.getNode(ISD::SHL, DL, VT,
12859                                     V,
12860                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
12861                                                     MVT::i32)));
12862     } else if (isPowerOf2_32(MulAmt + 1)) {
12863       // (mul x, 2^N - 1) => (sub (shl x, N), x)
12864       Res = DAG.getNode(ISD::SUB, DL, VT,
12865                         DAG.getNode(ISD::SHL, DL, VT,
12866                                     V,
12867                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
12868                                                     MVT::i32)),
12869                         V);
12870     } else
12871       return SDValue();
12872   } else {
12873     uint64_t MulAmtAbs = -MulAmt;
12874     if (isPowerOf2_32(MulAmtAbs + 1)) {
12875       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12876       Res = DAG.getNode(ISD::SUB, DL, VT,
12877                         V,
12878                         DAG.getNode(ISD::SHL, DL, VT,
12879                                     V,
12880                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12881                                                     MVT::i32)));
12882     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12883       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12884       Res = DAG.getNode(ISD::ADD, DL, VT,
12885                         V,
12886                         DAG.getNode(ISD::SHL, DL, VT,
12887                                     V,
12888                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12889                                                     MVT::i32)));
12890       Res = DAG.getNode(ISD::SUB, DL, VT,
12891                         DAG.getConstant(0, DL, MVT::i32), Res);
12892     } else
12893       return SDValue();
12894   }
12895 
12896   if (ShiftAmt != 0)
12897     Res = DAG.getNode(ISD::SHL, DL, VT,
12898                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12899 
12900   // Do not add new nodes to DAG combiner worklist.
12901   DCI.CombineTo(N, Res, false);
12902   return SDValue();
12903 }
12904 
12905 static SDValue CombineANDShift(SDNode *N,
12906                                TargetLowering::DAGCombinerInfo &DCI,
12907                                const ARMSubtarget *Subtarget) {
12908   // Allow DAGCombine to pattern-match before we touch the canonical form.
12909   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12910     return SDValue();
12911 
12912   if (N->getValueType(0) != MVT::i32)
12913     return SDValue();
12914 
12915   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12916   if (!N1C)
12917     return SDValue();
12918 
12919   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12920   // Don't transform uxtb/uxth.
12921   if (C1 == 255 || C1 == 65535)
12922     return SDValue();
12923 
12924   SDNode *N0 = N->getOperand(0).getNode();
12925   if (!N0->hasOneUse())
12926     return SDValue();
12927 
12928   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12929     return SDValue();
12930 
12931   bool LeftShift = N0->getOpcode() == ISD::SHL;
12932 
12933   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12934   if (!N01C)
12935     return SDValue();
12936 
12937   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12938   if (!C2 || C2 >= 32)
12939     return SDValue();
12940 
12941   // Clear irrelevant bits in the mask.
12942   if (LeftShift)
12943     C1 &= (-1U << C2);
12944   else
12945     C1 &= (-1U >> C2);
12946 
12947   SelectionDAG &DAG = DCI.DAG;
12948   SDLoc DL(N);
12949 
12950   // We have a pattern of the form "(and (shl x, c2) c1)" or
12951   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12952   // transform to a pair of shifts, to save materializing c1.
12953 
12954   // First pattern: right shift, then mask off leading bits.
12955   // FIXME: Use demanded bits?
12956   if (!LeftShift && isMask_32(C1)) {
12957     uint32_t C3 = countLeadingZeros(C1);
12958     if (C2 < C3) {
12959       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12960                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12961       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12962                          DAG.getConstant(C3, DL, MVT::i32));
12963     }
12964   }
12965 
12966   // First pattern, reversed: left shift, then mask off trailing bits.
12967   if (LeftShift && isMask_32(~C1)) {
12968     uint32_t C3 = countTrailingZeros(C1);
12969     if (C2 < C3) {
12970       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12971                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12972       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12973                          DAG.getConstant(C3, DL, MVT::i32));
12974     }
12975   }
12976 
12977   // Second pattern: left shift, then mask off leading bits.
12978   // FIXME: Use demanded bits?
12979   if (LeftShift && isShiftedMask_32(C1)) {
12980     uint32_t Trailing = countTrailingZeros(C1);
12981     uint32_t C3 = countLeadingZeros(C1);
12982     if (Trailing == C2 && C2 + C3 < 32) {
12983       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12984                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12985       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12986                         DAG.getConstant(C3, DL, MVT::i32));
12987     }
12988   }
12989 
12990   // Second pattern, reversed: right shift, then mask off trailing bits.
12991   // FIXME: Handle other patterns of known/demanded bits.
12992   if (!LeftShift && isShiftedMask_32(C1)) {
12993     uint32_t Leading = countLeadingZeros(C1);
12994     uint32_t C3 = countTrailingZeros(C1);
12995     if (Leading == C2 && C2 + C3 < 32) {
12996       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12997                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12998       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12999                          DAG.getConstant(C3, DL, MVT::i32));
13000     }
13001   }
13002 
13003   // FIXME: Transform "(and (shl x, c2) c1)" ->
13004   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
13005   // c1.
13006   return SDValue();
13007 }
13008 
13009 static SDValue PerformANDCombine(SDNode *N,
13010                                  TargetLowering::DAGCombinerInfo &DCI,
13011                                  const ARMSubtarget *Subtarget) {
13012   // Attempt to use immediate-form VBIC
13013   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13014   SDLoc dl(N);
13015   EVT VT = N->getValueType(0);
13016   SelectionDAG &DAG = DCI.DAG;
13017 
13018   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
13019       VT == MVT::v8i1 || VT == MVT::v16i1)
13020     return SDValue();
13021 
13022   APInt SplatBits, SplatUndef;
13023   unsigned SplatBitSize;
13024   bool HasAnyUndefs;
13025   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13026       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13027     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13028         SplatBitSize == 64) {
13029       EVT VbicVT;
13030       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
13031                                       SplatUndef.getZExtValue(), SplatBitSize,
13032                                       DAG, dl, VbicVT, VT, OtherModImm);
13033       if (Val.getNode()) {
13034         SDValue Input =
13035           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
13036         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
13037         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
13038       }
13039     }
13040   }
13041 
13042   if (!Subtarget->isThumb1Only()) {
13043     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
13044     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
13045       return Result;
13046 
13047     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13048       return Result;
13049   }
13050 
13051   if (Subtarget->isThumb1Only())
13052     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
13053       return Result;
13054 
13055   return SDValue();
13056 }
13057 
13058 // Try combining OR nodes to SMULWB, SMULWT.
13059 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
13060                                          TargetLowering::DAGCombinerInfo &DCI,
13061                                          const ARMSubtarget *Subtarget) {
13062   if (!Subtarget->hasV6Ops() ||
13063       (Subtarget->isThumb() &&
13064        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
13065     return SDValue();
13066 
13067   SDValue SRL = OR->getOperand(0);
13068   SDValue SHL = OR->getOperand(1);
13069 
13070   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
13071     SRL = OR->getOperand(1);
13072     SHL = OR->getOperand(0);
13073   }
13074   if (!isSRL16(SRL) || !isSHL16(SHL))
13075     return SDValue();
13076 
13077   // The first operands to the shifts need to be the two results from the
13078   // same smul_lohi node.
13079   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
13080        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
13081     return SDValue();
13082 
13083   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
13084   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
13085       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
13086     return SDValue();
13087 
13088   // Now we have:
13089   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
13090   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
13091   // For SMUWB the 16-bit value will signed extended somehow.
13092   // For SMULWT only the SRA is required.
13093   // Check both sides of SMUL_LOHI
13094   SDValue OpS16 = SMULLOHI->getOperand(0);
13095   SDValue OpS32 = SMULLOHI->getOperand(1);
13096 
13097   SelectionDAG &DAG = DCI.DAG;
13098   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
13099     OpS16 = OpS32;
13100     OpS32 = SMULLOHI->getOperand(0);
13101   }
13102 
13103   SDLoc dl(OR);
13104   unsigned Opcode = 0;
13105   if (isS16(OpS16, DAG))
13106     Opcode = ARMISD::SMULWB;
13107   else if (isSRA16(OpS16)) {
13108     Opcode = ARMISD::SMULWT;
13109     OpS16 = OpS16->getOperand(0);
13110   }
13111   else
13112     return SDValue();
13113 
13114   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
13115   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
13116   return SDValue(OR, 0);
13117 }
13118 
13119 static SDValue PerformORCombineToBFI(SDNode *N,
13120                                      TargetLowering::DAGCombinerInfo &DCI,
13121                                      const ARMSubtarget *Subtarget) {
13122   // BFI is only available on V6T2+
13123   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
13124     return SDValue();
13125 
13126   EVT VT = N->getValueType(0);
13127   SDValue N0 = N->getOperand(0);
13128   SDValue N1 = N->getOperand(1);
13129   SelectionDAG &DAG = DCI.DAG;
13130   SDLoc DL(N);
13131   // 1) or (and A, mask), val => ARMbfi A, val, mask
13132   //      iff (val & mask) == val
13133   //
13134   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13135   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
13136   //          && mask == ~mask2
13137   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
13138   //          && ~mask == mask2
13139   //  (i.e., copy a bitfield value into another bitfield of the same width)
13140 
13141   if (VT != MVT::i32)
13142     return SDValue();
13143 
13144   SDValue N00 = N0.getOperand(0);
13145 
13146   // The value and the mask need to be constants so we can verify this is
13147   // actually a bitfield set. If the mask is 0xffff, we can do better
13148   // via a movt instruction, so don't use BFI in that case.
13149   SDValue MaskOp = N0.getOperand(1);
13150   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
13151   if (!MaskC)
13152     return SDValue();
13153   unsigned Mask = MaskC->getZExtValue();
13154   if (Mask == 0xffff)
13155     return SDValue();
13156   SDValue Res;
13157   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
13158   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13159   if (N1C) {
13160     unsigned Val = N1C->getZExtValue();
13161     if ((Val & ~Mask) != Val)
13162       return SDValue();
13163 
13164     if (ARM::isBitFieldInvertedMask(Mask)) {
13165       Val >>= countTrailingZeros(~Mask);
13166 
13167       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
13168                         DAG.getConstant(Val, DL, MVT::i32),
13169                         DAG.getConstant(Mask, DL, MVT::i32));
13170 
13171       DCI.CombineTo(N, Res, false);
13172       // Return value from the original node to inform the combiner than N is
13173       // now dead.
13174       return SDValue(N, 0);
13175     }
13176   } else if (N1.getOpcode() == ISD::AND) {
13177     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13178     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13179     if (!N11C)
13180       return SDValue();
13181     unsigned Mask2 = N11C->getZExtValue();
13182 
13183     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
13184     // as is to match.
13185     if (ARM::isBitFieldInvertedMask(Mask) &&
13186         (Mask == ~Mask2)) {
13187       // The pack halfword instruction works better for masks that fit it,
13188       // so use that when it's available.
13189       if (Subtarget->hasDSP() &&
13190           (Mask == 0xffff || Mask == 0xffff0000))
13191         return SDValue();
13192       // 2a
13193       unsigned amt = countTrailingZeros(Mask2);
13194       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
13195                         DAG.getConstant(amt, DL, MVT::i32));
13196       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
13197                         DAG.getConstant(Mask, DL, MVT::i32));
13198       DCI.CombineTo(N, Res, false);
13199       // Return value from the original node to inform the combiner than N is
13200       // now dead.
13201       return SDValue(N, 0);
13202     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
13203                (~Mask == Mask2)) {
13204       // The pack halfword instruction works better for masks that fit it,
13205       // so use that when it's available.
13206       if (Subtarget->hasDSP() &&
13207           (Mask2 == 0xffff || Mask2 == 0xffff0000))
13208         return SDValue();
13209       // 2b
13210       unsigned lsb = countTrailingZeros(Mask);
13211       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
13212                         DAG.getConstant(lsb, DL, MVT::i32));
13213       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
13214                         DAG.getConstant(Mask2, DL, MVT::i32));
13215       DCI.CombineTo(N, Res, false);
13216       // Return value from the original node to inform the combiner than N is
13217       // now dead.
13218       return SDValue(N, 0);
13219     }
13220   }
13221 
13222   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
13223       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
13224       ARM::isBitFieldInvertedMask(~Mask)) {
13225     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
13226     // where lsb(mask) == #shamt and masked bits of B are known zero.
13227     SDValue ShAmt = N00.getOperand(1);
13228     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
13229     unsigned LSB = countTrailingZeros(Mask);
13230     if (ShAmtC != LSB)
13231       return SDValue();
13232 
13233     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
13234                       DAG.getConstant(~Mask, DL, MVT::i32));
13235 
13236     DCI.CombineTo(N, Res, false);
13237     // Return value from the original node to inform the combiner than N is
13238     // now dead.
13239     return SDValue(N, 0);
13240   }
13241 
13242   return SDValue();
13243 }
13244 
13245 static bool isValidMVECond(unsigned CC, bool IsFloat) {
13246   switch (CC) {
13247   case ARMCC::EQ:
13248   case ARMCC::NE:
13249   case ARMCC::LE:
13250   case ARMCC::GT:
13251   case ARMCC::GE:
13252   case ARMCC::LT:
13253     return true;
13254   case ARMCC::HS:
13255   case ARMCC::HI:
13256     return !IsFloat;
13257   default:
13258     return false;
13259   };
13260 }
13261 
13262 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
13263   if (N->getOpcode() == ARMISD::VCMP)
13264     return (ARMCC::CondCodes)N->getConstantOperandVal(2);
13265   else if (N->getOpcode() == ARMISD::VCMPZ)
13266     return (ARMCC::CondCodes)N->getConstantOperandVal(1);
13267   else
13268     llvm_unreachable("Not a VCMP/VCMPZ!");
13269 }
13270 
13271 static bool CanInvertMVEVCMP(SDValue N) {
13272   ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
13273   return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
13274 }
13275 
13276 static SDValue PerformORCombine_i1(SDNode *N,
13277                                    TargetLowering::DAGCombinerInfo &DCI,
13278                                    const ARMSubtarget *Subtarget) {
13279   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
13280   // together with predicates
13281   EVT VT = N->getValueType(0);
13282   SDLoc DL(N);
13283   SDValue N0 = N->getOperand(0);
13284   SDValue N1 = N->getOperand(1);
13285 
13286   auto IsFreelyInvertable = [&](SDValue V) {
13287     if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
13288       return CanInvertMVEVCMP(V);
13289     return false;
13290   };
13291 
13292   // At least one operand must be freely invertable.
13293   if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
13294     return SDValue();
13295 
13296   SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT);
13297   SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT);
13298   SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
13299   return DCI.DAG.getLogicalNOT(DL, And, VT);
13300 }
13301 
13302 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
13303 static SDValue PerformORCombine(SDNode *N,
13304                                 TargetLowering::DAGCombinerInfo &DCI,
13305                                 const ARMSubtarget *Subtarget) {
13306   // Attempt to use immediate-form VORR
13307   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13308   SDLoc dl(N);
13309   EVT VT = N->getValueType(0);
13310   SelectionDAG &DAG = DCI.DAG;
13311 
13312   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13313     return SDValue();
13314 
13315   if (Subtarget->hasMVEIntegerOps() &&
13316       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
13317     return PerformORCombine_i1(N, DCI, Subtarget);
13318 
13319   APInt SplatBits, SplatUndef;
13320   unsigned SplatBitSize;
13321   bool HasAnyUndefs;
13322   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13323       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13324     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13325         SplatBitSize == 64) {
13326       EVT VorrVT;
13327       SDValue Val =
13328           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
13329                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
13330       if (Val.getNode()) {
13331         SDValue Input =
13332           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
13333         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
13334         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
13335       }
13336     }
13337   }
13338 
13339   if (!Subtarget->isThumb1Only()) {
13340     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
13341     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13342       return Result;
13343     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
13344       return Result;
13345   }
13346 
13347   SDValue N0 = N->getOperand(0);
13348   SDValue N1 = N->getOperand(1);
13349 
13350   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
13351   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
13352       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13353 
13354     // The code below optimizes (or (and X, Y), Z).
13355     // The AND operand needs to have a single user to make these optimizations
13356     // profitable.
13357     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
13358       return SDValue();
13359 
13360     APInt SplatUndef;
13361     unsigned SplatBitSize;
13362     bool HasAnyUndefs;
13363 
13364     APInt SplatBits0, SplatBits1;
13365     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
13366     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
13367     // Ensure that the second operand of both ands are constants
13368     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
13369                                       HasAnyUndefs) && !HasAnyUndefs) {
13370         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
13371                                           HasAnyUndefs) && !HasAnyUndefs) {
13372             // Ensure that the bit width of the constants are the same and that
13373             // the splat arguments are logical inverses as per the pattern we
13374             // are trying to simplify.
13375             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
13376                 SplatBits0 == ~SplatBits1) {
13377                 // Canonicalize the vector type to make instruction selection
13378                 // simpler.
13379                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
13380                 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
13381                                              N0->getOperand(1),
13382                                              N0->getOperand(0),
13383                                              N1->getOperand(0));
13384                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13385             }
13386         }
13387     }
13388   }
13389 
13390   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
13391   // reasonable.
13392   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
13393     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
13394       return Res;
13395   }
13396 
13397   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13398     return Result;
13399 
13400   return SDValue();
13401 }
13402 
13403 static SDValue PerformXORCombine(SDNode *N,
13404                                  TargetLowering::DAGCombinerInfo &DCI,
13405                                  const ARMSubtarget *Subtarget) {
13406   EVT VT = N->getValueType(0);
13407   SelectionDAG &DAG = DCI.DAG;
13408 
13409   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13410     return SDValue();
13411 
13412   if (!Subtarget->isThumb1Only()) {
13413     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
13414     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13415       return Result;
13416 
13417     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13418       return Result;
13419   }
13420 
13421   if (Subtarget->hasMVEIntegerOps()) {
13422     // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
13423     SDValue N0 = N->getOperand(0);
13424     SDValue N1 = N->getOperand(1);
13425     const TargetLowering *TLI = Subtarget->getTargetLowering();
13426     if (TLI->isConstTrueVal(N1.getNode()) &&
13427         (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
13428       if (CanInvertMVEVCMP(N0)) {
13429         SDLoc DL(N0);
13430         ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
13431 
13432         SmallVector<SDValue, 4> Ops;
13433         Ops.push_back(N0->getOperand(0));
13434         if (N0->getOpcode() == ARMISD::VCMP)
13435           Ops.push_back(N0->getOperand(1));
13436         Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32));
13437         return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
13438       }
13439     }
13440   }
13441 
13442   return SDValue();
13443 }
13444 
13445 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
13446 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
13447 // their position in "to" (Rd).
13448 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
13449   assert(N->getOpcode() == ARMISD::BFI);
13450 
13451   SDValue From = N->getOperand(1);
13452   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
13453   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
13454 
13455   // If the Base came from a SHR #C, we can deduce that it is really testing bit
13456   // #C in the base of the SHR.
13457   if (From->getOpcode() == ISD::SRL &&
13458       isa<ConstantSDNode>(From->getOperand(1))) {
13459     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
13460     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
13461     FromMask <<= Shift.getLimitedValue(31);
13462     From = From->getOperand(0);
13463   }
13464 
13465   return From;
13466 }
13467 
13468 // If A and B contain one contiguous set of bits, does A | B == A . B?
13469 //
13470 // Neither A nor B must be zero.
13471 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
13472   unsigned LastActiveBitInA =  A.countTrailingZeros();
13473   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
13474   return LastActiveBitInA - 1 == FirstActiveBitInB;
13475 }
13476 
13477 static SDValue FindBFIToCombineWith(SDNode *N) {
13478   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
13479   // if one exists.
13480   APInt ToMask, FromMask;
13481   SDValue From = ParseBFI(N, ToMask, FromMask);
13482   SDValue To = N->getOperand(0);
13483 
13484   // Now check for a compatible BFI to merge with. We can pass through BFIs that
13485   // aren't compatible, but not if they set the same bit in their destination as
13486   // we do (or that of any BFI we're going to combine with).
13487   SDValue V = To;
13488   APInt CombinedToMask = ToMask;
13489   while (V.getOpcode() == ARMISD::BFI) {
13490     APInt NewToMask, NewFromMask;
13491     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
13492     if (NewFrom != From) {
13493       // This BFI has a different base. Keep going.
13494       CombinedToMask |= NewToMask;
13495       V = V.getOperand(0);
13496       continue;
13497     }
13498 
13499     // Do the written bits conflict with any we've seen so far?
13500     if ((NewToMask & CombinedToMask).getBoolValue())
13501       // Conflicting bits - bail out because going further is unsafe.
13502       return SDValue();
13503 
13504     // Are the new bits contiguous when combined with the old bits?
13505     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
13506         BitsProperlyConcatenate(FromMask, NewFromMask))
13507       return V;
13508     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
13509         BitsProperlyConcatenate(NewFromMask, FromMask))
13510       return V;
13511 
13512     // We've seen a write to some bits, so track it.
13513     CombinedToMask |= NewToMask;
13514     // Keep going...
13515     V = V.getOperand(0);
13516   }
13517 
13518   return SDValue();
13519 }
13520 
13521 static SDValue PerformBFICombine(SDNode *N,
13522                                  TargetLowering::DAGCombinerInfo &DCI) {
13523   SDValue N1 = N->getOperand(1);
13524   if (N1.getOpcode() == ISD::AND) {
13525     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
13526     // the bits being cleared by the AND are not demanded by the BFI.
13527     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13528     if (!N11C)
13529       return SDValue();
13530     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13531     unsigned LSB = countTrailingZeros(~InvMask);
13532     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
13533     assert(Width <
13534                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
13535            "undefined behavior");
13536     unsigned Mask = (1u << Width) - 1;
13537     unsigned Mask2 = N11C->getZExtValue();
13538     if ((Mask & (~Mask2)) == 0)
13539       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
13540                              N->getOperand(0), N1.getOperand(0),
13541                              N->getOperand(2));
13542   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
13543     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
13544     // Keep track of any consecutive bits set that all come from the same base
13545     // value. We can combine these together into a single BFI.
13546     SDValue CombineBFI = FindBFIToCombineWith(N);
13547     if (CombineBFI == SDValue())
13548       return SDValue();
13549 
13550     // We've found a BFI.
13551     APInt ToMask1, FromMask1;
13552     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
13553 
13554     APInt ToMask2, FromMask2;
13555     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
13556     assert(From1 == From2);
13557     (void)From2;
13558 
13559     // First, unlink CombineBFI.
13560     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
13561     // Then create a new BFI, combining the two together.
13562     APInt NewFromMask = FromMask1 | FromMask2;
13563     APInt NewToMask = ToMask1 | ToMask2;
13564 
13565     EVT VT = N->getValueType(0);
13566     SDLoc dl(N);
13567 
13568     if (NewFromMask[0] == 0)
13569       From1 = DCI.DAG.getNode(
13570         ISD::SRL, dl, VT, From1,
13571         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
13572     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
13573                            DCI.DAG.getConstant(~NewToMask, dl, VT));
13574   }
13575   return SDValue();
13576 }
13577 
13578 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
13579 /// ARMISD::VMOVRRD.
13580 static SDValue PerformVMOVRRDCombine(SDNode *N,
13581                                      TargetLowering::DAGCombinerInfo &DCI,
13582                                      const ARMSubtarget *Subtarget) {
13583   // vmovrrd(vmovdrr x, y) -> x,y
13584   SDValue InDouble = N->getOperand(0);
13585   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
13586     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
13587 
13588   // vmovrrd(load f64) -> (load i32), (load i32)
13589   SDNode *InNode = InDouble.getNode();
13590   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
13591       InNode->getValueType(0) == MVT::f64 &&
13592       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
13593       !cast<LoadSDNode>(InNode)->isVolatile()) {
13594     // TODO: Should this be done for non-FrameIndex operands?
13595     LoadSDNode *LD = cast<LoadSDNode>(InNode);
13596 
13597     SelectionDAG &DAG = DCI.DAG;
13598     SDLoc DL(LD);
13599     SDValue BasePtr = LD->getBasePtr();
13600     SDValue NewLD1 =
13601         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
13602                     LD->getAlignment(), LD->getMemOperand()->getFlags());
13603 
13604     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13605                                     DAG.getConstant(4, DL, MVT::i32));
13606 
13607     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
13608                                  LD->getPointerInfo().getWithOffset(4),
13609                                  std::min(4U, LD->getAlignment()),
13610                                  LD->getMemOperand()->getFlags());
13611 
13612     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
13613     if (DCI.DAG.getDataLayout().isBigEndian())
13614       std::swap (NewLD1, NewLD2);
13615     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
13616     return Result;
13617   }
13618 
13619   return SDValue();
13620 }
13621 
13622 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
13623 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
13624 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
13625   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
13626   SDValue Op0 = N->getOperand(0);
13627   SDValue Op1 = N->getOperand(1);
13628   if (Op0.getOpcode() == ISD::BITCAST)
13629     Op0 = Op0.getOperand(0);
13630   if (Op1.getOpcode() == ISD::BITCAST)
13631     Op1 = Op1.getOperand(0);
13632   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
13633       Op0.getNode() == Op1.getNode() &&
13634       Op0.getResNo() == 0 && Op1.getResNo() == 1)
13635     return DAG.getNode(ISD::BITCAST, SDLoc(N),
13636                        N->getValueType(0), Op0.getOperand(0));
13637   return SDValue();
13638 }
13639 
13640 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13641   SDValue Op0 = N->getOperand(0);
13642 
13643   // VMOVhr (VMOVrh (X)) -> X
13644   if (Op0->getOpcode() == ARMISD::VMOVrh)
13645     return Op0->getOperand(0);
13646 
13647   // FullFP16: half values are passed in S-registers, and we don't
13648   // need any of the bitcast and moves:
13649   //
13650   //     t2: f32,ch = CopyFromReg t0, Register:f32 %0
13651   //   t5: i32 = bitcast t2
13652   // t18: f16 = ARMISD::VMOVhr t5
13653   if (Op0->getOpcode() == ISD::BITCAST) {
13654     SDValue Copy = Op0->getOperand(0);
13655     if (Copy.getValueType() == MVT::f32 &&
13656         Copy->getOpcode() == ISD::CopyFromReg) {
13657       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
13658       SDValue NewCopy =
13659           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
13660       return NewCopy;
13661     }
13662   }
13663 
13664   // fold (VMOVhr (load x)) -> (load (f16*)x)
13665   if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
13666     if (LN0->hasOneUse() && LN0->isUnindexed() &&
13667         LN0->getMemoryVT() == MVT::i16) {
13668       SDValue Load =
13669           DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
13670                           LN0->getBasePtr(), LN0->getMemOperand());
13671       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13672       DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
13673       return Load;
13674     }
13675   }
13676 
13677   // Only the bottom 16 bits of the source register are used.
13678   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13679   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13680   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13681     return SDValue(N, 0);
13682 
13683   return SDValue();
13684 }
13685 
13686 static SDValue PerformVMOVrhCombine(SDNode *N,
13687                                     TargetLowering::DAGCombinerInfo &DCI) {
13688   SDValue N0 = N->getOperand(0);
13689   EVT VT = N->getValueType(0);
13690 
13691   // fold (VMOVrh (fpconst x)) -> const x
13692   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
13693     APFloat V = C->getValueAPF();
13694     return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
13695   }
13696 
13697   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13698   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13699     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13700 
13701     SDValue Load =
13702         DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13703                            LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13704     DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13705     DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13706     return Load;
13707   }
13708 
13709   // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
13710   if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13711       isa<ConstantSDNode>(N0->getOperand(1)))
13712     return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
13713                            N0->getOperand(1));
13714 
13715   return SDValue();
13716 }
13717 
13718 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13719 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
13720 /// i64 vector to have f64 elements, since the value can then be loaded
13721 /// directly into a VFP register.
13722 static bool hasNormalLoadOperand(SDNode *N) {
13723   unsigned NumElts = N->getValueType(0).getVectorNumElements();
13724   for (unsigned i = 0; i < NumElts; ++i) {
13725     SDNode *Elt = N->getOperand(i).getNode();
13726     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13727       return true;
13728   }
13729   return false;
13730 }
13731 
13732 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13733 /// ISD::BUILD_VECTOR.
13734 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13735                                           TargetLowering::DAGCombinerInfo &DCI,
13736                                           const ARMSubtarget *Subtarget) {
13737   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13738   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
13739   // into a pair of GPRs, which is fine when the value is used as a scalar,
13740   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13741   SelectionDAG &DAG = DCI.DAG;
13742   if (N->getNumOperands() == 2)
13743     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13744       return RV;
13745 
13746   // Load i64 elements as f64 values so that type legalization does not split
13747   // them up into i32 values.
13748   EVT VT = N->getValueType(0);
13749   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13750     return SDValue();
13751   SDLoc dl(N);
13752   SmallVector<SDValue, 8> Ops;
13753   unsigned NumElts = VT.getVectorNumElements();
13754   for (unsigned i = 0; i < NumElts; ++i) {
13755     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13756     Ops.push_back(V);
13757     // Make the DAGCombiner fold the bitcast.
13758     DCI.AddToWorklist(V.getNode());
13759   }
13760   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13761   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13762   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13763 }
13764 
13765 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13766 static SDValue
13767 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13768   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13769   // At that time, we may have inserted bitcasts from integer to float.
13770   // If these bitcasts have survived DAGCombine, change the lowering of this
13771   // BUILD_VECTOR in something more vector friendly, i.e., that does not
13772   // force to use floating point types.
13773 
13774   // Make sure we can change the type of the vector.
13775   // This is possible iff:
13776   // 1. The vector is only used in a bitcast to a integer type. I.e.,
13777   //    1.1. Vector is used only once.
13778   //    1.2. Use is a bit convert to an integer type.
13779   // 2. The size of its operands are 32-bits (64-bits are not legal).
13780   EVT VT = N->getValueType(0);
13781   EVT EltVT = VT.getVectorElementType();
13782 
13783   // Check 1.1. and 2.
13784   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13785     return SDValue();
13786 
13787   // By construction, the input type must be float.
13788   assert(EltVT == MVT::f32 && "Unexpected type!");
13789 
13790   // Check 1.2.
13791   SDNode *Use = *N->use_begin();
13792   if (Use->getOpcode() != ISD::BITCAST ||
13793       Use->getValueType(0).isFloatingPoint())
13794     return SDValue();
13795 
13796   // Check profitability.
13797   // Model is, if more than half of the relevant operands are bitcast from
13798   // i32, turn the build_vector into a sequence of insert_vector_elt.
13799   // Relevant operands are everything that is not statically
13800   // (i.e., at compile time) bitcasted.
13801   unsigned NumOfBitCastedElts = 0;
13802   unsigned NumElts = VT.getVectorNumElements();
13803   unsigned NumOfRelevantElts = NumElts;
13804   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13805     SDValue Elt = N->getOperand(Idx);
13806     if (Elt->getOpcode() == ISD::BITCAST) {
13807       // Assume only bit cast to i32 will go away.
13808       if (Elt->getOperand(0).getValueType() == MVT::i32)
13809         ++NumOfBitCastedElts;
13810     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13811       // Constants are statically casted, thus do not count them as
13812       // relevant operands.
13813       --NumOfRelevantElts;
13814   }
13815 
13816   // Check if more than half of the elements require a non-free bitcast.
13817   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13818     return SDValue();
13819 
13820   SelectionDAG &DAG = DCI.DAG;
13821   // Create the new vector type.
13822   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13823   // Check if the type is legal.
13824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13825   if (!TLI.isTypeLegal(VecVT))
13826     return SDValue();
13827 
13828   // Combine:
13829   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13830   // => BITCAST INSERT_VECTOR_ELT
13831   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13832   //                      (BITCAST EN), N.
13833   SDValue Vec = DAG.getUNDEF(VecVT);
13834   SDLoc dl(N);
13835   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13836     SDValue V = N->getOperand(Idx);
13837     if (V.isUndef())
13838       continue;
13839     if (V.getOpcode() == ISD::BITCAST &&
13840         V->getOperand(0).getValueType() == MVT::i32)
13841       // Fold obvious case.
13842       V = V.getOperand(0);
13843     else {
13844       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13845       // Make the DAGCombiner fold the bitcasts.
13846       DCI.AddToWorklist(V.getNode());
13847     }
13848     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13849     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13850   }
13851   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13852   // Make the DAGCombiner fold the bitcasts.
13853   DCI.AddToWorklist(Vec.getNode());
13854   return Vec;
13855 }
13856 
13857 static SDValue
13858 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13859   EVT VT = N->getValueType(0);
13860   SDValue Op = N->getOperand(0);
13861   SDLoc dl(N);
13862 
13863   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13864   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13865     // If the valuetypes are the same, we can remove the cast entirely.
13866     if (Op->getOperand(0).getValueType() == VT)
13867       return Op->getOperand(0);
13868     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13869   }
13870 
13871   // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
13872   // more VPNOT which might get folded as else predicates.
13873   if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
13874     SDValue X =
13875         DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13876     SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
13877                                 DCI.DAG.getConstant(65535, dl, MVT::i32));
13878     return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
13879   }
13880 
13881   // Only the bottom 16 bits of the source register are used.
13882   if (Op.getValueType() == MVT::i32) {
13883     APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13884     const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13885     if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
13886       return SDValue(N, 0);
13887   }
13888   return SDValue();
13889 }
13890 
13891 static SDValue
13892 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13893                               const ARMSubtarget *ST) {
13894   EVT VT = N->getValueType(0);
13895   SDValue Op = N->getOperand(0);
13896   SDLoc dl(N);
13897 
13898   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13899   if (ST->isLittle())
13900     return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13901 
13902   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13903   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13904     // If the valuetypes are the same, we can remove the cast entirely.
13905     if (Op->getOperand(0).getValueType() == VT)
13906       return Op->getOperand(0);
13907     return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13908   }
13909 
13910   return SDValue();
13911 }
13912 
13913 static SDValue PerformVCMPCombine(SDNode *N,
13914                                   TargetLowering::DAGCombinerInfo &DCI,
13915                                   const ARMSubtarget *Subtarget) {
13916   if (!Subtarget->hasMVEIntegerOps())
13917     return SDValue();
13918 
13919   EVT VT = N->getValueType(0);
13920   SDValue Op0 = N->getOperand(0);
13921   SDValue Op1 = N->getOperand(1);
13922   ARMCC::CondCodes Cond =
13923       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13924   SDLoc dl(N);
13925 
13926   // vcmp X, 0, cc -> vcmpz X, cc
13927   if (isZeroVector(Op1))
13928     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13929                            N->getOperand(2));
13930 
13931   unsigned SwappedCond = getSwappedCondition(Cond);
13932   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13933     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13934     if (isZeroVector(Op0))
13935       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13936                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13937     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13938     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13939       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13940                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13941   }
13942 
13943   return SDValue();
13944 }
13945 
13946 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13947 /// ISD::INSERT_VECTOR_ELT.
13948 static SDValue PerformInsertEltCombine(SDNode *N,
13949                                        TargetLowering::DAGCombinerInfo &DCI) {
13950   // Bitcast an i64 load inserted into a vector to f64.
13951   // Otherwise, the i64 value will be legalized to a pair of i32 values.
13952   EVT VT = N->getValueType(0);
13953   SDNode *Elt = N->getOperand(1).getNode();
13954   if (VT.getVectorElementType() != MVT::i64 ||
13955       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13956     return SDValue();
13957 
13958   SelectionDAG &DAG = DCI.DAG;
13959   SDLoc dl(N);
13960   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13961                                  VT.getVectorNumElements());
13962   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13963   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13964   // Make the DAGCombiner fold the bitcasts.
13965   DCI.AddToWorklist(Vec.getNode());
13966   DCI.AddToWorklist(V.getNode());
13967   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13968                                Vec, V, N->getOperand(2));
13969   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13970 }
13971 
13972 static SDValue PerformExtractEltCombine(SDNode *N,
13973                                         TargetLowering::DAGCombinerInfo &DCI) {
13974   SDValue Op0 = N->getOperand(0);
13975   EVT VT = N->getValueType(0);
13976   SDLoc dl(N);
13977 
13978   // extract (vdup x) -> x
13979   if (Op0->getOpcode() == ARMISD::VDUP) {
13980     SDValue X = Op0->getOperand(0);
13981     if (VT == MVT::f16 && X.getValueType() == MVT::i32)
13982       return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
13983     if (VT == MVT::i32 && X.getValueType() == MVT::f16)
13984       return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
13985 
13986     while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
13987       X = X->getOperand(0);
13988     if (X.getValueType() == VT)
13989       return X;
13990   }
13991 
13992   return SDValue();
13993 }
13994 
13995 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13996 /// ISD::VECTOR_SHUFFLE.
13997 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13998   // The LLVM shufflevector instruction does not require the shuffle mask
13999   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
14000   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
14001   // operands do not match the mask length, they are extended by concatenating
14002   // them with undef vectors.  That is probably the right thing for other
14003   // targets, but for NEON it is better to concatenate two double-register
14004   // size vector operands into a single quad-register size vector.  Do that
14005   // transformation here:
14006   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
14007   //   shuffle(concat(v1, v2), undef)
14008   SDValue Op0 = N->getOperand(0);
14009   SDValue Op1 = N->getOperand(1);
14010   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
14011       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
14012       Op0.getNumOperands() != 2 ||
14013       Op1.getNumOperands() != 2)
14014     return SDValue();
14015   SDValue Concat0Op1 = Op0.getOperand(1);
14016   SDValue Concat1Op1 = Op1.getOperand(1);
14017   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
14018     return SDValue();
14019   // Skip the transformation if any of the types are illegal.
14020   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14021   EVT VT = N->getValueType(0);
14022   if (!TLI.isTypeLegal(VT) ||
14023       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
14024       !TLI.isTypeLegal(Concat1Op1.getValueType()))
14025     return SDValue();
14026 
14027   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
14028                                   Op0.getOperand(0), Op1.getOperand(0));
14029   // Translate the shuffle mask.
14030   SmallVector<int, 16> NewMask;
14031   unsigned NumElts = VT.getVectorNumElements();
14032   unsigned HalfElts = NumElts/2;
14033   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14034   for (unsigned n = 0; n < NumElts; ++n) {
14035     int MaskElt = SVN->getMaskElt(n);
14036     int NewElt = -1;
14037     if (MaskElt < (int)HalfElts)
14038       NewElt = MaskElt;
14039     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
14040       NewElt = HalfElts + MaskElt - NumElts;
14041     NewMask.push_back(NewElt);
14042   }
14043   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
14044                               DAG.getUNDEF(VT), NewMask);
14045 }
14046 
14047 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
14048 /// NEON load/store intrinsics, and generic vector load/stores, to merge
14049 /// base address updates.
14050 /// For generic load/stores, the memory type is assumed to be a vector.
14051 /// The caller is assumed to have checked legality.
14052 static SDValue CombineBaseUpdate(SDNode *N,
14053                                  TargetLowering::DAGCombinerInfo &DCI) {
14054   SelectionDAG &DAG = DCI.DAG;
14055   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
14056                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
14057   const bool isStore = N->getOpcode() == ISD::STORE;
14058   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
14059   SDValue Addr = N->getOperand(AddrOpIdx);
14060   MemSDNode *MemN = cast<MemSDNode>(N);
14061   SDLoc dl(N);
14062 
14063   // Search for a use of the address operand that is an increment.
14064   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14065          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
14066     SDNode *User = *UI;
14067     if (User->getOpcode() != ISD::ADD ||
14068         UI.getUse().getResNo() != Addr.getResNo())
14069       continue;
14070 
14071     // Check that the add is independent of the load/store.  Otherwise, folding
14072     // it would create a cycle. We can avoid searching through Addr as it's a
14073     // predecessor to both.
14074     SmallPtrSet<const SDNode *, 32> Visited;
14075     SmallVector<const SDNode *, 16> Worklist;
14076     Visited.insert(Addr.getNode());
14077     Worklist.push_back(N);
14078     Worklist.push_back(User);
14079     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14080         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14081       continue;
14082 
14083     // Find the new opcode for the updating load/store.
14084     bool isLoadOp = true;
14085     bool isLaneOp = false;
14086     unsigned NewOpc = 0;
14087     unsigned NumVecs = 0;
14088     if (isIntrinsic) {
14089       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14090       switch (IntNo) {
14091       default: llvm_unreachable("unexpected intrinsic for Neon base update");
14092       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
14093         NumVecs = 1; break;
14094       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
14095         NumVecs = 2; break;
14096       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
14097         NumVecs = 3; break;
14098       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
14099         NumVecs = 4; break;
14100       case Intrinsic::arm_neon_vld1x2:
14101       case Intrinsic::arm_neon_vld1x3:
14102       case Intrinsic::arm_neon_vld1x4:
14103       case Intrinsic::arm_neon_vld2dup:
14104       case Intrinsic::arm_neon_vld3dup:
14105       case Intrinsic::arm_neon_vld4dup:
14106         // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip
14107         // combining base updates for such intrinsics.
14108         continue;
14109       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
14110         NumVecs = 2; isLaneOp = true; break;
14111       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
14112         NumVecs = 3; isLaneOp = true; break;
14113       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
14114         NumVecs = 4; isLaneOp = true; break;
14115       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
14116         NumVecs = 1; isLoadOp = false; break;
14117       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
14118         NumVecs = 2; isLoadOp = false; break;
14119       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
14120         NumVecs = 3; isLoadOp = false; break;
14121       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
14122         NumVecs = 4; isLoadOp = false; break;
14123       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
14124         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
14125       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
14126         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
14127       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
14128         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
14129       }
14130     } else {
14131       isLaneOp = true;
14132       switch (N->getOpcode()) {
14133       default: llvm_unreachable("unexpected opcode for Neon base update");
14134       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
14135       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
14136       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
14137       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
14138       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
14139         NumVecs = 1; isLaneOp = false; break;
14140       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
14141         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
14142       }
14143     }
14144 
14145     // Find the size of memory referenced by the load/store.
14146     EVT VecTy;
14147     if (isLoadOp) {
14148       VecTy = N->getValueType(0);
14149     } else if (isIntrinsic) {
14150       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
14151     } else {
14152       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
14153       VecTy = N->getOperand(1).getValueType();
14154     }
14155 
14156     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14157     if (isLaneOp)
14158       NumBytes /= VecTy.getVectorNumElements();
14159 
14160     // If the increment is a constant, it must match the memory ref size.
14161     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14162     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14163     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
14164       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
14165       // separate instructions that make it harder to use a non-constant update.
14166       continue;
14167     }
14168 
14169     // OK, we found an ADD we can fold into the base update.
14170     // Now, create a _UPD node, taking care of not breaking alignment.
14171 
14172     EVT AlignedVecTy = VecTy;
14173     unsigned Alignment = MemN->getAlignment();
14174 
14175     // If this is a less-than-standard-aligned load/store, change the type to
14176     // match the standard alignment.
14177     // The alignment is overlooked when selecting _UPD variants; and it's
14178     // easier to introduce bitcasts here than fix that.
14179     // There are 3 ways to get to this base-update combine:
14180     // - intrinsics: they are assumed to be properly aligned (to the standard
14181     //   alignment of the memory type), so we don't need to do anything.
14182     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
14183     //   intrinsics, so, likewise, there's nothing to do.
14184     // - generic load/store instructions: the alignment is specified as an
14185     //   explicit operand, rather than implicitly as the standard alignment
14186     //   of the memory type (like the intrisics).  We need to change the
14187     //   memory type to match the explicit alignment.  That way, we don't
14188     //   generate non-standard-aligned ARMISD::VLDx nodes.
14189     if (isa<LSBaseSDNode>(N)) {
14190       if (Alignment == 0)
14191         Alignment = 1;
14192       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
14193         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
14194         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
14195         assert(!isLaneOp && "Unexpected generic load/store lane.");
14196         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
14197         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
14198       }
14199       // Don't set an explicit alignment on regular load/stores that we want
14200       // to transform to VLD/VST 1_UPD nodes.
14201       // This matches the behavior of regular load/stores, which only get an
14202       // explicit alignment if the MMO alignment is larger than the standard
14203       // alignment of the memory type.
14204       // Intrinsics, however, always get an explicit alignment, set to the
14205       // alignment of the MMO.
14206       Alignment = 1;
14207     }
14208 
14209     // Create the new updating load/store node.
14210     // First, create an SDVTList for the new updating node's results.
14211     EVT Tys[6];
14212     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14213     unsigned n;
14214     for (n = 0; n < NumResultVecs; ++n)
14215       Tys[n] = AlignedVecTy;
14216     Tys[n++] = MVT::i32;
14217     Tys[n] = MVT::Other;
14218     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
14219 
14220     // Then, gather the new node's operands.
14221     SmallVector<SDValue, 8> Ops;
14222     Ops.push_back(N->getOperand(0)); // incoming chain
14223     Ops.push_back(N->getOperand(AddrOpIdx));
14224     Ops.push_back(Inc);
14225 
14226     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
14227       // Try to match the intrinsic's signature
14228       Ops.push_back(StN->getValue());
14229     } else {
14230       // Loads (and of course intrinsics) match the intrinsics' signature,
14231       // so just add all but the alignment operand.
14232       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
14233         Ops.push_back(N->getOperand(i));
14234     }
14235 
14236     // For all node types, the alignment operand is always the last one.
14237     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
14238 
14239     // If this is a non-standard-aligned STORE, the penultimate operand is the
14240     // stored value.  Bitcast it to the aligned type.
14241     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
14242       SDValue &StVal = Ops[Ops.size()-2];
14243       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
14244     }
14245 
14246     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
14247     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
14248                                            MemN->getMemOperand());
14249 
14250     // Update the uses.
14251     SmallVector<SDValue, 5> NewResults;
14252     for (unsigned i = 0; i < NumResultVecs; ++i)
14253       NewResults.push_back(SDValue(UpdN.getNode(), i));
14254 
14255     // If this is an non-standard-aligned LOAD, the first result is the loaded
14256     // value.  Bitcast it to the expected result type.
14257     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
14258       SDValue &LdVal = NewResults[0];
14259       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
14260     }
14261 
14262     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
14263     DCI.CombineTo(N, NewResults);
14264     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14265 
14266     break;
14267   }
14268   return SDValue();
14269 }
14270 
14271 static SDValue PerformVLDCombine(SDNode *N,
14272                                  TargetLowering::DAGCombinerInfo &DCI) {
14273   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14274     return SDValue();
14275 
14276   return CombineBaseUpdate(N, DCI);
14277 }
14278 
14279 static SDValue PerformMVEVLDCombine(SDNode *N,
14280                                     TargetLowering::DAGCombinerInfo &DCI) {
14281   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14282     return SDValue();
14283 
14284   SelectionDAG &DAG = DCI.DAG;
14285   SDValue Addr = N->getOperand(2);
14286   MemSDNode *MemN = cast<MemSDNode>(N);
14287   SDLoc dl(N);
14288 
14289   // For the stores, where there are multiple intrinsics we only actually want
14290   // to post-inc the last of the them.
14291   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14292   if (IntNo == Intrinsic::arm_mve_vst2q &&
14293       cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
14294     return SDValue();
14295   if (IntNo == Intrinsic::arm_mve_vst4q &&
14296       cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
14297     return SDValue();
14298 
14299   // Search for a use of the address operand that is an increment.
14300   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14301                             UE = Addr.getNode()->use_end();
14302        UI != UE; ++UI) {
14303     SDNode *User = *UI;
14304     if (User->getOpcode() != ISD::ADD ||
14305         UI.getUse().getResNo() != Addr.getResNo())
14306       continue;
14307 
14308     // Check that the add is independent of the load/store.  Otherwise, folding
14309     // it would create a cycle. We can avoid searching through Addr as it's a
14310     // predecessor to both.
14311     SmallPtrSet<const SDNode *, 32> Visited;
14312     SmallVector<const SDNode *, 16> Worklist;
14313     Visited.insert(Addr.getNode());
14314     Worklist.push_back(N);
14315     Worklist.push_back(User);
14316     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14317         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14318       continue;
14319 
14320     // Find the new opcode for the updating load/store.
14321     bool isLoadOp = true;
14322     unsigned NewOpc = 0;
14323     unsigned NumVecs = 0;
14324     switch (IntNo) {
14325     default:
14326       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
14327     case Intrinsic::arm_mve_vld2q:
14328       NewOpc = ARMISD::VLD2_UPD;
14329       NumVecs = 2;
14330       break;
14331     case Intrinsic::arm_mve_vld4q:
14332       NewOpc = ARMISD::VLD4_UPD;
14333       NumVecs = 4;
14334       break;
14335     case Intrinsic::arm_mve_vst2q:
14336       NewOpc = ARMISD::VST2_UPD;
14337       NumVecs = 2;
14338       isLoadOp = false;
14339       break;
14340     case Intrinsic::arm_mve_vst4q:
14341       NewOpc = ARMISD::VST4_UPD;
14342       NumVecs = 4;
14343       isLoadOp = false;
14344       break;
14345     }
14346 
14347     // Find the size of memory referenced by the load/store.
14348     EVT VecTy;
14349     if (isLoadOp) {
14350       VecTy = N->getValueType(0);
14351     } else {
14352       VecTy = N->getOperand(3).getValueType();
14353     }
14354 
14355     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14356 
14357     // If the increment is a constant, it must match the memory ref size.
14358     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14359     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14360     if (!CInc || CInc->getZExtValue() != NumBytes)
14361       continue;
14362 
14363     // Create the new updating load/store node.
14364     // First, create an SDVTList for the new updating node's results.
14365     EVT Tys[6];
14366     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14367     unsigned n;
14368     for (n = 0; n < NumResultVecs; ++n)
14369       Tys[n] = VecTy;
14370     Tys[n++] = MVT::i32;
14371     Tys[n] = MVT::Other;
14372     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
14373 
14374     // Then, gather the new node's operands.
14375     SmallVector<SDValue, 8> Ops;
14376     Ops.push_back(N->getOperand(0)); // incoming chain
14377     Ops.push_back(N->getOperand(2)); // ptr
14378     Ops.push_back(Inc);
14379 
14380     for (unsigned i = 3; i < N->getNumOperands(); ++i)
14381       Ops.push_back(N->getOperand(i));
14382 
14383     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
14384                                            MemN->getMemOperand());
14385 
14386     // Update the uses.
14387     SmallVector<SDValue, 5> NewResults;
14388     for (unsigned i = 0; i < NumResultVecs; ++i)
14389       NewResults.push_back(SDValue(UpdN.getNode(), i));
14390 
14391     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
14392     DCI.CombineTo(N, NewResults);
14393     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14394 
14395     break;
14396   }
14397 
14398   return SDValue();
14399 }
14400 
14401 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
14402 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
14403 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
14404 /// return true.
14405 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14406   SelectionDAG &DAG = DCI.DAG;
14407   EVT VT = N->getValueType(0);
14408   // vldN-dup instructions only support 64-bit vectors for N > 1.
14409   if (!VT.is64BitVector())
14410     return false;
14411 
14412   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
14413   SDNode *VLD = N->getOperand(0).getNode();
14414   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
14415     return false;
14416   unsigned NumVecs = 0;
14417   unsigned NewOpc = 0;
14418   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
14419   if (IntNo == Intrinsic::arm_neon_vld2lane) {
14420     NumVecs = 2;
14421     NewOpc = ARMISD::VLD2DUP;
14422   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
14423     NumVecs = 3;
14424     NewOpc = ARMISD::VLD3DUP;
14425   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
14426     NumVecs = 4;
14427     NewOpc = ARMISD::VLD4DUP;
14428   } else {
14429     return false;
14430   }
14431 
14432   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
14433   // numbers match the load.
14434   unsigned VLDLaneNo =
14435     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
14436   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14437        UI != UE; ++UI) {
14438     // Ignore uses of the chain result.
14439     if (UI.getUse().getResNo() == NumVecs)
14440       continue;
14441     SDNode *User = *UI;
14442     if (User->getOpcode() != ARMISD::VDUPLANE ||
14443         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
14444       return false;
14445   }
14446 
14447   // Create the vldN-dup node.
14448   EVT Tys[5];
14449   unsigned n;
14450   for (n = 0; n < NumVecs; ++n)
14451     Tys[n] = VT;
14452   Tys[n] = MVT::Other;
14453   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
14454   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
14455   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
14456   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
14457                                            Ops, VLDMemInt->getMemoryVT(),
14458                                            VLDMemInt->getMemOperand());
14459 
14460   // Update the uses.
14461   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14462        UI != UE; ++UI) {
14463     unsigned ResNo = UI.getUse().getResNo();
14464     // Ignore uses of the chain result.
14465     if (ResNo == NumVecs)
14466       continue;
14467     SDNode *User = *UI;
14468     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
14469   }
14470 
14471   // Now the vldN-lane intrinsic is dead except for its chain result.
14472   // Update uses of the chain.
14473   std::vector<SDValue> VLDDupResults;
14474   for (unsigned n = 0; n < NumVecs; ++n)
14475     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
14476   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
14477   DCI.CombineTo(VLD, VLDDupResults);
14478 
14479   return true;
14480 }
14481 
14482 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
14483 /// ARMISD::VDUPLANE.
14484 static SDValue PerformVDUPLANECombine(SDNode *N,
14485                                       TargetLowering::DAGCombinerInfo &DCI,
14486                                       const ARMSubtarget *Subtarget) {
14487   SDValue Op = N->getOperand(0);
14488   EVT VT = N->getValueType(0);
14489 
14490   // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
14491   if (Subtarget->hasMVEIntegerOps()) {
14492     EVT ExtractVT = VT.getVectorElementType();
14493     // We need to ensure we are creating a legal type.
14494     if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
14495       ExtractVT = MVT::i32;
14496     SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
14497                               N->getOperand(0), N->getOperand(1));
14498     return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
14499   }
14500 
14501   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
14502   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
14503   if (CombineVLDDUP(N, DCI))
14504     return SDValue(N, 0);
14505 
14506   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
14507   // redundant.  Ignore bit_converts for now; element sizes are checked below.
14508   while (Op.getOpcode() == ISD::BITCAST)
14509     Op = Op.getOperand(0);
14510   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
14511     return SDValue();
14512 
14513   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
14514   unsigned EltSize = Op.getScalarValueSizeInBits();
14515   // The canonical VMOV for a zero vector uses a 32-bit element size.
14516   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14517   unsigned EltBits;
14518   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
14519     EltSize = 8;
14520   if (EltSize > VT.getScalarSizeInBits())
14521     return SDValue();
14522 
14523   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
14524 }
14525 
14526 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
14527 static SDValue PerformVDUPCombine(SDNode *N,
14528                                   TargetLowering::DAGCombinerInfo &DCI,
14529                                   const ARMSubtarget *Subtarget) {
14530   SelectionDAG &DAG = DCI.DAG;
14531   SDValue Op = N->getOperand(0);
14532   SDLoc dl(N);
14533 
14534   if (Subtarget->hasMVEIntegerOps()) {
14535     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
14536     // need to come from a GPR.
14537     if (Op.getValueType() == MVT::f32)
14538       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14539                              DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
14540     else if (Op.getValueType() == MVT::f16)
14541       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14542                              DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
14543   }
14544 
14545   if (!Subtarget->hasNEON())
14546     return SDValue();
14547 
14548   // Match VDUP(LOAD) -> VLD1DUP.
14549   // We match this pattern here rather than waiting for isel because the
14550   // transform is only legal for unindexed loads.
14551   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
14552   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
14553       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
14554     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
14555                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
14556     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
14557     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
14558                                              Ops, LD->getMemoryVT(),
14559                                              LD->getMemOperand());
14560     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
14561     return VLDDup;
14562   }
14563 
14564   return SDValue();
14565 }
14566 
14567 static SDValue PerformLOADCombine(SDNode *N,
14568                                   TargetLowering::DAGCombinerInfo &DCI) {
14569   EVT VT = N->getValueType(0);
14570 
14571   // If this is a legal vector load, try to combine it into a VLD1_UPD.
14572   if (ISD::isNormalLoad(N) && VT.isVector() &&
14573       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14574     return CombineBaseUpdate(N, DCI);
14575 
14576   return SDValue();
14577 }
14578 
14579 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
14580 // pack all of the elements in one place.  Next, store to memory in fewer
14581 // chunks.
14582 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
14583                                              SelectionDAG &DAG) {
14584   SDValue StVal = St->getValue();
14585   EVT VT = StVal.getValueType();
14586   if (!St->isTruncatingStore() || !VT.isVector())
14587     return SDValue();
14588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14589   EVT StVT = St->getMemoryVT();
14590   unsigned NumElems = VT.getVectorNumElements();
14591   assert(StVT != VT && "Cannot truncate to the same type");
14592   unsigned FromEltSz = VT.getScalarSizeInBits();
14593   unsigned ToEltSz = StVT.getScalarSizeInBits();
14594 
14595   // From, To sizes and ElemCount must be pow of two
14596   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
14597     return SDValue();
14598 
14599   // We are going to use the original vector elt for storing.
14600   // Accumulated smaller vector elements must be a multiple of the store size.
14601   if (0 != (NumElems * FromEltSz) % ToEltSz)
14602     return SDValue();
14603 
14604   unsigned SizeRatio = FromEltSz / ToEltSz;
14605   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
14606 
14607   // Create a type on which we perform the shuffle.
14608   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
14609                                    NumElems * SizeRatio);
14610   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14611 
14612   SDLoc DL(St);
14613   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
14614   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14615   for (unsigned i = 0; i < NumElems; ++i)
14616     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
14617                                                       : i * SizeRatio;
14618 
14619   // Can't shuffle using an illegal type.
14620   if (!TLI.isTypeLegal(WideVecVT))
14621     return SDValue();
14622 
14623   SDValue Shuff = DAG.getVectorShuffle(
14624       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
14625   // At this point all of the data is stored at the bottom of the
14626   // register. We now need to save it to mem.
14627 
14628   // Find the largest store unit
14629   MVT StoreType = MVT::i8;
14630   for (MVT Tp : MVT::integer_valuetypes()) {
14631     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
14632       StoreType = Tp;
14633   }
14634   // Didn't find a legal store type.
14635   if (!TLI.isTypeLegal(StoreType))
14636     return SDValue();
14637 
14638   // Bitcast the original vector into a vector of store-size units
14639   EVT StoreVecVT =
14640       EVT::getVectorVT(*DAG.getContext(), StoreType,
14641                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
14642   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14643   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
14644   SmallVector<SDValue, 8> Chains;
14645   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
14646                                       TLI.getPointerTy(DAG.getDataLayout()));
14647   SDValue BasePtr = St->getBasePtr();
14648 
14649   // Perform one or more big stores into memory.
14650   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
14651   for (unsigned I = 0; I < E; I++) {
14652     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
14653                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
14654     SDValue Ch =
14655         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
14656                      St->getAlignment(), St->getMemOperand()->getFlags());
14657     BasePtr =
14658         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
14659     Chains.push_back(Ch);
14660   }
14661   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14662 }
14663 
14664 // Try taking a single vector store from an truncate (which would otherwise turn
14665 // into an expensive buildvector) and splitting it into a series of narrowing
14666 // stores.
14667 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
14668                                                  SelectionDAG &DAG) {
14669   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
14670     return SDValue();
14671   SDValue Trunc = St->getValue();
14672   if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND)
14673     return SDValue();
14674   EVT FromVT = Trunc->getOperand(0).getValueType();
14675   EVT ToVT = Trunc.getValueType();
14676   if (!ToVT.isVector())
14677     return SDValue();
14678   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14679   EVT ToEltVT = ToVT.getVectorElementType();
14680   EVT FromEltVT = FromVT.getVectorElementType();
14681 
14682   unsigned NumElements = 0;
14683   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
14684     NumElements = 4;
14685   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
14686     NumElements = 8;
14687   if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16)
14688     NumElements = 4;
14689   if (NumElements == 0 ||
14690       (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) ||
14691       FromVT.getVectorNumElements() % NumElements != 0)
14692     return SDValue();
14693 
14694   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
14695   // use the VMOVN over splitting the store. We are looking for patterns of:
14696   // !rev: 0 N 1 N+1 2 N+2 ...
14697   //  rev: N 0 N+1 1 N+2 2 ...
14698   // The shuffle may either be a single source (in which case N = NumElts/2) or
14699   // two inputs extended with concat to the same size (in which case N =
14700   // NumElts).
14701   auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
14702     ArrayRef<int> M = SVN->getMask();
14703     unsigned NumElts = ToVT.getVectorNumElements();
14704     if (SVN->getOperand(1).isUndef())
14705       NumElts /= 2;
14706 
14707     unsigned Off0 = Rev ? NumElts : 0;
14708     unsigned Off1 = Rev ? 0 : NumElts;
14709 
14710     for (unsigned I = 0; I < NumElts; I += 2) {
14711       if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
14712         return false;
14713       if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
14714         return false;
14715     }
14716 
14717     return true;
14718   };
14719 
14720   // It may be preferable to keep the store unsplit as the trunc may end up
14721   // being removed. Check that here.
14722   if (Trunc.getOperand(0).getOpcode() == ISD::SMIN) {
14723     if (SDValue U = PerformVQDMULHCombine(Trunc.getOperand(0).getNode(), DAG)) {
14724       DAG.ReplaceAllUsesWith(Trunc.getOperand(0), U);
14725       return SDValue();
14726     }
14727   }
14728   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
14729     if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
14730       return SDValue();
14731 
14732   LLVMContext &C = *DAG.getContext();
14733   SDLoc DL(St);
14734   // Details about the old store
14735   SDValue Ch = St->getChain();
14736   SDValue BasePtr = St->getBasePtr();
14737   Align Alignment = St->getOriginalAlign();
14738   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
14739   AAMDNodes AAInfo = St->getAAInfo();
14740 
14741   // We split the store into slices of NumElements. fp16 trunc stores are vcvt
14742   // and then stored as truncating integer stores.
14743   EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
14744   EVT NewToVT = EVT::getVectorVT(
14745       C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
14746 
14747   SmallVector<SDValue, 4> Stores;
14748   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
14749     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
14750     SDValue NewPtr =
14751         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
14752 
14753     SDValue Extract =
14754         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
14755                     DAG.getConstant(i * NumElements, DL, MVT::i32));
14756 
14757     if (ToEltVT == MVT::f16) {
14758       SDValue FPTrunc =
14759           DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
14760                       Extract, DAG.getConstant(0, DL, MVT::i32));
14761       Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
14762     }
14763 
14764     SDValue Store = DAG.getTruncStore(
14765         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
14766         NewToVT, Alignment.value(), MMOFlags, AAInfo);
14767     Stores.push_back(Store);
14768   }
14769   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14770 }
14771 
14772 /// PerformSTORECombine - Target-specific dag combine xforms for
14773 /// ISD::STORE.
14774 static SDValue PerformSTORECombine(SDNode *N,
14775                                    TargetLowering::DAGCombinerInfo &DCI,
14776                                    const ARMSubtarget *Subtarget) {
14777   StoreSDNode *St = cast<StoreSDNode>(N);
14778   if (St->isVolatile())
14779     return SDValue();
14780   SDValue StVal = St->getValue();
14781   EVT VT = StVal.getValueType();
14782 
14783   if (Subtarget->hasNEON())
14784     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14785       return Store;
14786 
14787   if (Subtarget->hasMVEIntegerOps())
14788     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14789       return NewToken;
14790 
14791   if (!ISD::isNormalStore(St))
14792     return SDValue();
14793 
14794   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14795   // ARM stores of arguments in the same cache line.
14796   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14797       StVal.getNode()->hasOneUse()) {
14798     SelectionDAG  &DAG = DCI.DAG;
14799     bool isBigEndian = DAG.getDataLayout().isBigEndian();
14800     SDLoc DL(St);
14801     SDValue BasePtr = St->getBasePtr();
14802     SDValue NewST1 = DAG.getStore(
14803         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14804         BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
14805         St->getMemOperand()->getFlags());
14806 
14807     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14808                                     DAG.getConstant(4, DL, MVT::i32));
14809     return DAG.getStore(NewST1.getValue(0), DL,
14810                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14811                         OffsetPtr, St->getPointerInfo().getWithOffset(4),
14812                         St->getOriginalAlign(),
14813                         St->getMemOperand()->getFlags());
14814   }
14815 
14816   if (StVal.getValueType() == MVT::i64 &&
14817       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14818 
14819     // Bitcast an i64 store extracted from a vector to f64.
14820     // Otherwise, the i64 value will be legalized to a pair of i32 values.
14821     SelectionDAG &DAG = DCI.DAG;
14822     SDLoc dl(StVal);
14823     SDValue IntVec = StVal.getOperand(0);
14824     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14825                                    IntVec.getValueType().getVectorNumElements());
14826     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14827     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14828                                  Vec, StVal.getOperand(1));
14829     dl = SDLoc(N);
14830     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14831     // Make the DAGCombiner fold the bitcasts.
14832     DCI.AddToWorklist(Vec.getNode());
14833     DCI.AddToWorklist(ExtElt.getNode());
14834     DCI.AddToWorklist(V.getNode());
14835     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14836                         St->getPointerInfo(), St->getAlignment(),
14837                         St->getMemOperand()->getFlags(), St->getAAInfo());
14838   }
14839 
14840   // If this is a legal vector store, try to combine it into a VST1_UPD.
14841   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14842       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14843     return CombineBaseUpdate(N, DCI);
14844 
14845   return SDValue();
14846 }
14847 
14848 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14849 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14850 /// when the VMUL has a constant operand that is a power of 2.
14851 ///
14852 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14853 ///  vmul.f32        d16, d17, d16
14854 ///  vcvt.s32.f32    d16, d16
14855 /// becomes:
14856 ///  vcvt.s32.f32    d16, d16, #3
14857 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14858                                   const ARMSubtarget *Subtarget) {
14859   if (!Subtarget->hasNEON())
14860     return SDValue();
14861 
14862   SDValue Op = N->getOperand(0);
14863   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14864       Op.getOpcode() != ISD::FMUL)
14865     return SDValue();
14866 
14867   SDValue ConstVec = Op->getOperand(1);
14868   if (!isa<BuildVectorSDNode>(ConstVec))
14869     return SDValue();
14870 
14871   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14872   uint32_t FloatBits = FloatTy.getSizeInBits();
14873   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14874   uint32_t IntBits = IntTy.getSizeInBits();
14875   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14876   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14877     // These instructions only exist converting from f32 to i32. We can handle
14878     // smaller integers by generating an extra truncate, but larger ones would
14879     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14880     // these intructions only support v2i32/v4i32 types.
14881     return SDValue();
14882   }
14883 
14884   BitVector UndefElements;
14885   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14886   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14887   if (C == -1 || C == 0 || C > 32)
14888     return SDValue();
14889 
14890   SDLoc dl(N);
14891   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14892   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14893     Intrinsic::arm_neon_vcvtfp2fxu;
14894   SDValue FixConv = DAG.getNode(
14895       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14896       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14897       DAG.getConstant(C, dl, MVT::i32));
14898 
14899   if (IntBits < FloatBits)
14900     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14901 
14902   return FixConv;
14903 }
14904 
14905 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14906 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14907 /// when the VDIV has a constant operand that is a power of 2.
14908 ///
14909 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14910 ///  vcvt.f32.s32    d16, d16
14911 ///  vdiv.f32        d16, d17, d16
14912 /// becomes:
14913 ///  vcvt.f32.s32    d16, d16, #3
14914 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14915                                   const ARMSubtarget *Subtarget) {
14916   if (!Subtarget->hasNEON())
14917     return SDValue();
14918 
14919   SDValue Op = N->getOperand(0);
14920   unsigned OpOpcode = Op.getNode()->getOpcode();
14921   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14922       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14923     return SDValue();
14924 
14925   SDValue ConstVec = N->getOperand(1);
14926   if (!isa<BuildVectorSDNode>(ConstVec))
14927     return SDValue();
14928 
14929   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14930   uint32_t FloatBits = FloatTy.getSizeInBits();
14931   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14932   uint32_t IntBits = IntTy.getSizeInBits();
14933   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14934   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14935     // These instructions only exist converting from i32 to f32. We can handle
14936     // smaller integers by generating an extra extend, but larger ones would
14937     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14938     // these intructions only support v2i32/v4i32 types.
14939     return SDValue();
14940   }
14941 
14942   BitVector UndefElements;
14943   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14944   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14945   if (C == -1 || C == 0 || C > 32)
14946     return SDValue();
14947 
14948   SDLoc dl(N);
14949   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14950   SDValue ConvInput = Op.getOperand(0);
14951   if (IntBits < FloatBits)
14952     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14953                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14954                             ConvInput);
14955 
14956   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14957     Intrinsic::arm_neon_vcvtfxu2fp;
14958   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14959                      Op.getValueType(),
14960                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14961                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
14962 }
14963 
14964 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14965                                            const ARMSubtarget *ST) {
14966   if (!ST->hasMVEIntegerOps())
14967     return SDValue();
14968 
14969   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14970   EVT ResVT = N->getValueType(0);
14971   SDValue N0 = N->getOperand(0);
14972   SDLoc dl(N);
14973 
14974   // We are looking for something that will have illegal types if left alone,
14975   // but that we can convert to a single instruction undef MVE. For example
14976   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14977   // or
14978   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14979 
14980   // Cases:
14981   //   VADDV u/s 8/16/32
14982   //   VMLAV u/s 8/16/32
14983   //   VADDLV u/s 32
14984   //   VMLALV u/s 16/32
14985 
14986   // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
14987   // extend it and use v4i32 instead.
14988   auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
14989     EVT AVT = A.getValueType();
14990     if (!AVT.is128BitVector())
14991       A = DAG.getNode(ExtendCode, dl,
14992                       AVT.changeVectorElementType(MVT::getIntegerVT(
14993                           128 / AVT.getVectorMinNumElements())),
14994                       A);
14995     return A;
14996   };
14997   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14998     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14999       return SDValue();
15000     SDValue A = N0->getOperand(0);
15001     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
15002       return ExtendIfNeeded(A, ExtendCode);
15003     return SDValue();
15004   };
15005   auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
15006                          ArrayRef<MVT> ExtTypes, SDValue &Mask) {
15007     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
15008         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
15009       return SDValue();
15010     Mask = N0->getOperand(0);
15011     SDValue Ext = N0->getOperand(1);
15012     if (Ext->getOpcode() != ExtendCode)
15013       return SDValue();
15014     SDValue A = Ext->getOperand(0);
15015     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
15016       return ExtendIfNeeded(A, ExtendCode);
15017     return SDValue();
15018   };
15019   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
15020                      SDValue &A, SDValue &B) {
15021     // For a vmla we are trying to match a larger pattern:
15022     // ExtA = sext/zext A
15023     // ExtB = sext/zext B
15024     // Mul = mul ExtA, ExtB
15025     // vecreduce.add Mul
15026     // There might also be en extra extend between the mul and the addreduce, so
15027     // long as the bitwidth is high enough to make them equivalent (for example
15028     // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
15029     if (ResVT != RetTy)
15030       return false;
15031     SDValue Mul = N0;
15032     if (Mul->getOpcode() == ExtendCode &&
15033         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
15034             ResVT.getScalarSizeInBits())
15035       Mul = Mul->getOperand(0);
15036     if (Mul->getOpcode() != ISD::MUL)
15037       return false;
15038     SDValue ExtA = Mul->getOperand(0);
15039     SDValue ExtB = Mul->getOperand(1);
15040     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
15041       return false;
15042     A = ExtA->getOperand(0);
15043     B = ExtB->getOperand(0);
15044     if (A.getValueType() == B.getValueType() &&
15045         llvm::any_of(ExtTypes,
15046                      [&A](MVT Ty) { return A.getValueType() == Ty; })) {
15047       A = ExtendIfNeeded(A, ExtendCode);
15048       B = ExtendIfNeeded(B, ExtendCode);
15049       return true;
15050     }
15051     return false;
15052   };
15053   auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
15054                      SDValue &A, SDValue &B, SDValue &Mask) {
15055     // Same as the pattern above with a select for the zero predicated lanes
15056     // ExtA = sext/zext A
15057     // ExtB = sext/zext B
15058     // Mul = mul ExtA, ExtB
15059     // N0 = select Mask, Mul, 0
15060     // vecreduce.add N0
15061     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
15062         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
15063       return false;
15064     Mask = N0->getOperand(0);
15065     SDValue Mul = N0->getOperand(1);
15066     if (Mul->getOpcode() == ExtendCode &&
15067         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
15068             ResVT.getScalarSizeInBits())
15069       Mul = Mul->getOperand(0);
15070     if (Mul->getOpcode() != ISD::MUL)
15071       return false;
15072     SDValue ExtA = Mul->getOperand(0);
15073     SDValue ExtB = Mul->getOperand(1);
15074     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
15075       return false;
15076     A = ExtA->getOperand(0);
15077     B = ExtB->getOperand(0);
15078     if (A.getValueType() == B.getValueType() &&
15079         llvm::any_of(ExtTypes,
15080                      [&A](MVT Ty) { return A.getValueType() == Ty; })) {
15081       A = ExtendIfNeeded(A, ExtendCode);
15082       B = ExtendIfNeeded(B, ExtendCode);
15083       return true;
15084     }
15085     return false;
15086   };
15087   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
15088     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
15089     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
15090                        SDValue(Node.getNode(), 1));
15091   };
15092 
15093   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
15094     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
15095   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
15096     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
15097   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND,
15098                           {MVT::v4i8, MVT::v4i16, MVT::v4i32}))
15099     return Create64bitNode(ARMISD::VADDLVs, {A});
15100   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND,
15101                           {MVT::v4i8, MVT::v4i16, MVT::v4i32}))
15102     return Create64bitNode(ARMISD::VADDLVu, {A});
15103   if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
15104     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15105                        DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
15106   if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
15107     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15108                        DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
15109 
15110   SDValue Mask;
15111   if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
15112     return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
15113   if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
15114     return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
15115   if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND,
15116                               {MVT::v4i8, MVT::v4i16, MVT::v4i32}, Mask))
15117     return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
15118   if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND,
15119                               {MVT::v4i8, MVT::v4i16, MVT::v4i32}, Mask))
15120     return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
15121   if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
15122     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15123                        DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
15124   if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
15125     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15126                        DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
15127 
15128   SDValue A, B;
15129   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
15130     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
15131   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
15132     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
15133   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND,
15134               {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A, B))
15135     return Create64bitNode(ARMISD::VMLALVs, {A, B});
15136   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND,
15137               {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A, B))
15138     return Create64bitNode(ARMISD::VMLALVu, {A, B});
15139   if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
15140     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15141                        DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
15142   if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
15143     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15144                        DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
15145 
15146   if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
15147     return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
15148   if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
15149     return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
15150   if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND,
15151                   {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A,
15152                   B, Mask))
15153     return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
15154   if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND,
15155                   {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A,
15156                   B, Mask))
15157     return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
15158   if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
15159     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15160                        DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
15161   if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
15162     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15163                        DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
15164 
15165   // Some complications. We can get a case where the two inputs of the mul are
15166   // the same, then the output sext will have been helpfully converted to a
15167   // zext. Turn it back.
15168   SDValue Op = N0;
15169   if (Op->getOpcode() == ISD::VSELECT)
15170     Op = Op->getOperand(1);
15171   if (Op->getOpcode() == ISD::ZERO_EXTEND &&
15172       Op->getOperand(0)->getOpcode() == ISD::MUL) {
15173     SDValue Mul = Op->getOperand(0);
15174     if (Mul->getOperand(0) == Mul->getOperand(1) &&
15175         Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
15176       SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
15177       if (Op != N0)
15178         Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
15179                           N0->getOperand(0), Ext, N0->getOperand(2));
15180       return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
15181     }
15182   }
15183 
15184   return SDValue();
15185 }
15186 
15187 static SDValue PerformVMOVNCombine(SDNode *N,
15188                                    TargetLowering::DAGCombinerInfo &DCI) {
15189   SDValue Op0 = N->getOperand(0);
15190   SDValue Op1 = N->getOperand(1);
15191   unsigned IsTop = N->getConstantOperandVal(2);
15192 
15193   // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
15194   // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
15195   if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
15196        Op1->getOpcode() == ARMISD::VQMOVNu) &&
15197       Op1->getConstantOperandVal(2) == 0)
15198     return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
15199                            Op0, Op1->getOperand(1), N->getOperand(2));
15200 
15201   // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
15202   // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
15203   // into the top or bottom lanes.
15204   unsigned NumElts = N->getValueType(0).getVectorNumElements();
15205   APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
15206   APInt Op0DemandedElts =
15207       IsTop ? Op1DemandedElts
15208             : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
15209 
15210   APInt KnownUndef, KnownZero;
15211   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15212   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
15213                                      KnownZero, DCI))
15214     return SDValue(N, 0);
15215   if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
15216                                      KnownZero, DCI))
15217     return SDValue(N, 0);
15218 
15219   return SDValue();
15220 }
15221 
15222 static SDValue PerformVQMOVNCombine(SDNode *N,
15223                                     TargetLowering::DAGCombinerInfo &DCI) {
15224   SDValue Op0 = N->getOperand(0);
15225   unsigned IsTop = N->getConstantOperandVal(2);
15226 
15227   unsigned NumElts = N->getValueType(0).getVectorNumElements();
15228   APInt Op0DemandedElts =
15229       APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
15230                                      : APInt::getHighBitsSet(2, 1));
15231 
15232   APInt KnownUndef, KnownZero;
15233   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15234   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
15235                                      KnownZero, DCI))
15236     return SDValue(N, 0);
15237   return SDValue();
15238 }
15239 
15240 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
15241   SDLoc DL(N);
15242   SDValue Op0 = N->getOperand(0);
15243   SDValue Op1 = N->getOperand(1);
15244 
15245   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
15246   // uses of the intrinsics.
15247   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
15248     int ShiftAmt = C->getSExtValue();
15249     if (ShiftAmt == 0) {
15250       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
15251       DAG.ReplaceAllUsesWith(N, Merge.getNode());
15252       return SDValue();
15253     }
15254 
15255     if (ShiftAmt >= -32 && ShiftAmt < 0) {
15256       unsigned NewOpcode =
15257           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
15258       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
15259                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
15260       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
15261       return NewShift;
15262     }
15263   }
15264 
15265   return SDValue();
15266 }
15267 
15268 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
15269 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
15270                                                    DAGCombinerInfo &DCI) const {
15271   SelectionDAG &DAG = DCI.DAG;
15272   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15273   switch (IntNo) {
15274   default:
15275     // Don't do anything for most intrinsics.
15276     break;
15277 
15278   // Vector shifts: check for immediate versions and lower them.
15279   // Note: This is done during DAG combining instead of DAG legalizing because
15280   // the build_vectors for 64-bit vector element shift counts are generally
15281   // not legal, and it is hard to see their values after they get legalized to
15282   // loads from a constant pool.
15283   case Intrinsic::arm_neon_vshifts:
15284   case Intrinsic::arm_neon_vshiftu:
15285   case Intrinsic::arm_neon_vrshifts:
15286   case Intrinsic::arm_neon_vrshiftu:
15287   case Intrinsic::arm_neon_vrshiftn:
15288   case Intrinsic::arm_neon_vqshifts:
15289   case Intrinsic::arm_neon_vqshiftu:
15290   case Intrinsic::arm_neon_vqshiftsu:
15291   case Intrinsic::arm_neon_vqshiftns:
15292   case Intrinsic::arm_neon_vqshiftnu:
15293   case Intrinsic::arm_neon_vqshiftnsu:
15294   case Intrinsic::arm_neon_vqrshiftns:
15295   case Intrinsic::arm_neon_vqrshiftnu:
15296   case Intrinsic::arm_neon_vqrshiftnsu: {
15297     EVT VT = N->getOperand(1).getValueType();
15298     int64_t Cnt;
15299     unsigned VShiftOpc = 0;
15300 
15301     switch (IntNo) {
15302     case Intrinsic::arm_neon_vshifts:
15303     case Intrinsic::arm_neon_vshiftu:
15304       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
15305         VShiftOpc = ARMISD::VSHLIMM;
15306         break;
15307       }
15308       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
15309         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
15310                                                           : ARMISD::VSHRuIMM);
15311         break;
15312       }
15313       return SDValue();
15314 
15315     case Intrinsic::arm_neon_vrshifts:
15316     case Intrinsic::arm_neon_vrshiftu:
15317       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
15318         break;
15319       return SDValue();
15320 
15321     case Intrinsic::arm_neon_vqshifts:
15322     case Intrinsic::arm_neon_vqshiftu:
15323       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15324         break;
15325       return SDValue();
15326 
15327     case Intrinsic::arm_neon_vqshiftsu:
15328       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15329         break;
15330       llvm_unreachable("invalid shift count for vqshlu intrinsic");
15331 
15332     case Intrinsic::arm_neon_vrshiftn:
15333     case Intrinsic::arm_neon_vqshiftns:
15334     case Intrinsic::arm_neon_vqshiftnu:
15335     case Intrinsic::arm_neon_vqshiftnsu:
15336     case Intrinsic::arm_neon_vqrshiftns:
15337     case Intrinsic::arm_neon_vqrshiftnu:
15338     case Intrinsic::arm_neon_vqrshiftnsu:
15339       // Narrowing shifts require an immediate right shift.
15340       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
15341         break;
15342       llvm_unreachable("invalid shift count for narrowing vector shift "
15343                        "intrinsic");
15344 
15345     default:
15346       llvm_unreachable("unhandled vector shift");
15347     }
15348 
15349     switch (IntNo) {
15350     case Intrinsic::arm_neon_vshifts:
15351     case Intrinsic::arm_neon_vshiftu:
15352       // Opcode already set above.
15353       break;
15354     case Intrinsic::arm_neon_vrshifts:
15355       VShiftOpc = ARMISD::VRSHRsIMM;
15356       break;
15357     case Intrinsic::arm_neon_vrshiftu:
15358       VShiftOpc = ARMISD::VRSHRuIMM;
15359       break;
15360     case Intrinsic::arm_neon_vrshiftn:
15361       VShiftOpc = ARMISD::VRSHRNIMM;
15362       break;
15363     case Intrinsic::arm_neon_vqshifts:
15364       VShiftOpc = ARMISD::VQSHLsIMM;
15365       break;
15366     case Intrinsic::arm_neon_vqshiftu:
15367       VShiftOpc = ARMISD::VQSHLuIMM;
15368       break;
15369     case Intrinsic::arm_neon_vqshiftsu:
15370       VShiftOpc = ARMISD::VQSHLsuIMM;
15371       break;
15372     case Intrinsic::arm_neon_vqshiftns:
15373       VShiftOpc = ARMISD::VQSHRNsIMM;
15374       break;
15375     case Intrinsic::arm_neon_vqshiftnu:
15376       VShiftOpc = ARMISD::VQSHRNuIMM;
15377       break;
15378     case Intrinsic::arm_neon_vqshiftnsu:
15379       VShiftOpc = ARMISD::VQSHRNsuIMM;
15380       break;
15381     case Intrinsic::arm_neon_vqrshiftns:
15382       VShiftOpc = ARMISD::VQRSHRNsIMM;
15383       break;
15384     case Intrinsic::arm_neon_vqrshiftnu:
15385       VShiftOpc = ARMISD::VQRSHRNuIMM;
15386       break;
15387     case Intrinsic::arm_neon_vqrshiftnsu:
15388       VShiftOpc = ARMISD::VQRSHRNsuIMM;
15389       break;
15390     }
15391 
15392     SDLoc dl(N);
15393     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15394                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
15395   }
15396 
15397   case Intrinsic::arm_neon_vshiftins: {
15398     EVT VT = N->getOperand(1).getValueType();
15399     int64_t Cnt;
15400     unsigned VShiftOpc = 0;
15401 
15402     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
15403       VShiftOpc = ARMISD::VSLIIMM;
15404     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
15405       VShiftOpc = ARMISD::VSRIIMM;
15406     else {
15407       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
15408     }
15409 
15410     SDLoc dl(N);
15411     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15412                        N->getOperand(1), N->getOperand(2),
15413                        DAG.getConstant(Cnt, dl, MVT::i32));
15414   }
15415 
15416   case Intrinsic::arm_neon_vqrshifts:
15417   case Intrinsic::arm_neon_vqrshiftu:
15418     // No immediate versions of these to check for.
15419     break;
15420 
15421   case Intrinsic::arm_mve_vqdmlah:
15422   case Intrinsic::arm_mve_vqdmlash:
15423   case Intrinsic::arm_mve_vqrdmlah:
15424   case Intrinsic::arm_mve_vqrdmlash:
15425   case Intrinsic::arm_mve_vmla_n_predicated:
15426   case Intrinsic::arm_mve_vmlas_n_predicated:
15427   case Intrinsic::arm_mve_vqdmlah_predicated:
15428   case Intrinsic::arm_mve_vqdmlash_predicated:
15429   case Intrinsic::arm_mve_vqrdmlah_predicated:
15430   case Intrinsic::arm_mve_vqrdmlash_predicated: {
15431     // These intrinsics all take an i32 scalar operand which is narrowed to the
15432     // size of a single lane of the vector type they return. So we don't need
15433     // any bits of that operand above that point, which allows us to eliminate
15434     // uxth/sxth.
15435     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
15436     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15437     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
15438       return SDValue();
15439     break;
15440   }
15441 
15442   case Intrinsic::arm_mve_minv:
15443   case Intrinsic::arm_mve_maxv:
15444   case Intrinsic::arm_mve_minav:
15445   case Intrinsic::arm_mve_maxav:
15446   case Intrinsic::arm_mve_minv_predicated:
15447   case Intrinsic::arm_mve_maxv_predicated:
15448   case Intrinsic::arm_mve_minav_predicated:
15449   case Intrinsic::arm_mve_maxav_predicated: {
15450     // These intrinsics all take an i32 scalar operand which is narrowed to the
15451     // size of a single lane of the vector type they take as the other input.
15452     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
15453     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15454     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15455       return SDValue();
15456     break;
15457   }
15458 
15459   case Intrinsic::arm_mve_addv: {
15460     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
15461     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
15462     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15463     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
15464     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
15465   }
15466 
15467   case Intrinsic::arm_mve_addlv:
15468   case Intrinsic::arm_mve_addlv_predicated: {
15469     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
15470     // which recombines the two outputs into an i64
15471     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15472     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
15473                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
15474                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
15475 
15476     SmallVector<SDValue, 4> Ops;
15477     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
15478       if (i != 2)                      // skip the unsigned flag
15479         Ops.push_back(N->getOperand(i));
15480 
15481     SDLoc dl(N);
15482     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
15483     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
15484                        val.getValue(1));
15485   }
15486   }
15487 
15488   return SDValue();
15489 }
15490 
15491 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
15492 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
15493 /// combining instead of DAG legalizing because the build_vectors for 64-bit
15494 /// vector element shift counts are generally not legal, and it is hard to see
15495 /// their values after they get legalized to loads from a constant pool.
15496 static SDValue PerformShiftCombine(SDNode *N,
15497                                    TargetLowering::DAGCombinerInfo &DCI,
15498                                    const ARMSubtarget *ST) {
15499   SelectionDAG &DAG = DCI.DAG;
15500   EVT VT = N->getValueType(0);
15501   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
15502     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
15503     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
15504     SDValue N1 = N->getOperand(1);
15505     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
15506       SDValue N0 = N->getOperand(0);
15507       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
15508           DAG.MaskedValueIsZero(N0.getOperand(0),
15509                                 APInt::getHighBitsSet(32, 16)))
15510         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
15511     }
15512   }
15513 
15514   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
15515       N->getOperand(0)->getOpcode() == ISD::AND &&
15516       N->getOperand(0)->hasOneUse()) {
15517     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15518       return SDValue();
15519     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
15520     // usually show up because instcombine prefers to canonicalize it to
15521     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
15522     // out of GEP lowering in some cases.
15523     SDValue N0 = N->getOperand(0);
15524     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
15525     if (!ShiftAmtNode)
15526       return SDValue();
15527     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
15528     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15529     if (!AndMaskNode)
15530       return SDValue();
15531     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
15532     // Don't transform uxtb/uxth.
15533     if (AndMask == 255 || AndMask == 65535)
15534       return SDValue();
15535     if (isMask_32(AndMask)) {
15536       uint32_t MaskedBits = countLeadingZeros(AndMask);
15537       if (MaskedBits > ShiftAmt) {
15538         SDLoc DL(N);
15539         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
15540                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
15541         return DAG.getNode(
15542             ISD::SRL, DL, MVT::i32, SHL,
15543             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
15544       }
15545     }
15546   }
15547 
15548   // Nothing to be done for scalar shifts.
15549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15550   if (!VT.isVector() || !TLI.isTypeLegal(VT))
15551     return SDValue();
15552   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
15553     return SDValue();
15554 
15555   int64_t Cnt;
15556 
15557   switch (N->getOpcode()) {
15558   default: llvm_unreachable("unexpected shift opcode");
15559 
15560   case ISD::SHL:
15561     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
15562       SDLoc dl(N);
15563       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
15564                          DAG.getConstant(Cnt, dl, MVT::i32));
15565     }
15566     break;
15567 
15568   case ISD::SRA:
15569   case ISD::SRL:
15570     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
15571       unsigned VShiftOpc =
15572           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
15573       SDLoc dl(N);
15574       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
15575                          DAG.getConstant(Cnt, dl, MVT::i32));
15576     }
15577   }
15578   return SDValue();
15579 }
15580 
15581 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be
15582 // split into multiple extending loads, which are simpler to deal with than an
15583 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL
15584 // to convert the type to an f32.
15585 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
15586   SDValue N0 = N->getOperand(0);
15587   if (N0.getOpcode() != ISD::LOAD)
15588     return SDValue();
15589   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
15590   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
15591       LD->getExtensionType() != ISD::NON_EXTLOAD)
15592     return SDValue();
15593   EVT FromVT = LD->getValueType(0);
15594   EVT ToVT = N->getValueType(0);
15595   if (!ToVT.isVector())
15596     return SDValue();
15597   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
15598   EVT ToEltVT = ToVT.getVectorElementType();
15599   EVT FromEltVT = FromVT.getVectorElementType();
15600 
15601   unsigned NumElements = 0;
15602   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
15603     NumElements = 4;
15604   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
15605     NumElements = 8;
15606   if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
15607     NumElements = 4;
15608   if (NumElements == 0 ||
15609       (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
15610       FromVT.getVectorNumElements() % NumElements != 0 ||
15611       !isPowerOf2_32(NumElements))
15612     return SDValue();
15613 
15614   LLVMContext &C = *DAG.getContext();
15615   SDLoc DL(LD);
15616   // Details about the old load
15617   SDValue Ch = LD->getChain();
15618   SDValue BasePtr = LD->getBasePtr();
15619   Align Alignment = LD->getOriginalAlign();
15620   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
15621   AAMDNodes AAInfo = LD->getAAInfo();
15622 
15623   ISD::LoadExtType NewExtType =
15624       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15625   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
15626   EVT NewFromVT = EVT::getVectorVT(
15627       C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
15628   EVT NewToVT = EVT::getVectorVT(
15629       C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
15630 
15631   SmallVector<SDValue, 4> Loads;
15632   SmallVector<SDValue, 4> Chains;
15633   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
15634     unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
15635     SDValue NewPtr =
15636         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
15637 
15638     SDValue NewLoad =
15639         DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
15640                     LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
15641                     Alignment, MMOFlags, AAInfo);
15642     Loads.push_back(NewLoad);
15643     Chains.push_back(SDValue(NewLoad.getNode(), 1));
15644   }
15645 
15646   // Float truncs need to extended with VCVTB's into their floating point types.
15647   if (FromEltVT == MVT::f16) {
15648     SmallVector<SDValue, 4> Extends;
15649 
15650     for (unsigned i = 0; i < Loads.size(); i++) {
15651       SDValue LoadBC =
15652           DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
15653       SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
15654                                   DAG.getConstant(0, DL, MVT::i32));
15655       Extends.push_back(FPExt);
15656     }
15657 
15658     Loads = Extends;
15659   }
15660 
15661   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15662   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
15663   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
15664 }
15665 
15666 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
15667 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
15668 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
15669                                     const ARMSubtarget *ST) {
15670   SDValue N0 = N->getOperand(0);
15671 
15672   // Check for sign- and zero-extensions of vector extract operations of 8- and
15673   // 16-bit vector elements. NEON and MVE support these directly. They are
15674   // handled during DAG combining because type legalization will promote them
15675   // to 32-bit types and it is messy to recognize the operations after that.
15676   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
15677       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15678     SDValue Vec = N0.getOperand(0);
15679     SDValue Lane = N0.getOperand(1);
15680     EVT VT = N->getValueType(0);
15681     EVT EltVT = N0.getValueType();
15682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15683 
15684     if (VT == MVT::i32 &&
15685         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
15686         TLI.isTypeLegal(Vec.getValueType()) &&
15687         isa<ConstantSDNode>(Lane)) {
15688 
15689       unsigned Opc = 0;
15690       switch (N->getOpcode()) {
15691       default: llvm_unreachable("unexpected opcode");
15692       case ISD::SIGN_EXTEND:
15693         Opc = ARMISD::VGETLANEs;
15694         break;
15695       case ISD::ZERO_EXTEND:
15696       case ISD::ANY_EXTEND:
15697         Opc = ARMISD::VGETLANEu;
15698         break;
15699       }
15700       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
15701     }
15702   }
15703 
15704   if (ST->hasMVEIntegerOps())
15705     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15706       return NewLoad;
15707 
15708   return SDValue();
15709 }
15710 
15711 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
15712                                       const ARMSubtarget *ST) {
15713   if (ST->hasMVEFloatOps())
15714     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15715       return NewLoad;
15716 
15717   return SDValue();
15718 }
15719 
15720 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
15721 /// saturates.
15722 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
15723                                     const ARMSubtarget *ST) {
15724   EVT VT = N->getValueType(0);
15725   SDValue N0 = N->getOperand(0);
15726   if (!ST->hasMVEIntegerOps())
15727     return SDValue();
15728 
15729   if (SDValue V = PerformVQDMULHCombine(N, DAG))
15730     return V;
15731 
15732   if (VT != MVT::v4i32 && VT != MVT::v8i16)
15733     return SDValue();
15734 
15735   auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
15736     // Check one is a smin and the other is a smax
15737     if (Min->getOpcode() != ISD::SMIN)
15738       std::swap(Min, Max);
15739     if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
15740       return false;
15741 
15742     APInt SaturateC;
15743     if (VT == MVT::v4i32)
15744       SaturateC = APInt(32, (1 << 15) - 1, true);
15745     else //if (VT == MVT::v8i16)
15746       SaturateC = APInt(16, (1 << 7) - 1, true);
15747 
15748     APInt MinC, MaxC;
15749     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15750         MinC != SaturateC)
15751       return false;
15752     if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
15753         MaxC != ~SaturateC)
15754       return false;
15755     return true;
15756   };
15757 
15758   if (IsSignedSaturate(N, N0.getNode())) {
15759     SDLoc DL(N);
15760     MVT ExtVT, HalfVT;
15761     if (VT == MVT::v4i32) {
15762       HalfVT = MVT::v8i16;
15763       ExtVT = MVT::v4i16;
15764     } else { // if (VT == MVT::v8i16)
15765       HalfVT = MVT::v16i8;
15766       ExtVT = MVT::v8i8;
15767     }
15768 
15769     // Create a VQMOVNB with undef top lanes, then signed extended into the top
15770     // half. That extend will hopefully be removed if only the bottom bits are
15771     // demanded (though a truncating store, for example).
15772     SDValue VQMOVN =
15773         DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
15774                     N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
15775     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15776     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
15777                        DAG.getValueType(ExtVT));
15778   }
15779 
15780   auto IsUnsignedSaturate = [&](SDNode *Min) {
15781     // For unsigned, we just need to check for <= 0xffff
15782     if (Min->getOpcode() != ISD::UMIN)
15783       return false;
15784 
15785     APInt SaturateC;
15786     if (VT == MVT::v4i32)
15787       SaturateC = APInt(32, (1 << 16) - 1, true);
15788     else //if (VT == MVT::v8i16)
15789       SaturateC = APInt(16, (1 << 8) - 1, true);
15790 
15791     APInt MinC;
15792     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15793         MinC != SaturateC)
15794       return false;
15795     return true;
15796   };
15797 
15798   if (IsUnsignedSaturate(N)) {
15799     SDLoc DL(N);
15800     MVT HalfVT;
15801     unsigned ExtConst;
15802     if (VT == MVT::v4i32) {
15803       HalfVT = MVT::v8i16;
15804       ExtConst = 0x0000FFFF;
15805     } else { //if (VT == MVT::v8i16)
15806       HalfVT = MVT::v16i8;
15807       ExtConst = 0x00FF;
15808     }
15809 
15810     // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
15811     // an AND. That extend will hopefully be removed if only the bottom bits are
15812     // demanded (though a truncating store, for example).
15813     SDValue VQMOVN =
15814         DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
15815                     DAG.getConstant(0, DL, MVT::i32));
15816     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15817     return DAG.getNode(ISD::AND, DL, VT, Bitcast,
15818                        DAG.getConstant(ExtConst, DL, VT));
15819   }
15820 
15821   return SDValue();
15822 }
15823 
15824 static const APInt *isPowerOf2Constant(SDValue V) {
15825   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15826   if (!C)
15827     return nullptr;
15828   const APInt *CV = &C->getAPIntValue();
15829   return CV->isPowerOf2() ? CV : nullptr;
15830 }
15831 
15832 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
15833   // If we have a CMOV, OR and AND combination such as:
15834   //   if (x & CN)
15835   //     y |= CM;
15836   //
15837   // And:
15838   //   * CN is a single bit;
15839   //   * All bits covered by CM are known zero in y
15840   //
15841   // Then we can convert this into a sequence of BFI instructions. This will
15842   // always be a win if CM is a single bit, will always be no worse than the
15843   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
15844   // three bits (due to the extra IT instruction).
15845 
15846   SDValue Op0 = CMOV->getOperand(0);
15847   SDValue Op1 = CMOV->getOperand(1);
15848   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
15849   auto CC = CCNode->getAPIntValue().getLimitedValue();
15850   SDValue CmpZ = CMOV->getOperand(4);
15851 
15852   // The compare must be against zero.
15853   if (!isNullConstant(CmpZ->getOperand(1)))
15854     return SDValue();
15855 
15856   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
15857   SDValue And = CmpZ->getOperand(0);
15858   if (And->getOpcode() != ISD::AND)
15859     return SDValue();
15860   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
15861   if (!AndC)
15862     return SDValue();
15863   SDValue X = And->getOperand(0);
15864 
15865   if (CC == ARMCC::EQ) {
15866     // We're performing an "equal to zero" compare. Swap the operands so we
15867     // canonicalize on a "not equal to zero" compare.
15868     std::swap(Op0, Op1);
15869   } else {
15870     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
15871   }
15872 
15873   if (Op1->getOpcode() != ISD::OR)
15874     return SDValue();
15875 
15876   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
15877   if (!OrC)
15878     return SDValue();
15879   SDValue Y = Op1->getOperand(0);
15880 
15881   if (Op0 != Y)
15882     return SDValue();
15883 
15884   // Now, is it profitable to continue?
15885   APInt OrCI = OrC->getAPIntValue();
15886   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
15887   if (OrCI.countPopulation() > Heuristic)
15888     return SDValue();
15889 
15890   // Lastly, can we determine that the bits defined by OrCI
15891   // are zero in Y?
15892   KnownBits Known = DAG.computeKnownBits(Y);
15893   if ((OrCI & Known.Zero) != OrCI)
15894     return SDValue();
15895 
15896   // OK, we can do the combine.
15897   SDValue V = Y;
15898   SDLoc dl(X);
15899   EVT VT = X.getValueType();
15900   unsigned BitInX = AndC->logBase2();
15901 
15902   if (BitInX != 0) {
15903     // We must shift X first.
15904     X = DAG.getNode(ISD::SRL, dl, VT, X,
15905                     DAG.getConstant(BitInX, dl, VT));
15906   }
15907 
15908   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
15909        BitInY < NumActiveBits; ++BitInY) {
15910     if (OrCI[BitInY] == 0)
15911       continue;
15912     APInt Mask(VT.getSizeInBits(), 0);
15913     Mask.setBit(BitInY);
15914     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
15915                     // Confusingly, the operand is an *inverted* mask.
15916                     DAG.getConstant(~Mask, dl, VT));
15917   }
15918 
15919   return V;
15920 }
15921 
15922 // Given N, the value controlling the conditional branch, search for the loop
15923 // intrinsic, returning it, along with how the value is used. We need to handle
15924 // patterns such as the following:
15925 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
15926 // (brcond (setcc (loop.decrement), 0, eq), exit)
15927 // (brcond (setcc (loop.decrement), 0, ne), header)
15928 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
15929                                    bool &Negate) {
15930   switch (N->getOpcode()) {
15931   default:
15932     break;
15933   case ISD::XOR: {
15934     if (!isa<ConstantSDNode>(N.getOperand(1)))
15935       return SDValue();
15936     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
15937       return SDValue();
15938     Negate = !Negate;
15939     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
15940   }
15941   case ISD::SETCC: {
15942     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
15943     if (!Const)
15944       return SDValue();
15945     if (Const->isNullValue())
15946       Imm = 0;
15947     else if (Const->isOne())
15948       Imm = 1;
15949     else
15950       return SDValue();
15951     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
15952     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
15953   }
15954   case ISD::INTRINSIC_W_CHAIN: {
15955     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
15956     if (IntOp != Intrinsic::test_set_loop_iterations &&
15957         IntOp != Intrinsic::loop_decrement_reg)
15958       return SDValue();
15959     return N;
15960   }
15961   }
15962   return SDValue();
15963 }
15964 
15965 static SDValue PerformHWLoopCombine(SDNode *N,
15966                                     TargetLowering::DAGCombinerInfo &DCI,
15967                                     const ARMSubtarget *ST) {
15968 
15969   // The hwloop intrinsics that we're interested are used for control-flow,
15970   // either for entering or exiting the loop:
15971   // - test.set.loop.iterations will test whether its operand is zero. If it
15972   //   is zero, the proceeding branch should not enter the loop.
15973   // - loop.decrement.reg also tests whether its operand is zero. If it is
15974   //   zero, the proceeding branch should not branch back to the beginning of
15975   //   the loop.
15976   // So here, we need to check that how the brcond is using the result of each
15977   // of the intrinsics to ensure that we're branching to the right place at the
15978   // right time.
15979 
15980   ISD::CondCode CC;
15981   SDValue Cond;
15982   int Imm = 1;
15983   bool Negate = false;
15984   SDValue Chain = N->getOperand(0);
15985   SDValue Dest;
15986 
15987   if (N->getOpcode() == ISD::BRCOND) {
15988     CC = ISD::SETEQ;
15989     Cond = N->getOperand(1);
15990     Dest = N->getOperand(2);
15991   } else {
15992     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
15993     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15994     Cond = N->getOperand(2);
15995     Dest = N->getOperand(4);
15996     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
15997       if (!Const->isOne() && !Const->isNullValue())
15998         return SDValue();
15999       Imm = Const->getZExtValue();
16000     } else
16001       return SDValue();
16002   }
16003 
16004   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
16005   if (!Int)
16006     return SDValue();
16007 
16008   if (Negate)
16009     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
16010 
16011   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
16012     return (CC == ISD::SETEQ && Imm == 0) ||
16013            (CC == ISD::SETNE && Imm == 1) ||
16014            (CC == ISD::SETLT && Imm == 1) ||
16015            (CC == ISD::SETULT && Imm == 1);
16016   };
16017 
16018   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
16019     return (CC == ISD::SETEQ && Imm == 1) ||
16020            (CC == ISD::SETNE && Imm == 0) ||
16021            (CC == ISD::SETGT && Imm == 0) ||
16022            (CC == ISD::SETUGT && Imm == 0) ||
16023            (CC == ISD::SETGE && Imm == 1) ||
16024            (CC == ISD::SETUGE && Imm == 1);
16025   };
16026 
16027   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
16028          "unsupported condition");
16029 
16030   SDLoc dl(Int);
16031   SelectionDAG &DAG = DCI.DAG;
16032   SDValue Elements = Int.getOperand(2);
16033   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
16034   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
16035           && "expected single br user");
16036   SDNode *Br = *N->use_begin();
16037   SDValue OtherTarget = Br->getOperand(1);
16038 
16039   // Update the unconditional branch to branch to the given Dest.
16040   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
16041     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
16042     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
16043     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
16044   };
16045 
16046   if (IntOp == Intrinsic::test_set_loop_iterations) {
16047     SDValue Res;
16048     // We expect this 'instruction' to branch when the counter is zero.
16049     if (IsTrueIfZero(CC, Imm)) {
16050       SDValue Ops[] = { Chain, Elements, Dest };
16051       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
16052     } else {
16053       // The logic is the reverse of what we need for WLS, so find the other
16054       // basic block target: the target of the proceeding br.
16055       UpdateUncondBr(Br, Dest, DAG);
16056 
16057       SDValue Ops[] = { Chain, Elements, OtherTarget };
16058       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
16059     }
16060     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
16061     return Res;
16062   } else {
16063     SDValue Size = DAG.getTargetConstant(
16064       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
16065     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
16066     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
16067                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
16068     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
16069 
16070     // We expect this instruction to branch when the count is not zero.
16071     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
16072 
16073     // Update the unconditional branch to target the loop preheader if we've
16074     // found the condition has been reversed.
16075     if (Target == OtherTarget)
16076       UpdateUncondBr(Br, Dest, DAG);
16077 
16078     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16079                         SDValue(LoopDec.getNode(), 1), Chain);
16080 
16081     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
16082     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
16083   }
16084   return SDValue();
16085 }
16086 
16087 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
16088 SDValue
16089 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
16090   SDValue Cmp = N->getOperand(4);
16091   if (Cmp.getOpcode() != ARMISD::CMPZ)
16092     // Only looking at NE cases.
16093     return SDValue();
16094 
16095   EVT VT = N->getValueType(0);
16096   SDLoc dl(N);
16097   SDValue LHS = Cmp.getOperand(0);
16098   SDValue RHS = Cmp.getOperand(1);
16099   SDValue Chain = N->getOperand(0);
16100   SDValue BB = N->getOperand(1);
16101   SDValue ARMcc = N->getOperand(2);
16102   ARMCC::CondCodes CC =
16103     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
16104 
16105   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
16106   // -> (brcond Chain BB CC CPSR Cmp)
16107   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
16108       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
16109       LHS->getOperand(0)->hasOneUse()) {
16110     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
16111     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
16112     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16113     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
16114     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
16115         (LHS01C && LHS01C->getZExtValue() == 1) &&
16116         (LHS1C && LHS1C->getZExtValue() == 1) &&
16117         (RHSC && RHSC->getZExtValue() == 0)) {
16118       return DAG.getNode(
16119           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
16120           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
16121     }
16122   }
16123 
16124   return SDValue();
16125 }
16126 
16127 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
16128 SDValue
16129 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
16130   SDValue Cmp = N->getOperand(4);
16131   if (Cmp.getOpcode() != ARMISD::CMPZ)
16132     // Only looking at EQ and NE cases.
16133     return SDValue();
16134 
16135   EVT VT = N->getValueType(0);
16136   SDLoc dl(N);
16137   SDValue LHS = Cmp.getOperand(0);
16138   SDValue RHS = Cmp.getOperand(1);
16139   SDValue FalseVal = N->getOperand(0);
16140   SDValue TrueVal = N->getOperand(1);
16141   SDValue ARMcc = N->getOperand(2);
16142   ARMCC::CondCodes CC =
16143     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
16144 
16145   // BFI is only available on V6T2+.
16146   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
16147     SDValue R = PerformCMOVToBFICombine(N, DAG);
16148     if (R)
16149       return R;
16150   }
16151 
16152   // Simplify
16153   //   mov     r1, r0
16154   //   cmp     r1, x
16155   //   mov     r0, y
16156   //   moveq   r0, x
16157   // to
16158   //   cmp     r0, x
16159   //   movne   r0, y
16160   //
16161   //   mov     r1, r0
16162   //   cmp     r1, x
16163   //   mov     r0, x
16164   //   movne   r0, y
16165   // to
16166   //   cmp     r0, x
16167   //   movne   r0, y
16168   /// FIXME: Turn this into a target neutral optimization?
16169   SDValue Res;
16170   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
16171     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
16172                       N->getOperand(3), Cmp);
16173   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
16174     SDValue ARMcc;
16175     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
16176     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
16177                       N->getOperand(3), NewCmp);
16178   }
16179 
16180   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
16181   // -> (cmov F T CC CPSR Cmp)
16182   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
16183     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
16184     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16185     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
16186     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
16187         (LHS1C && LHS1C->getZExtValue() == 1) &&
16188         (RHSC && RHSC->getZExtValue() == 0)) {
16189       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
16190                          LHS->getOperand(2), LHS->getOperand(3),
16191                          LHS->getOperand(4));
16192     }
16193   }
16194 
16195   if (!VT.isInteger())
16196       return SDValue();
16197 
16198   // Materialize a boolean comparison for integers so we can avoid branching.
16199   if (isNullConstant(FalseVal)) {
16200     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
16201       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
16202         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
16203         // right 5 bits will make that 32 be 1, otherwise it will be 0.
16204         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
16205         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
16206         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
16207                           DAG.getConstant(5, dl, MVT::i32));
16208       } else {
16209         // CMOV 0, 1, ==, (CMPZ x, y) ->
16210         //     (ADDCARRY (SUB x, y), t:0, t:1)
16211         // where t = (SUBCARRY 0, (SUB x, y), 0)
16212         //
16213         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
16214         // x != y. In other words, a carry C == 1 when x == y, C == 0
16215         // otherwise.
16216         // The final ADDCARRY computes
16217         //     x - y + (0 - (x - y)) + C == C
16218         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
16219         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16220         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
16221         // ISD::SUBCARRY returns a borrow but we want the carry here
16222         // actually.
16223         SDValue Carry =
16224             DAG.getNode(ISD::SUB, dl, MVT::i32,
16225                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
16226         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
16227       }
16228     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
16229                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
16230       // This seems pointless but will allow us to combine it further below.
16231       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
16232       SDValue Sub =
16233           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
16234       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
16235                                           Sub.getValue(1), SDValue());
16236       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
16237                         N->getOperand(3), CPSRGlue.getValue(1));
16238       FalseVal = Sub;
16239     }
16240   } else if (isNullConstant(TrueVal)) {
16241     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
16242         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
16243       // This seems pointless but will allow us to combine it further below
16244       // Note that we change == for != as this is the dual for the case above.
16245       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
16246       SDValue Sub =
16247           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
16248       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
16249                                           Sub.getValue(1), SDValue());
16250       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
16251                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
16252                         N->getOperand(3), CPSRGlue.getValue(1));
16253       FalseVal = Sub;
16254     }
16255   }
16256 
16257   // On Thumb1, the DAG above may be further combined if z is a power of 2
16258   // (z == 2 ^ K).
16259   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
16260   // t1 = (USUBO (SUB x, y), 1)
16261   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
16262   // Result = if K != 0 then (SHL t2:0, K) else t2:0
16263   //
16264   // This also handles the special case of comparing against zero; it's
16265   // essentially, the same pattern, except there's no SUBS:
16266   // CMOV x, z, !=, (CMPZ x, 0) ->
16267   // t1 = (USUBO x, 1)
16268   // t2 = (SUBCARRY x, t1:0, t1:1)
16269   // Result = if K != 0 then (SHL t2:0, K) else t2:0
16270   const APInt *TrueConst;
16271   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
16272       ((FalseVal.getOpcode() == ARMISD::SUBS &&
16273         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
16274        (FalseVal == LHS && isNullConstant(RHS))) &&
16275       (TrueConst = isPowerOf2Constant(TrueVal))) {
16276     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16277     unsigned ShiftAmount = TrueConst->logBase2();
16278     if (ShiftAmount)
16279       TrueVal = DAG.getConstant(1, dl, VT);
16280     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
16281     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
16282 
16283     if (ShiftAmount)
16284       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
16285                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
16286   }
16287 
16288   if (Res.getNode()) {
16289     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
16290     // Capture demanded bits information that would be otherwise lost.
16291     if (Known.Zero == 0xfffffffe)
16292       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16293                         DAG.getValueType(MVT::i1));
16294     else if (Known.Zero == 0xffffff00)
16295       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16296                         DAG.getValueType(MVT::i8));
16297     else if (Known.Zero == 0xffff0000)
16298       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16299                         DAG.getValueType(MVT::i16));
16300   }
16301 
16302   return Res;
16303 }
16304 
16305 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
16306                                     const ARMSubtarget *ST) {
16307   SDValue Src = N->getOperand(0);
16308   EVT DstVT = N->getValueType(0);
16309 
16310   // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
16311   if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
16312     EVT SrcVT = Src.getValueType();
16313     if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
16314       return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
16315   }
16316 
16317   // We may have a bitcast of something that has already had this bitcast
16318   // combine performed on it, so skip past any VECTOR_REG_CASTs.
16319   while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
16320     Src = Src.getOperand(0);
16321 
16322   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
16323   // would be generated is at least the width of the element type.
16324   EVT SrcVT = Src.getValueType();
16325   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
16326        Src.getOpcode() == ARMISD::VMVNIMM ||
16327        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
16328       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
16329       DAG.getDataLayout().isBigEndian())
16330     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
16331 
16332   return SDValue();
16333 }
16334 
16335 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
16336                                              DAGCombinerInfo &DCI) const {
16337   switch (N->getOpcode()) {
16338   default: break;
16339   case ISD::SELECT_CC:
16340   case ISD::SELECT:     return PerformSELECTCombine(N, DCI, Subtarget);
16341   case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
16342   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
16343   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
16344   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
16345   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
16346   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
16347   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
16348   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
16349   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
16350   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
16351   case ISD::BRCOND:
16352   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
16353   case ARMISD::ADDC:
16354   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
16355   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
16356   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
16357   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
16358   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
16359   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
16360   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI);
16361   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
16362   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
16363   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
16364   case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI);
16365   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
16366   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
16367   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
16368   case ISD::FP_TO_SINT:
16369   case ISD::FP_TO_UINT:
16370     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
16371   case ISD::FDIV:
16372     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
16373   case ISD::INTRINSIC_WO_CHAIN:
16374     return PerformIntrinsicCombine(N, DCI);
16375   case ISD::SHL:
16376   case ISD::SRA:
16377   case ISD::SRL:
16378     return PerformShiftCombine(N, DCI, Subtarget);
16379   case ISD::SIGN_EXTEND:
16380   case ISD::ZERO_EXTEND:
16381   case ISD::ANY_EXTEND:
16382     return PerformExtendCombine(N, DCI.DAG, Subtarget);
16383   case ISD::FP_EXTEND:
16384     return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
16385   case ISD::SMIN:
16386   case ISD::UMIN:
16387   case ISD::SMAX:
16388   case ISD::UMAX:
16389     return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
16390   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
16391   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
16392   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
16393   case ARMISD::VLD1DUP:
16394   case ARMISD::VLD2DUP:
16395   case ARMISD::VLD3DUP:
16396   case ARMISD::VLD4DUP:
16397     return PerformVLDCombine(N, DCI);
16398   case ARMISD::BUILD_VECTOR:
16399     return PerformARMBUILD_VECTORCombine(N, DCI);
16400   case ISD::BITCAST:
16401     return PerformBITCASTCombine(N, DCI.DAG, Subtarget);
16402   case ARMISD::PREDICATE_CAST:
16403     return PerformPREDICATE_CASTCombine(N, DCI);
16404   case ARMISD::VECTOR_REG_CAST:
16405     return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
16406   case ARMISD::VCMP:
16407     return PerformVCMPCombine(N, DCI, Subtarget);
16408   case ISD::VECREDUCE_ADD:
16409     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
16410   case ARMISD::VMOVN:
16411     return PerformVMOVNCombine(N, DCI);
16412   case ARMISD::VQMOVNs:
16413   case ARMISD::VQMOVNu:
16414     return PerformVQMOVNCombine(N, DCI);
16415   case ARMISD::ASRL:
16416   case ARMISD::LSRL:
16417   case ARMISD::LSLL:
16418     return PerformLongShiftCombine(N, DCI.DAG);
16419   case ARMISD::SMULWB: {
16420     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16421     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16422     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16423       return SDValue();
16424     break;
16425   }
16426   case ARMISD::SMULWT: {
16427     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16428     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16429     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16430       return SDValue();
16431     break;
16432   }
16433   case ARMISD::SMLALBB:
16434   case ARMISD::QADD16b:
16435   case ARMISD::QSUB16b: {
16436     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16437     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16438     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16439         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16440       return SDValue();
16441     break;
16442   }
16443   case ARMISD::SMLALBT: {
16444     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
16445     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16446     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
16447     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16448     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
16449         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
16450       return SDValue();
16451     break;
16452   }
16453   case ARMISD::SMLALTB: {
16454     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
16455     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16456     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
16457     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16458     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
16459         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
16460       return SDValue();
16461     break;
16462   }
16463   case ARMISD::SMLALTT: {
16464     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16465     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16466     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16467         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16468       return SDValue();
16469     break;
16470   }
16471   case ARMISD::QADD8b:
16472   case ARMISD::QSUB8b: {
16473     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16474     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
16475     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16476         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16477       return SDValue();
16478     break;
16479   }
16480   case ISD::INTRINSIC_VOID:
16481   case ISD::INTRINSIC_W_CHAIN:
16482     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
16483     case Intrinsic::arm_neon_vld1:
16484     case Intrinsic::arm_neon_vld1x2:
16485     case Intrinsic::arm_neon_vld1x3:
16486     case Intrinsic::arm_neon_vld1x4:
16487     case Intrinsic::arm_neon_vld2:
16488     case Intrinsic::arm_neon_vld3:
16489     case Intrinsic::arm_neon_vld4:
16490     case Intrinsic::arm_neon_vld2lane:
16491     case Intrinsic::arm_neon_vld3lane:
16492     case Intrinsic::arm_neon_vld4lane:
16493     case Intrinsic::arm_neon_vld2dup:
16494     case Intrinsic::arm_neon_vld3dup:
16495     case Intrinsic::arm_neon_vld4dup:
16496     case Intrinsic::arm_neon_vst1:
16497     case Intrinsic::arm_neon_vst1x2:
16498     case Intrinsic::arm_neon_vst1x3:
16499     case Intrinsic::arm_neon_vst1x4:
16500     case Intrinsic::arm_neon_vst2:
16501     case Intrinsic::arm_neon_vst3:
16502     case Intrinsic::arm_neon_vst4:
16503     case Intrinsic::arm_neon_vst2lane:
16504     case Intrinsic::arm_neon_vst3lane:
16505     case Intrinsic::arm_neon_vst4lane:
16506       return PerformVLDCombine(N, DCI);
16507     case Intrinsic::arm_mve_vld2q:
16508     case Intrinsic::arm_mve_vld4q:
16509     case Intrinsic::arm_mve_vst2q:
16510     case Intrinsic::arm_mve_vst4q:
16511       return PerformMVEVLDCombine(N, DCI);
16512     default: break;
16513     }
16514     break;
16515   }
16516   return SDValue();
16517 }
16518 
16519 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
16520                                                           EVT VT) const {
16521   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
16522 }
16523 
16524 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
16525                                                        unsigned Alignment,
16526                                                        MachineMemOperand::Flags,
16527                                                        bool *Fast) const {
16528   // Depends what it gets converted into if the type is weird.
16529   if (!VT.isSimple())
16530     return false;
16531 
16532   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
16533   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
16534   auto Ty = VT.getSimpleVT().SimpleTy;
16535 
16536   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
16537     // Unaligned access can use (for example) LRDB, LRDH, LDR
16538     if (AllowsUnaligned) {
16539       if (Fast)
16540         *Fast = Subtarget->hasV7Ops();
16541       return true;
16542     }
16543   }
16544 
16545   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
16546     // For any little-endian targets with neon, we can support unaligned ld/st
16547     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
16548     // A big-endian target may also explicitly support unaligned accesses
16549     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
16550       if (Fast)
16551         *Fast = true;
16552       return true;
16553     }
16554   }
16555 
16556   if (!Subtarget->hasMVEIntegerOps())
16557     return false;
16558 
16559   // These are for predicates
16560   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
16561     if (Fast)
16562       *Fast = true;
16563     return true;
16564   }
16565 
16566   // These are for truncated stores/narrowing loads. They are fine so long as
16567   // the alignment is at least the size of the item being loaded
16568   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
16569       Alignment >= VT.getScalarSizeInBits() / 8) {
16570     if (Fast)
16571       *Fast = true;
16572     return true;
16573   }
16574 
16575   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
16576   // VSTRW.U32 all store the vector register in exactly the same format, and
16577   // differ only in the range of their immediate offset field and the required
16578   // alignment. So there is always a store that can be used, regardless of
16579   // actual type.
16580   //
16581   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
16582   // VREV64.8) pair and get the same effect. This will likely be better than
16583   // aligning the vector through the stack.
16584   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
16585       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
16586       Ty == MVT::v2f64) {
16587     if (Fast)
16588       *Fast = true;
16589     return true;
16590   }
16591 
16592   return false;
16593 }
16594 
16595 
16596 EVT ARMTargetLowering::getOptimalMemOpType(
16597     const MemOp &Op, const AttributeList &FuncAttributes) const {
16598   // See if we can use NEON instructions for this...
16599   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
16600       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
16601     bool Fast;
16602     if (Op.size() >= 16 &&
16603         (Op.isAligned(Align(16)) ||
16604          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
16605                                          MachineMemOperand::MONone, &Fast) &&
16606           Fast))) {
16607       return MVT::v2f64;
16608     } else if (Op.size() >= 8 &&
16609                (Op.isAligned(Align(8)) ||
16610                 (allowsMisalignedMemoryAccesses(
16611                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
16612                  Fast))) {
16613       return MVT::f64;
16614     }
16615   }
16616 
16617   // Let the target-independent logic figure it out.
16618   return MVT::Other;
16619 }
16620 
16621 // 64-bit integers are split into their high and low parts and held in two
16622 // different registers, so the trunc is free since the low register can just
16623 // be used.
16624 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
16625   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
16626     return false;
16627   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
16628   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
16629   return (SrcBits == 64 && DestBits == 32);
16630 }
16631 
16632 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
16633   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
16634       !DstVT.isInteger())
16635     return false;
16636   unsigned SrcBits = SrcVT.getSizeInBits();
16637   unsigned DestBits = DstVT.getSizeInBits();
16638   return (SrcBits == 64 && DestBits == 32);
16639 }
16640 
16641 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16642   if (Val.getOpcode() != ISD::LOAD)
16643     return false;
16644 
16645   EVT VT1 = Val.getValueType();
16646   if (!VT1.isSimple() || !VT1.isInteger() ||
16647       !VT2.isSimple() || !VT2.isInteger())
16648     return false;
16649 
16650   switch (VT1.getSimpleVT().SimpleTy) {
16651   default: break;
16652   case MVT::i1:
16653   case MVT::i8:
16654   case MVT::i16:
16655     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
16656     return true;
16657   }
16658 
16659   return false;
16660 }
16661 
16662 bool ARMTargetLowering::isFNegFree(EVT VT) const {
16663   if (!VT.isSimple())
16664     return false;
16665 
16666   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
16667   // negate values directly (fneg is free). So, we don't want to let the DAG
16668   // combiner rewrite fneg into xors and some other instructions.  For f16 and
16669   // FullFP16 argument passing, some bitcast nodes may be introduced,
16670   // triggering this DAG combine rewrite, so we are avoiding that with this.
16671   switch (VT.getSimpleVT().SimpleTy) {
16672   default: break;
16673   case MVT::f16:
16674     return Subtarget->hasFullFP16();
16675   }
16676 
16677   return false;
16678 }
16679 
16680 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
16681 /// of the vector elements.
16682 static bool areExtractExts(Value *Ext1, Value *Ext2) {
16683   auto areExtDoubled = [](Instruction *Ext) {
16684     return Ext->getType()->getScalarSizeInBits() ==
16685            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
16686   };
16687 
16688   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
16689       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
16690       !areExtDoubled(cast<Instruction>(Ext1)) ||
16691       !areExtDoubled(cast<Instruction>(Ext2)))
16692     return false;
16693 
16694   return true;
16695 }
16696 
16697 /// Check if sinking \p I's operands to I's basic block is profitable, because
16698 /// the operands can be folded into a target instruction, e.g.
16699 /// sext/zext can be folded into vsubl.
16700 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
16701                                            SmallVectorImpl<Use *> &Ops) const {
16702   if (!I->getType()->isVectorTy())
16703     return false;
16704 
16705   if (Subtarget->hasNEON()) {
16706     switch (I->getOpcode()) {
16707     case Instruction::Sub:
16708     case Instruction::Add: {
16709       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
16710         return false;
16711       Ops.push_back(&I->getOperandUse(0));
16712       Ops.push_back(&I->getOperandUse(1));
16713       return true;
16714     }
16715     default:
16716       return false;
16717     }
16718   }
16719 
16720   if (!Subtarget->hasMVEIntegerOps())
16721     return false;
16722 
16723   auto IsFMSMul = [&](Instruction *I) {
16724     if (!I->hasOneUse())
16725       return false;
16726     auto *Sub = cast<Instruction>(*I->users().begin());
16727     return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
16728   };
16729   auto IsFMS = [&](Instruction *I) {
16730     if (match(I->getOperand(0), m_FNeg(m_Value())) ||
16731         match(I->getOperand(1), m_FNeg(m_Value())))
16732       return true;
16733     return false;
16734   };
16735 
16736   auto IsSinker = [&](Instruction *I, int Operand) {
16737     switch (I->getOpcode()) {
16738     case Instruction::Add:
16739     case Instruction::Mul:
16740     case Instruction::FAdd:
16741     case Instruction::ICmp:
16742     case Instruction::FCmp:
16743       return true;
16744     case Instruction::FMul:
16745       return !IsFMSMul(I);
16746     case Instruction::Sub:
16747     case Instruction::FSub:
16748     case Instruction::Shl:
16749     case Instruction::LShr:
16750     case Instruction::AShr:
16751       return Operand == 1;
16752     case Instruction::Call:
16753       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
16754         switch (II->getIntrinsicID()) {
16755         case Intrinsic::fma:
16756           return !IsFMS(I);
16757         case Intrinsic::arm_mve_add_predicated:
16758         case Intrinsic::arm_mve_mul_predicated:
16759         case Intrinsic::arm_mve_qadd_predicated:
16760         case Intrinsic::arm_mve_hadd_predicated:
16761         case Intrinsic::arm_mve_vqdmull_predicated:
16762         case Intrinsic::arm_mve_qdmulh_predicated:
16763         case Intrinsic::arm_mve_qrdmulh_predicated:
16764         case Intrinsic::arm_mve_fma_predicated:
16765           return true;
16766         case Intrinsic::arm_mve_sub_predicated:
16767         case Intrinsic::arm_mve_qsub_predicated:
16768         case Intrinsic::arm_mve_hsub_predicated:
16769           return Operand == 1;
16770         default:
16771           return false;
16772         }
16773       }
16774       return false;
16775     default:
16776       return false;
16777     }
16778   };
16779 
16780   for (auto OpIdx : enumerate(I->operands())) {
16781     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
16782     // Make sure we are not already sinking this operand
16783     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
16784       continue;
16785 
16786     Instruction *Shuffle = Op;
16787     if (Shuffle->getOpcode() == Instruction::BitCast)
16788       Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
16789     // We are looking for a splat that can be sunk.
16790     if (!Shuffle ||
16791         !match(Shuffle, m_Shuffle(
16792                             m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
16793                             m_Undef(), m_ZeroMask())))
16794       continue;
16795     if (!IsSinker(I, OpIdx.index()))
16796       continue;
16797 
16798     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
16799     // and vector registers
16800     for (Use &U : Op->uses()) {
16801       Instruction *Insn = cast<Instruction>(U.getUser());
16802       if (!IsSinker(Insn, U.getOperandNo()))
16803         return false;
16804     }
16805 
16806     Ops.push_back(&Shuffle->getOperandUse(0));
16807     if (Shuffle != Op)
16808       Ops.push_back(&Op->getOperandUse(0));
16809     Ops.push_back(&OpIdx.value());
16810   }
16811   return true;
16812 }
16813 
16814 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
16815   if (!Subtarget->hasMVEIntegerOps())
16816     return nullptr;
16817   Type *SVIType = SVI->getType();
16818   Type *ScalarType = SVIType->getScalarType();
16819 
16820   if (ScalarType->isFloatTy())
16821     return Type::getInt32Ty(SVIType->getContext());
16822   if (ScalarType->isHalfTy())
16823     return Type::getInt16Ty(SVIType->getContext());
16824   return nullptr;
16825 }
16826 
16827 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
16828   EVT VT = ExtVal.getValueType();
16829 
16830   if (!isTypeLegal(VT))
16831     return false;
16832 
16833   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
16834     if (Ld->isExpandingLoad())
16835       return false;
16836   }
16837 
16838   if (Subtarget->hasMVEIntegerOps())
16839     return true;
16840 
16841   // Don't create a loadext if we can fold the extension into a wide/long
16842   // instruction.
16843   // If there's more than one user instruction, the loadext is desirable no
16844   // matter what.  There can be two uses by the same instruction.
16845   if (ExtVal->use_empty() ||
16846       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
16847     return true;
16848 
16849   SDNode *U = *ExtVal->use_begin();
16850   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
16851        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
16852     return false;
16853 
16854   return true;
16855 }
16856 
16857 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16858   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16859     return false;
16860 
16861   if (!isTypeLegal(EVT::getEVT(Ty1)))
16862     return false;
16863 
16864   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16865 
16866   // Assuming the caller doesn't have a zeroext or signext return parameter,
16867   // truncation all the way down to i1 is valid.
16868   return true;
16869 }
16870 
16871 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
16872                                                 const AddrMode &AM, Type *Ty,
16873                                                 unsigned AS) const {
16874   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
16875     if (Subtarget->hasFPAO())
16876       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
16877     return 0;
16878   }
16879   return -1;
16880 }
16881 
16882 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
16883 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
16884 /// expanded to FMAs when this method returns true, otherwise fmuladd is
16885 /// expanded to fmul + fadd.
16886 ///
16887 /// ARM supports both fused and unfused multiply-add operations; we already
16888 /// lower a pair of fmul and fadd to the latter so it's not clear that there
16889 /// would be a gain or that the gain would be worthwhile enough to risk
16890 /// correctness bugs.
16891 ///
16892 /// For MVE, we set this to true as it helps simplify the need for some
16893 /// patterns (and we don't have the non-fused floating point instruction).
16894 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16895                                                    EVT VT) const {
16896   if (!VT.isSimple())
16897     return false;
16898 
16899   switch (VT.getSimpleVT().SimpleTy) {
16900   case MVT::v4f32:
16901   case MVT::v8f16:
16902     return Subtarget->hasMVEFloatOps();
16903   case MVT::f16:
16904     return Subtarget->useFPVFMx16();
16905   case MVT::f32:
16906     return Subtarget->useFPVFMx();
16907   case MVT::f64:
16908     return Subtarget->useFPVFMx64();
16909   default:
16910     break;
16911   }
16912 
16913   return false;
16914 }
16915 
16916 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
16917   if (V < 0)
16918     return false;
16919 
16920   unsigned Scale = 1;
16921   switch (VT.getSimpleVT().SimpleTy) {
16922   case MVT::i1:
16923   case MVT::i8:
16924     // Scale == 1;
16925     break;
16926   case MVT::i16:
16927     // Scale == 2;
16928     Scale = 2;
16929     break;
16930   default:
16931     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
16932     // Scale == 4;
16933     Scale = 4;
16934     break;
16935   }
16936 
16937   if ((V & (Scale - 1)) != 0)
16938     return false;
16939   return isUInt<5>(V / Scale);
16940 }
16941 
16942 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
16943                                       const ARMSubtarget *Subtarget) {
16944   if (!VT.isInteger() && !VT.isFloatingPoint())
16945     return false;
16946   if (VT.isVector() && Subtarget->hasNEON())
16947     return false;
16948   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
16949       !Subtarget->hasMVEFloatOps())
16950     return false;
16951 
16952   bool IsNeg = false;
16953   if (V < 0) {
16954     IsNeg = true;
16955     V = -V;
16956   }
16957 
16958   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
16959 
16960   // MVE: size * imm7
16961   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
16962     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
16963     case MVT::i32:
16964     case MVT::f32:
16965       return isShiftedUInt<7,2>(V);
16966     case MVT::i16:
16967     case MVT::f16:
16968       return isShiftedUInt<7,1>(V);
16969     case MVT::i8:
16970       return isUInt<7>(V);
16971     default:
16972       return false;
16973     }
16974   }
16975 
16976   // half VLDR: 2 * imm8
16977   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
16978     return isShiftedUInt<8, 1>(V);
16979   // VLDR and LDRD: 4 * imm8
16980   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
16981     return isShiftedUInt<8, 2>(V);
16982 
16983   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
16984     // + imm12 or - imm8
16985     if (IsNeg)
16986       return isUInt<8>(V);
16987     return isUInt<12>(V);
16988   }
16989 
16990   return false;
16991 }
16992 
16993 /// isLegalAddressImmediate - Return true if the integer value can be used
16994 /// as the offset of the target addressing mode for load / store of the
16995 /// given type.
16996 static bool isLegalAddressImmediate(int64_t V, EVT VT,
16997                                     const ARMSubtarget *Subtarget) {
16998   if (V == 0)
16999     return true;
17000 
17001   if (!VT.isSimple())
17002     return false;
17003 
17004   if (Subtarget->isThumb1Only())
17005     return isLegalT1AddressImmediate(V, VT);
17006   else if (Subtarget->isThumb2())
17007     return isLegalT2AddressImmediate(V, VT, Subtarget);
17008 
17009   // ARM mode.
17010   if (V < 0)
17011     V = - V;
17012   switch (VT.getSimpleVT().SimpleTy) {
17013   default: return false;
17014   case MVT::i1:
17015   case MVT::i8:
17016   case MVT::i32:
17017     // +- imm12
17018     return isUInt<12>(V);
17019   case MVT::i16:
17020     // +- imm8
17021     return isUInt<8>(V);
17022   case MVT::f32:
17023   case MVT::f64:
17024     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
17025       return false;
17026     return isShiftedUInt<8, 2>(V);
17027   }
17028 }
17029 
17030 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
17031                                                       EVT VT) const {
17032   int Scale = AM.Scale;
17033   if (Scale < 0)
17034     return false;
17035 
17036   switch (VT.getSimpleVT().SimpleTy) {
17037   default: return false;
17038   case MVT::i1:
17039   case MVT::i8:
17040   case MVT::i16:
17041   case MVT::i32:
17042     if (Scale == 1)
17043       return true;
17044     // r + r << imm
17045     Scale = Scale & ~1;
17046     return Scale == 2 || Scale == 4 || Scale == 8;
17047   case MVT::i64:
17048     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
17049     // version in Thumb mode.
17050     // r + r
17051     if (Scale == 1)
17052       return true;
17053     // r * 2 (this can be lowered to r + r).
17054     if (!AM.HasBaseReg && Scale == 2)
17055       return true;
17056     return false;
17057   case MVT::isVoid:
17058     // Note, we allow "void" uses (basically, uses that aren't loads or
17059     // stores), because arm allows folding a scale into many arithmetic
17060     // operations.  This should be made more precise and revisited later.
17061 
17062     // Allow r << imm, but the imm has to be a multiple of two.
17063     if (Scale & 1) return false;
17064     return isPowerOf2_32(Scale);
17065   }
17066 }
17067 
17068 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
17069                                                       EVT VT) const {
17070   const int Scale = AM.Scale;
17071 
17072   // Negative scales are not supported in Thumb1.
17073   if (Scale < 0)
17074     return false;
17075 
17076   // Thumb1 addressing modes do not support register scaling excepting the
17077   // following cases:
17078   // 1. Scale == 1 means no scaling.
17079   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
17080   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
17081 }
17082 
17083 /// isLegalAddressingMode - Return true if the addressing mode represented
17084 /// by AM is legal for this target, for a load/store of the specified type.
17085 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
17086                                               const AddrMode &AM, Type *Ty,
17087                                               unsigned AS, Instruction *I) const {
17088   EVT VT = getValueType(DL, Ty, true);
17089   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
17090     return false;
17091 
17092   // Can never fold addr of global into load/store.
17093   if (AM.BaseGV)
17094     return false;
17095 
17096   switch (AM.Scale) {
17097   case 0:  // no scale reg, must be "r+i" or "r", or "i".
17098     break;
17099   default:
17100     // ARM doesn't support any R+R*scale+imm addr modes.
17101     if (AM.BaseOffs)
17102       return false;
17103 
17104     if (!VT.isSimple())
17105       return false;
17106 
17107     if (Subtarget->isThumb1Only())
17108       return isLegalT1ScaledAddressingMode(AM, VT);
17109 
17110     if (Subtarget->isThumb2())
17111       return isLegalT2ScaledAddressingMode(AM, VT);
17112 
17113     int Scale = AM.Scale;
17114     switch (VT.getSimpleVT().SimpleTy) {
17115     default: return false;
17116     case MVT::i1:
17117     case MVT::i8:
17118     case MVT::i32:
17119       if (Scale < 0) Scale = -Scale;
17120       if (Scale == 1)
17121         return true;
17122       // r + r << imm
17123       return isPowerOf2_32(Scale & ~1);
17124     case MVT::i16:
17125     case MVT::i64:
17126       // r +/- r
17127       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
17128         return true;
17129       // r * 2 (this can be lowered to r + r).
17130       if (!AM.HasBaseReg && Scale == 2)
17131         return true;
17132       return false;
17133 
17134     case MVT::isVoid:
17135       // Note, we allow "void" uses (basically, uses that aren't loads or
17136       // stores), because arm allows folding a scale into many arithmetic
17137       // operations.  This should be made more precise and revisited later.
17138 
17139       // Allow r << imm, but the imm has to be a multiple of two.
17140       if (Scale & 1) return false;
17141       return isPowerOf2_32(Scale);
17142     }
17143   }
17144   return true;
17145 }
17146 
17147 /// isLegalICmpImmediate - Return true if the specified immediate is legal
17148 /// icmp immediate, that is the target has icmp instructions which can compare
17149 /// a register against the immediate without having to materialize the
17150 /// immediate into a register.
17151 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17152   // Thumb2 and ARM modes can use cmn for negative immediates.
17153   if (!Subtarget->isThumb())
17154     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
17155            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
17156   if (Subtarget->isThumb2())
17157     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
17158            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
17159   // Thumb1 doesn't have cmn, and only 8-bit immediates.
17160   return Imm >= 0 && Imm <= 255;
17161 }
17162 
17163 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
17164 /// *or sub* immediate, that is the target has add or sub instructions which can
17165 /// add a register with the immediate without having to materialize the
17166 /// immediate into a register.
17167 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
17168   // Same encoding for add/sub, just flip the sign.
17169   int64_t AbsImm = std::abs(Imm);
17170   if (!Subtarget->isThumb())
17171     return ARM_AM::getSOImmVal(AbsImm) != -1;
17172   if (Subtarget->isThumb2())
17173     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
17174   // Thumb1 only has 8-bit unsigned immediate.
17175   return AbsImm >= 0 && AbsImm <= 255;
17176 }
17177 
17178 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
17179                                       bool isSEXTLoad, SDValue &Base,
17180                                       SDValue &Offset, bool &isInc,
17181                                       SelectionDAG &DAG) {
17182   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17183     return false;
17184 
17185   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
17186     // AddressingMode 3
17187     Base = Ptr->getOperand(0);
17188     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17189       int RHSC = (int)RHS->getZExtValue();
17190       if (RHSC < 0 && RHSC > -256) {
17191         assert(Ptr->getOpcode() == ISD::ADD);
17192         isInc = false;
17193         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17194         return true;
17195       }
17196     }
17197     isInc = (Ptr->getOpcode() == ISD::ADD);
17198     Offset = Ptr->getOperand(1);
17199     return true;
17200   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
17201     // AddressingMode 2
17202     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17203       int RHSC = (int)RHS->getZExtValue();
17204       if (RHSC < 0 && RHSC > -0x1000) {
17205         assert(Ptr->getOpcode() == ISD::ADD);
17206         isInc = false;
17207         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17208         Base = Ptr->getOperand(0);
17209         return true;
17210       }
17211     }
17212 
17213     if (Ptr->getOpcode() == ISD::ADD) {
17214       isInc = true;
17215       ARM_AM::ShiftOpc ShOpcVal=
17216         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
17217       if (ShOpcVal != ARM_AM::no_shift) {
17218         Base = Ptr->getOperand(1);
17219         Offset = Ptr->getOperand(0);
17220       } else {
17221         Base = Ptr->getOperand(0);
17222         Offset = Ptr->getOperand(1);
17223       }
17224       return true;
17225     }
17226 
17227     isInc = (Ptr->getOpcode() == ISD::ADD);
17228     Base = Ptr->getOperand(0);
17229     Offset = Ptr->getOperand(1);
17230     return true;
17231   }
17232 
17233   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
17234   return false;
17235 }
17236 
17237 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
17238                                      bool isSEXTLoad, SDValue &Base,
17239                                      SDValue &Offset, bool &isInc,
17240                                      SelectionDAG &DAG) {
17241   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17242     return false;
17243 
17244   Base = Ptr->getOperand(0);
17245   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17246     int RHSC = (int)RHS->getZExtValue();
17247     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
17248       assert(Ptr->getOpcode() == ISD::ADD);
17249       isInc = false;
17250       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17251       return true;
17252     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
17253       isInc = Ptr->getOpcode() == ISD::ADD;
17254       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
17255       return true;
17256     }
17257   }
17258 
17259   return false;
17260 }
17261 
17262 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
17263                                       bool isSEXTLoad, bool IsMasked, bool isLE,
17264                                       SDValue &Base, SDValue &Offset,
17265                                       bool &isInc, SelectionDAG &DAG) {
17266   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17267     return false;
17268   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
17269     return false;
17270 
17271   // We allow LE non-masked loads to change the type (for example use a vldrb.8
17272   // as opposed to a vldrw.32). This can allow extra addressing modes or
17273   // alignments for what is otherwise an equivalent instruction.
17274   bool CanChangeType = isLE && !IsMasked;
17275 
17276   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
17277   int RHSC = (int)RHS->getZExtValue();
17278 
17279   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
17280     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
17281       assert(Ptr->getOpcode() == ISD::ADD);
17282       isInc = false;
17283       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17284       return true;
17285     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
17286       isInc = Ptr->getOpcode() == ISD::ADD;
17287       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
17288       return true;
17289     }
17290     return false;
17291   };
17292 
17293   // Try to find a matching instruction based on s/zext, Alignment, Offset and
17294   // (in BE/masked) type.
17295   Base = Ptr->getOperand(0);
17296   if (VT == MVT::v4i16) {
17297     if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
17298       return true;
17299   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
17300     if (IsInRange(RHSC, 0x80, 1))
17301       return true;
17302   } else if (Alignment >= 4 &&
17303              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
17304              IsInRange(RHSC, 0x80, 4))
17305     return true;
17306   else if (Alignment >= 2 &&
17307            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
17308            IsInRange(RHSC, 0x80, 2))
17309     return true;
17310   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
17311     return true;
17312   return false;
17313 }
17314 
17315 /// getPreIndexedAddressParts - returns true by value, base pointer and
17316 /// offset pointer and addressing mode by reference if the node's address
17317 /// can be legally represented as pre-indexed load / store address.
17318 bool
17319 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
17320                                              SDValue &Offset,
17321                                              ISD::MemIndexedMode &AM,
17322                                              SelectionDAG &DAG) const {
17323   if (Subtarget->isThumb1Only())
17324     return false;
17325 
17326   EVT VT;
17327   SDValue Ptr;
17328   Align Alignment;
17329   bool isSEXTLoad = false;
17330   bool IsMasked = false;
17331   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17332     Ptr = LD->getBasePtr();
17333     VT = LD->getMemoryVT();
17334     Alignment = LD->getAlign();
17335     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17336   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17337     Ptr = ST->getBasePtr();
17338     VT = ST->getMemoryVT();
17339     Alignment = ST->getAlign();
17340   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17341     Ptr = LD->getBasePtr();
17342     VT = LD->getMemoryVT();
17343     Alignment = LD->getAlign();
17344     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17345     IsMasked = true;
17346   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17347     Ptr = ST->getBasePtr();
17348     VT = ST->getMemoryVT();
17349     Alignment = ST->getAlign();
17350     IsMasked = true;
17351   } else
17352     return false;
17353 
17354   bool isInc;
17355   bool isLegal = false;
17356   if (VT.isVector())
17357     isLegal = Subtarget->hasMVEIntegerOps() &&
17358               getMVEIndexedAddressParts(
17359                   Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
17360                   Subtarget->isLittle(), Base, Offset, isInc, DAG);
17361   else {
17362     if (Subtarget->isThumb2())
17363       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17364                                          Offset, isInc, DAG);
17365     else
17366       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17367                                           Offset, isInc, DAG);
17368   }
17369   if (!isLegal)
17370     return false;
17371 
17372   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
17373   return true;
17374 }
17375 
17376 /// getPostIndexedAddressParts - returns true by value, base pointer and
17377 /// offset pointer and addressing mode by reference if this node can be
17378 /// combined with a load / store to form a post-indexed load / store.
17379 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
17380                                                    SDValue &Base,
17381                                                    SDValue &Offset,
17382                                                    ISD::MemIndexedMode &AM,
17383                                                    SelectionDAG &DAG) const {
17384   EVT VT;
17385   SDValue Ptr;
17386   Align Alignment;
17387   bool isSEXTLoad = false, isNonExt;
17388   bool IsMasked = false;
17389   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17390     VT = LD->getMemoryVT();
17391     Ptr = LD->getBasePtr();
17392     Alignment = LD->getAlign();
17393     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17394     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17395   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17396     VT = ST->getMemoryVT();
17397     Ptr = ST->getBasePtr();
17398     Alignment = ST->getAlign();
17399     isNonExt = !ST->isTruncatingStore();
17400   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17401     VT = LD->getMemoryVT();
17402     Ptr = LD->getBasePtr();
17403     Alignment = LD->getAlign();
17404     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17405     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17406     IsMasked = true;
17407   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17408     VT = ST->getMemoryVT();
17409     Ptr = ST->getBasePtr();
17410     Alignment = ST->getAlign();
17411     isNonExt = !ST->isTruncatingStore();
17412     IsMasked = true;
17413   } else
17414     return false;
17415 
17416   if (Subtarget->isThumb1Only()) {
17417     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
17418     // must be non-extending/truncating, i32, with an offset of 4.
17419     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
17420     if (Op->getOpcode() != ISD::ADD || !isNonExt)
17421       return false;
17422     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
17423     if (!RHS || RHS->getZExtValue() != 4)
17424       return false;
17425 
17426     Offset = Op->getOperand(1);
17427     Base = Op->getOperand(0);
17428     AM = ISD::POST_INC;
17429     return true;
17430   }
17431 
17432   bool isInc;
17433   bool isLegal = false;
17434   if (VT.isVector())
17435     isLegal = Subtarget->hasMVEIntegerOps() &&
17436               getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
17437                                         Subtarget->isLittle(), Base, Offset,
17438                                         isInc, DAG);
17439   else {
17440     if (Subtarget->isThumb2())
17441       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17442                                          isInc, DAG);
17443     else
17444       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17445                                           isInc, DAG);
17446   }
17447   if (!isLegal)
17448     return false;
17449 
17450   if (Ptr != Base) {
17451     // Swap base ptr and offset to catch more post-index load / store when
17452     // it's legal. In Thumb2 mode, offset must be an immediate.
17453     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
17454         !Subtarget->isThumb2())
17455       std::swap(Base, Offset);
17456 
17457     // Post-indexed load / store update the base pointer.
17458     if (Ptr != Base)
17459       return false;
17460   }
17461 
17462   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
17463   return true;
17464 }
17465 
17466 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17467                                                       KnownBits &Known,
17468                                                       const APInt &DemandedElts,
17469                                                       const SelectionDAG &DAG,
17470                                                       unsigned Depth) const {
17471   unsigned BitWidth = Known.getBitWidth();
17472   Known.resetAll();
17473   switch (Op.getOpcode()) {
17474   default: break;
17475   case ARMISD::ADDC:
17476   case ARMISD::ADDE:
17477   case ARMISD::SUBC:
17478   case ARMISD::SUBE:
17479     // Special cases when we convert a carry to a boolean.
17480     if (Op.getResNo() == 0) {
17481       SDValue LHS = Op.getOperand(0);
17482       SDValue RHS = Op.getOperand(1);
17483       // (ADDE 0, 0, C) will give us a single bit.
17484       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
17485           isNullConstant(RHS)) {
17486         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17487         return;
17488       }
17489     }
17490     break;
17491   case ARMISD::CMOV: {
17492     // Bits are known zero/one if known on the LHS and RHS.
17493     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
17494     if (Known.isUnknown())
17495       return;
17496 
17497     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
17498     Known = KnownBits::commonBits(Known, KnownRHS);
17499     return;
17500   }
17501   case ISD::INTRINSIC_W_CHAIN: {
17502     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
17503     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
17504     switch (IntID) {
17505     default: return;
17506     case Intrinsic::arm_ldaex:
17507     case Intrinsic::arm_ldrex: {
17508       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
17509       unsigned MemBits = VT.getScalarSizeInBits();
17510       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
17511       return;
17512     }
17513     }
17514   }
17515   case ARMISD::BFI: {
17516     // Conservatively, we can recurse down the first operand
17517     // and just mask out all affected bits.
17518     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
17519 
17520     // The operand to BFI is already a mask suitable for removing the bits it
17521     // sets.
17522     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
17523     const APInt &Mask = CI->getAPIntValue();
17524     Known.Zero &= Mask;
17525     Known.One &= Mask;
17526     return;
17527   }
17528   case ARMISD::VGETLANEs:
17529   case ARMISD::VGETLANEu: {
17530     const SDValue &SrcSV = Op.getOperand(0);
17531     EVT VecVT = SrcSV.getValueType();
17532     assert(VecVT.isVector() && "VGETLANE expected a vector type");
17533     const unsigned NumSrcElts = VecVT.getVectorNumElements();
17534     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
17535     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
17536            "VGETLANE index out of bounds");
17537     unsigned Idx = Pos->getZExtValue();
17538     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
17539     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
17540 
17541     EVT VT = Op.getValueType();
17542     const unsigned DstSz = VT.getScalarSizeInBits();
17543     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
17544     (void)SrcSz;
17545     assert(SrcSz == Known.getBitWidth());
17546     assert(DstSz > SrcSz);
17547     if (Op.getOpcode() == ARMISD::VGETLANEs)
17548       Known = Known.sext(DstSz);
17549     else {
17550       Known = Known.zext(DstSz);
17551     }
17552     assert(DstSz == Known.getBitWidth());
17553     break;
17554   }
17555   case ARMISD::VMOVrh: {
17556     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
17557     assert(KnownOp.getBitWidth() == 16);
17558     Known = KnownOp.zext(32);
17559     break;
17560   }
17561   }
17562 }
17563 
17564 bool ARMTargetLowering::targetShrinkDemandedConstant(
17565     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
17566     TargetLoweringOpt &TLO) const {
17567   // Delay optimization, so we don't have to deal with illegal types, or block
17568   // optimizations.
17569   if (!TLO.LegalOps)
17570     return false;
17571 
17572   // Only optimize AND for now.
17573   if (Op.getOpcode() != ISD::AND)
17574     return false;
17575 
17576   EVT VT = Op.getValueType();
17577 
17578   // Ignore vectors.
17579   if (VT.isVector())
17580     return false;
17581 
17582   assert(VT == MVT::i32 && "Unexpected integer type");
17583 
17584   // Make sure the RHS really is a constant.
17585   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
17586   if (!C)
17587     return false;
17588 
17589   unsigned Mask = C->getZExtValue();
17590 
17591   unsigned Demanded = DemandedBits.getZExtValue();
17592   unsigned ShrunkMask = Mask & Demanded;
17593   unsigned ExpandedMask = Mask | ~Demanded;
17594 
17595   // If the mask is all zeros, let the target-independent code replace the
17596   // result with zero.
17597   if (ShrunkMask == 0)
17598     return false;
17599 
17600   // If the mask is all ones, erase the AND. (Currently, the target-independent
17601   // code won't do this, so we have to do it explicitly to avoid an infinite
17602   // loop in obscure cases.)
17603   if (ExpandedMask == ~0U)
17604     return TLO.CombineTo(Op, Op.getOperand(0));
17605 
17606   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
17607     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
17608   };
17609   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
17610     if (NewMask == Mask)
17611       return true;
17612     SDLoc DL(Op);
17613     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
17614     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
17615     return TLO.CombineTo(Op, NewOp);
17616   };
17617 
17618   // Prefer uxtb mask.
17619   if (IsLegalMask(0xFF))
17620     return UseMask(0xFF);
17621 
17622   // Prefer uxth mask.
17623   if (IsLegalMask(0xFFFF))
17624     return UseMask(0xFFFF);
17625 
17626   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
17627   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17628   if (ShrunkMask < 256)
17629     return UseMask(ShrunkMask);
17630 
17631   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
17632   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17633   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
17634     return UseMask(ExpandedMask);
17635 
17636   // Potential improvements:
17637   //
17638   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
17639   // We could try to prefer Thumb1 immediates which can be lowered to a
17640   // two-instruction sequence.
17641   // We could try to recognize more legal ARM/Thumb2 immediates here.
17642 
17643   return false;
17644 }
17645 
17646 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
17647     SDValue Op, const APInt &OriginalDemandedBits,
17648     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
17649     unsigned Depth) const {
17650   unsigned Opc = Op.getOpcode();
17651 
17652   switch (Opc) {
17653   case ARMISD::ASRL:
17654   case ARMISD::LSRL: {
17655     // If this is result 0 and the other result is unused, see if the demand
17656     // bits allow us to shrink this long shift into a standard small shift in
17657     // the opposite direction.
17658     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
17659         isa<ConstantSDNode>(Op->getOperand(2))) {
17660       unsigned ShAmt = Op->getConstantOperandVal(2);
17661       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
17662                             APInt::getAllOnesValue(32) << (32 - ShAmt)))
17663         return TLO.CombineTo(
17664             Op, TLO.DAG.getNode(
17665                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
17666                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
17667     }
17668     break;
17669   }
17670   }
17671 
17672   return TargetLowering::SimplifyDemandedBitsForTargetNode(
17673       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
17674 }
17675 
17676 //===----------------------------------------------------------------------===//
17677 //                           ARM Inline Assembly Support
17678 //===----------------------------------------------------------------------===//
17679 
17680 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
17681   // Looking for "rev" which is V6+.
17682   if (!Subtarget->hasV6Ops())
17683     return false;
17684 
17685   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
17686   std::string AsmStr = IA->getAsmString();
17687   SmallVector<StringRef, 4> AsmPieces;
17688   SplitString(AsmStr, AsmPieces, ";\n");
17689 
17690   switch (AsmPieces.size()) {
17691   default: return false;
17692   case 1:
17693     AsmStr = std::string(AsmPieces[0]);
17694     AsmPieces.clear();
17695     SplitString(AsmStr, AsmPieces, " \t,");
17696 
17697     // rev $0, $1
17698     if (AsmPieces.size() == 3 &&
17699         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
17700         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
17701       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17702       if (Ty && Ty->getBitWidth() == 32)
17703         return IntrinsicLowering::LowerToByteSwap(CI);
17704     }
17705     break;
17706   }
17707 
17708   return false;
17709 }
17710 
17711 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
17712   // At this point, we have to lower this constraint to something else, so we
17713   // lower it to an "r" or "w". However, by doing this we will force the result
17714   // to be in register, while the X constraint is much more permissive.
17715   //
17716   // Although we are correct (we are free to emit anything, without
17717   // constraints), we might break use cases that would expect us to be more
17718   // efficient and emit something else.
17719   if (!Subtarget->hasVFP2Base())
17720     return "r";
17721   if (ConstraintVT.isFloatingPoint())
17722     return "w";
17723   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
17724      (ConstraintVT.getSizeInBits() == 64 ||
17725       ConstraintVT.getSizeInBits() == 128))
17726     return "w";
17727 
17728   return "r";
17729 }
17730 
17731 /// getConstraintType - Given a constraint letter, return the type of
17732 /// constraint it is for this target.
17733 ARMTargetLowering::ConstraintType
17734 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
17735   unsigned S = Constraint.size();
17736   if (S == 1) {
17737     switch (Constraint[0]) {
17738     default:  break;
17739     case 'l': return C_RegisterClass;
17740     case 'w': return C_RegisterClass;
17741     case 'h': return C_RegisterClass;
17742     case 'x': return C_RegisterClass;
17743     case 't': return C_RegisterClass;
17744     case 'j': return C_Immediate; // Constant for movw.
17745     // An address with a single base register. Due to the way we
17746     // currently handle addresses it is the same as an 'r' memory constraint.
17747     case 'Q': return C_Memory;
17748     }
17749   } else if (S == 2) {
17750     switch (Constraint[0]) {
17751     default: break;
17752     case 'T': return C_RegisterClass;
17753     // All 'U+' constraints are addresses.
17754     case 'U': return C_Memory;
17755     }
17756   }
17757   return TargetLowering::getConstraintType(Constraint);
17758 }
17759 
17760 /// Examine constraint type and operand type and determine a weight value.
17761 /// This object must already have been set up with the operand type
17762 /// and the current alternative constraint selected.
17763 TargetLowering::ConstraintWeight
17764 ARMTargetLowering::getSingleConstraintMatchWeight(
17765     AsmOperandInfo &info, const char *constraint) const {
17766   ConstraintWeight weight = CW_Invalid;
17767   Value *CallOperandVal = info.CallOperandVal;
17768     // If we don't have a value, we can't do a match,
17769     // but allow it at the lowest weight.
17770   if (!CallOperandVal)
17771     return CW_Default;
17772   Type *type = CallOperandVal->getType();
17773   // Look at the constraint type.
17774   switch (*constraint) {
17775   default:
17776     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17777     break;
17778   case 'l':
17779     if (type->isIntegerTy()) {
17780       if (Subtarget->isThumb())
17781         weight = CW_SpecificReg;
17782       else
17783         weight = CW_Register;
17784     }
17785     break;
17786   case 'w':
17787     if (type->isFloatingPointTy())
17788       weight = CW_Register;
17789     break;
17790   }
17791   return weight;
17792 }
17793 
17794 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
17795 
17796 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
17797     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
17798   switch (Constraint.size()) {
17799   case 1:
17800     // GCC ARM Constraint Letters
17801     switch (Constraint[0]) {
17802     case 'l': // Low regs or general regs.
17803       if (Subtarget->isThumb())
17804         return RCPair(0U, &ARM::tGPRRegClass);
17805       return RCPair(0U, &ARM::GPRRegClass);
17806     case 'h': // High regs or no regs.
17807       if (Subtarget->isThumb())
17808         return RCPair(0U, &ARM::hGPRRegClass);
17809       break;
17810     case 'r':
17811       if (Subtarget->isThumb1Only())
17812         return RCPair(0U, &ARM::tGPRRegClass);
17813       return RCPair(0U, &ARM::GPRRegClass);
17814     case 'w':
17815       if (VT == MVT::Other)
17816         break;
17817       if (VT == MVT::f32)
17818         return RCPair(0U, &ARM::SPRRegClass);
17819       if (VT.getSizeInBits() == 64)
17820         return RCPair(0U, &ARM::DPRRegClass);
17821       if (VT.getSizeInBits() == 128)
17822         return RCPair(0U, &ARM::QPRRegClass);
17823       break;
17824     case 'x':
17825       if (VT == MVT::Other)
17826         break;
17827       if (VT == MVT::f32)
17828         return RCPair(0U, &ARM::SPR_8RegClass);
17829       if (VT.getSizeInBits() == 64)
17830         return RCPair(0U, &ARM::DPR_8RegClass);
17831       if (VT.getSizeInBits() == 128)
17832         return RCPair(0U, &ARM::QPR_8RegClass);
17833       break;
17834     case 't':
17835       if (VT == MVT::Other)
17836         break;
17837       if (VT == MVT::f32 || VT == MVT::i32)
17838         return RCPair(0U, &ARM::SPRRegClass);
17839       if (VT.getSizeInBits() == 64)
17840         return RCPair(0U, &ARM::DPR_VFP2RegClass);
17841       if (VT.getSizeInBits() == 128)
17842         return RCPair(0U, &ARM::QPR_VFP2RegClass);
17843       break;
17844     }
17845     break;
17846 
17847   case 2:
17848     if (Constraint[0] == 'T') {
17849       switch (Constraint[1]) {
17850       default:
17851         break;
17852       case 'e':
17853         return RCPair(0U, &ARM::tGPREvenRegClass);
17854       case 'o':
17855         return RCPair(0U, &ARM::tGPROddRegClass);
17856       }
17857     }
17858     break;
17859 
17860   default:
17861     break;
17862   }
17863 
17864   if (StringRef("{cc}").equals_lower(Constraint))
17865     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
17866 
17867   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
17868 }
17869 
17870 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17871 /// vector.  If it is invalid, don't add anything to Ops.
17872 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17873                                                      std::string &Constraint,
17874                                                      std::vector<SDValue>&Ops,
17875                                                      SelectionDAG &DAG) const {
17876   SDValue Result;
17877 
17878   // Currently only support length 1 constraints.
17879   if (Constraint.length() != 1) return;
17880 
17881   char ConstraintLetter = Constraint[0];
17882   switch (ConstraintLetter) {
17883   default: break;
17884   case 'j':
17885   case 'I': case 'J': case 'K': case 'L':
17886   case 'M': case 'N': case 'O':
17887     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
17888     if (!C)
17889       return;
17890 
17891     int64_t CVal64 = C->getSExtValue();
17892     int CVal = (int) CVal64;
17893     // None of these constraints allow values larger than 32 bits.  Check
17894     // that the value fits in an int.
17895     if (CVal != CVal64)
17896       return;
17897 
17898     switch (ConstraintLetter) {
17899       case 'j':
17900         // Constant suitable for movw, must be between 0 and
17901         // 65535.
17902         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
17903           if (CVal >= 0 && CVal <= 65535)
17904             break;
17905         return;
17906       case 'I':
17907         if (Subtarget->isThumb1Only()) {
17908           // This must be a constant between 0 and 255, for ADD
17909           // immediates.
17910           if (CVal >= 0 && CVal <= 255)
17911             break;
17912         } else if (Subtarget->isThumb2()) {
17913           // A constant that can be used as an immediate value in a
17914           // data-processing instruction.
17915           if (ARM_AM::getT2SOImmVal(CVal) != -1)
17916             break;
17917         } else {
17918           // A constant that can be used as an immediate value in a
17919           // data-processing instruction.
17920           if (ARM_AM::getSOImmVal(CVal) != -1)
17921             break;
17922         }
17923         return;
17924 
17925       case 'J':
17926         if (Subtarget->isThumb1Only()) {
17927           // This must be a constant between -255 and -1, for negated ADD
17928           // immediates. This can be used in GCC with an "n" modifier that
17929           // prints the negated value, for use with SUB instructions. It is
17930           // not useful otherwise but is implemented for compatibility.
17931           if (CVal >= -255 && CVal <= -1)
17932             break;
17933         } else {
17934           // This must be a constant between -4095 and 4095. It is not clear
17935           // what this constraint is intended for. Implemented for
17936           // compatibility with GCC.
17937           if (CVal >= -4095 && CVal <= 4095)
17938             break;
17939         }
17940         return;
17941 
17942       case 'K':
17943         if (Subtarget->isThumb1Only()) {
17944           // A 32-bit value where only one byte has a nonzero value. Exclude
17945           // zero to match GCC. This constraint is used by GCC internally for
17946           // constants that can be loaded with a move/shift combination.
17947           // It is not useful otherwise but is implemented for compatibility.
17948           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
17949             break;
17950         } else if (Subtarget->isThumb2()) {
17951           // A constant whose bitwise inverse can be used as an immediate
17952           // value in a data-processing instruction. This can be used in GCC
17953           // with a "B" modifier that prints the inverted value, for use with
17954           // BIC and MVN instructions. It is not useful otherwise but is
17955           // implemented for compatibility.
17956           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
17957             break;
17958         } else {
17959           // A constant whose bitwise inverse can be used as an immediate
17960           // value in a data-processing instruction. This can be used in GCC
17961           // with a "B" modifier that prints the inverted value, for use with
17962           // BIC and MVN instructions. It is not useful otherwise but is
17963           // implemented for compatibility.
17964           if (ARM_AM::getSOImmVal(~CVal) != -1)
17965             break;
17966         }
17967         return;
17968 
17969       case 'L':
17970         if (Subtarget->isThumb1Only()) {
17971           // This must be a constant between -7 and 7,
17972           // for 3-operand ADD/SUB immediate instructions.
17973           if (CVal >= -7 && CVal < 7)
17974             break;
17975         } else if (Subtarget->isThumb2()) {
17976           // A constant whose negation can be used as an immediate value in a
17977           // data-processing instruction. This can be used in GCC with an "n"
17978           // modifier that prints the negated value, for use with SUB
17979           // instructions. It is not useful otherwise but is implemented for
17980           // compatibility.
17981           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
17982             break;
17983         } else {
17984           // A constant whose negation can be used as an immediate value in a
17985           // data-processing instruction. This can be used in GCC with an "n"
17986           // modifier that prints the negated value, for use with SUB
17987           // instructions. It is not useful otherwise but is implemented for
17988           // compatibility.
17989           if (ARM_AM::getSOImmVal(-CVal) != -1)
17990             break;
17991         }
17992         return;
17993 
17994       case 'M':
17995         if (Subtarget->isThumb1Only()) {
17996           // This must be a multiple of 4 between 0 and 1020, for
17997           // ADD sp + immediate.
17998           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
17999             break;
18000         } else {
18001           // A power of two or a constant between 0 and 32.  This is used in
18002           // GCC for the shift amount on shifted register operands, but it is
18003           // useful in general for any shift amounts.
18004           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
18005             break;
18006         }
18007         return;
18008 
18009       case 'N':
18010         if (Subtarget->isThumb1Only()) {
18011           // This must be a constant between 0 and 31, for shift amounts.
18012           if (CVal >= 0 && CVal <= 31)
18013             break;
18014         }
18015         return;
18016 
18017       case 'O':
18018         if (Subtarget->isThumb1Only()) {
18019           // This must be a multiple of 4 between -508 and 508, for
18020           // ADD/SUB sp = sp + immediate.
18021           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
18022             break;
18023         }
18024         return;
18025     }
18026     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
18027     break;
18028   }
18029 
18030   if (Result.getNode()) {
18031     Ops.push_back(Result);
18032     return;
18033   }
18034   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18035 }
18036 
18037 static RTLIB::Libcall getDivRemLibcall(
18038     const SDNode *N, MVT::SimpleValueType SVT) {
18039   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
18040           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
18041          "Unhandled Opcode in getDivRemLibcall");
18042   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
18043                   N->getOpcode() == ISD::SREM;
18044   RTLIB::Libcall LC;
18045   switch (SVT) {
18046   default: llvm_unreachable("Unexpected request for libcall!");
18047   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
18048   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
18049   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
18050   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
18051   }
18052   return LC;
18053 }
18054 
18055 static TargetLowering::ArgListTy getDivRemArgList(
18056     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
18057   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
18058           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
18059          "Unhandled Opcode in getDivRemArgList");
18060   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
18061                   N->getOpcode() == ISD::SREM;
18062   TargetLowering::ArgListTy Args;
18063   TargetLowering::ArgListEntry Entry;
18064   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
18065     EVT ArgVT = N->getOperand(i).getValueType();
18066     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
18067     Entry.Node = N->getOperand(i);
18068     Entry.Ty = ArgTy;
18069     Entry.IsSExt = isSigned;
18070     Entry.IsZExt = !isSigned;
18071     Args.push_back(Entry);
18072   }
18073   if (Subtarget->isTargetWindows() && Args.size() >= 2)
18074     std::swap(Args[0], Args[1]);
18075   return Args;
18076 }
18077 
18078 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
18079   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
18080           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
18081           Subtarget->isTargetWindows()) &&
18082          "Register-based DivRem lowering only");
18083   unsigned Opcode = Op->getOpcode();
18084   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
18085          "Invalid opcode for Div/Rem lowering");
18086   bool isSigned = (Opcode == ISD::SDIVREM);
18087   EVT VT = Op->getValueType(0);
18088   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
18089   SDLoc dl(Op);
18090 
18091   // If the target has hardware divide, use divide + multiply + subtract:
18092   //     div = a / b
18093   //     rem = a - b * div
18094   //     return {div, rem}
18095   // This should be lowered into UDIV/SDIV + MLS later on.
18096   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
18097                                         : Subtarget->hasDivideInARMMode();
18098   if (hasDivide && Op->getValueType(0).isSimple() &&
18099       Op->getSimpleValueType(0) == MVT::i32) {
18100     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
18101     const SDValue Dividend = Op->getOperand(0);
18102     const SDValue Divisor = Op->getOperand(1);
18103     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
18104     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
18105     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
18106 
18107     SDValue Values[2] = {Div, Rem};
18108     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
18109   }
18110 
18111   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
18112                                        VT.getSimpleVT().SimpleTy);
18113   SDValue InChain = DAG.getEntryNode();
18114 
18115   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
18116                                                     DAG.getContext(),
18117                                                     Subtarget);
18118 
18119   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18120                                          getPointerTy(DAG.getDataLayout()));
18121 
18122   Type *RetTy = StructType::get(Ty, Ty);
18123 
18124   if (Subtarget->isTargetWindows())
18125     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
18126 
18127   TargetLowering::CallLoweringInfo CLI(DAG);
18128   CLI.setDebugLoc(dl).setChain(InChain)
18129     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
18130     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18131 
18132   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18133   return CallInfo.first;
18134 }
18135 
18136 // Lowers REM using divmod helpers
18137 // see RTABI section 4.2/4.3
18138 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
18139   // Build return types (div and rem)
18140   std::vector<Type*> RetTyParams;
18141   Type *RetTyElement;
18142 
18143   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
18144   default: llvm_unreachable("Unexpected request for libcall!");
18145   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
18146   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
18147   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
18148   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
18149   }
18150 
18151   RetTyParams.push_back(RetTyElement);
18152   RetTyParams.push_back(RetTyElement);
18153   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
18154   Type *RetTy = StructType::get(*DAG.getContext(), ret);
18155 
18156   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
18157                                                              SimpleTy);
18158   SDValue InChain = DAG.getEntryNode();
18159   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
18160                                                     Subtarget);
18161   bool isSigned = N->getOpcode() == ISD::SREM;
18162   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18163                                          getPointerTy(DAG.getDataLayout()));
18164 
18165   if (Subtarget->isTargetWindows())
18166     InChain = WinDBZCheckDenominator(DAG, N, InChain);
18167 
18168   // Lower call
18169   CallLoweringInfo CLI(DAG);
18170   CLI.setChain(InChain)
18171      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
18172      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
18173   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
18174 
18175   // Return second (rem) result operand (first contains div)
18176   SDNode *ResNode = CallResult.first.getNode();
18177   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
18178   return ResNode->getOperand(1);
18179 }
18180 
18181 SDValue
18182 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
18183   assert(Subtarget->isTargetWindows() && "unsupported target platform");
18184   SDLoc DL(Op);
18185 
18186   // Get the inputs.
18187   SDValue Chain = Op.getOperand(0);
18188   SDValue Size  = Op.getOperand(1);
18189 
18190   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
18191           "no-stack-arg-probe")) {
18192     MaybeAlign Align =
18193         cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
18194     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
18195     Chain = SP.getValue(1);
18196     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
18197     if (Align)
18198       SP =
18199           DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
18200                       DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
18201     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
18202     SDValue Ops[2] = { SP, Chain };
18203     return DAG.getMergeValues(Ops, DL);
18204   }
18205 
18206   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
18207                               DAG.getConstant(2, DL, MVT::i32));
18208 
18209   SDValue Flag;
18210   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
18211   Flag = Chain.getValue(1);
18212 
18213   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18214   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
18215 
18216   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
18217   Chain = NewSP.getValue(1);
18218 
18219   SDValue Ops[2] = { NewSP, Chain };
18220   return DAG.getMergeValues(Ops, DL);
18221 }
18222 
18223 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
18224   bool IsStrict = Op->isStrictFPOpcode();
18225   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
18226   const unsigned DstSz = Op.getValueType().getSizeInBits();
18227   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
18228   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
18229          "Unexpected type for custom-lowering FP_EXTEND");
18230 
18231   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18232          "With both FP DP and 16, any FP conversion is legal!");
18233 
18234   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
18235          "With FP16, 16 to 32 conversion is legal!");
18236 
18237   // Converting from 32 -> 64 is valid if we have FP64.
18238   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
18239     // FIXME: Remove this when we have strict fp instruction selection patterns
18240     if (IsStrict) {
18241       SDLoc Loc(Op);
18242       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
18243                                    Loc, Op.getValueType(), SrcVal);
18244       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
18245     }
18246     return Op;
18247   }
18248 
18249   // Either we are converting from 16 -> 64, without FP16 and/or
18250   // FP.double-precision or without Armv8-fp. So we must do it in two
18251   // steps.
18252   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
18253   // without FP16. So we must do a function call.
18254   SDLoc Loc(Op);
18255   RTLIB::Libcall LC;
18256   MakeLibCallOptions CallOptions;
18257   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18258   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
18259     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
18260     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
18261     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
18262     if (Supported) {
18263       if (IsStrict) {
18264         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
18265                              {DstVT, MVT::Other}, {Chain, SrcVal});
18266         Chain = SrcVal.getValue(1);
18267       } else {
18268         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
18269       }
18270     } else {
18271       LC = RTLIB::getFPEXT(SrcVT, DstVT);
18272       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18273              "Unexpected type for custom-lowering FP_EXTEND");
18274       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18275                                             Loc, Chain);
18276     }
18277   }
18278 
18279   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
18280 }
18281 
18282 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
18283   bool IsStrict = Op->isStrictFPOpcode();
18284 
18285   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
18286   EVT SrcVT = SrcVal.getValueType();
18287   EVT DstVT = Op.getValueType();
18288   const unsigned DstSz = Op.getValueType().getSizeInBits();
18289   const unsigned SrcSz = SrcVT.getSizeInBits();
18290   (void)DstSz;
18291   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
18292          "Unexpected type for custom-lowering FP_ROUND");
18293 
18294   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18295          "With both FP DP and 16, any FP conversion is legal!");
18296 
18297   SDLoc Loc(Op);
18298 
18299   // Instruction from 32 -> 16 if hasFP16 is valid
18300   if (SrcSz == 32 && Subtarget->hasFP16())
18301     return Op;
18302 
18303   // Lib call from 32 -> 16 / 64 -> [32, 16]
18304   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
18305   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18306          "Unexpected type for custom-lowering FP_ROUND");
18307   MakeLibCallOptions CallOptions;
18308   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18309   SDValue Result;
18310   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18311                                         Loc, Chain);
18312   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
18313 }
18314 
18315 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
18316                                  SelectionDAG &DAG) const {
18317   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
18318   MVT HalfT = MVT::i32;
18319   SDLoc dl(N);
18320   SDValue Hi, Lo, Tmp;
18321 
18322   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
18323       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
18324     return ;
18325 
18326   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
18327   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
18328 
18329   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18330                    DAG.getConstant(0, dl, HalfT));
18331   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18332                    DAG.getConstant(1, dl, HalfT));
18333 
18334   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
18335                     DAG.getConstant(OpTypeBits - 1, dl,
18336                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
18337   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
18338   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
18339                    SDValue(Lo.getNode(), 1));
18340   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
18341   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
18342 
18343   Results.push_back(Lo);
18344   Results.push_back(Hi);
18345 }
18346 
18347 bool
18348 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
18349   // The ARM target isn't yet aware of offsets.
18350   return false;
18351 }
18352 
18353 bool ARM::isBitFieldInvertedMask(unsigned v) {
18354   if (v == 0xffffffff)
18355     return false;
18356 
18357   // there can be 1's on either or both "outsides", all the "inside"
18358   // bits must be 0's
18359   return isShiftedMask_32(~v);
18360 }
18361 
18362 /// isFPImmLegal - Returns true if the target can instruction select the
18363 /// specified FP immediate natively. If false, the legalizer will
18364 /// materialize the FP immediate as a load from a constant pool.
18365 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
18366                                      bool ForCodeSize) const {
18367   if (!Subtarget->hasVFP3Base())
18368     return false;
18369   if (VT == MVT::f16 && Subtarget->hasFullFP16())
18370     return ARM_AM::getFP16Imm(Imm) != -1;
18371   if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
18372       ARM_AM::getFP32FP16Imm(Imm) != -1)
18373     return true;
18374   if (VT == MVT::f32)
18375     return ARM_AM::getFP32Imm(Imm) != -1;
18376   if (VT == MVT::f64 && Subtarget->hasFP64())
18377     return ARM_AM::getFP64Imm(Imm) != -1;
18378   return false;
18379 }
18380 
18381 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
18382 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
18383 /// specified in the intrinsic calls.
18384 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
18385                                            const CallInst &I,
18386                                            MachineFunction &MF,
18387                                            unsigned Intrinsic) const {
18388   switch (Intrinsic) {
18389   case Intrinsic::arm_neon_vld1:
18390   case Intrinsic::arm_neon_vld2:
18391   case Intrinsic::arm_neon_vld3:
18392   case Intrinsic::arm_neon_vld4:
18393   case Intrinsic::arm_neon_vld2lane:
18394   case Intrinsic::arm_neon_vld3lane:
18395   case Intrinsic::arm_neon_vld4lane:
18396   case Intrinsic::arm_neon_vld2dup:
18397   case Intrinsic::arm_neon_vld3dup:
18398   case Intrinsic::arm_neon_vld4dup: {
18399     Info.opc = ISD::INTRINSIC_W_CHAIN;
18400     // Conservatively set memVT to the entire set of vectors loaded.
18401     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18402     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18403     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18404     Info.ptrVal = I.getArgOperand(0);
18405     Info.offset = 0;
18406     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18407     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18408     // volatile loads with NEON intrinsics not supported
18409     Info.flags = MachineMemOperand::MOLoad;
18410     return true;
18411   }
18412   case Intrinsic::arm_neon_vld1x2:
18413   case Intrinsic::arm_neon_vld1x3:
18414   case Intrinsic::arm_neon_vld1x4: {
18415     Info.opc = ISD::INTRINSIC_W_CHAIN;
18416     // Conservatively set memVT to the entire set of vectors loaded.
18417     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18418     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18419     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18420     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
18421     Info.offset = 0;
18422     Info.align.reset();
18423     // volatile loads with NEON intrinsics not supported
18424     Info.flags = MachineMemOperand::MOLoad;
18425     return true;
18426   }
18427   case Intrinsic::arm_neon_vst1:
18428   case Intrinsic::arm_neon_vst2:
18429   case Intrinsic::arm_neon_vst3:
18430   case Intrinsic::arm_neon_vst4:
18431   case Intrinsic::arm_neon_vst2lane:
18432   case Intrinsic::arm_neon_vst3lane:
18433   case Intrinsic::arm_neon_vst4lane: {
18434     Info.opc = ISD::INTRINSIC_VOID;
18435     // Conservatively set memVT to the entire set of vectors stored.
18436     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18437     unsigned NumElts = 0;
18438     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18439       Type *ArgTy = I.getArgOperand(ArgI)->getType();
18440       if (!ArgTy->isVectorTy())
18441         break;
18442       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18443     }
18444     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18445     Info.ptrVal = I.getArgOperand(0);
18446     Info.offset = 0;
18447     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18448     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18449     // volatile stores with NEON intrinsics not supported
18450     Info.flags = MachineMemOperand::MOStore;
18451     return true;
18452   }
18453   case Intrinsic::arm_neon_vst1x2:
18454   case Intrinsic::arm_neon_vst1x3:
18455   case Intrinsic::arm_neon_vst1x4: {
18456     Info.opc = ISD::INTRINSIC_VOID;
18457     // Conservatively set memVT to the entire set of vectors stored.
18458     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18459     unsigned NumElts = 0;
18460     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18461       Type *ArgTy = I.getArgOperand(ArgI)->getType();
18462       if (!ArgTy->isVectorTy())
18463         break;
18464       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18465     }
18466     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18467     Info.ptrVal = I.getArgOperand(0);
18468     Info.offset = 0;
18469     Info.align.reset();
18470     // volatile stores with NEON intrinsics not supported
18471     Info.flags = MachineMemOperand::MOStore;
18472     return true;
18473   }
18474   case Intrinsic::arm_mve_vld2q:
18475   case Intrinsic::arm_mve_vld4q: {
18476     Info.opc = ISD::INTRINSIC_W_CHAIN;
18477     // Conservatively set memVT to the entire set of vectors loaded.
18478     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
18479     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
18480     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18481     Info.ptrVal = I.getArgOperand(0);
18482     Info.offset = 0;
18483     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18484     // volatile loads with MVE intrinsics not supported
18485     Info.flags = MachineMemOperand::MOLoad;
18486     return true;
18487   }
18488   case Intrinsic::arm_mve_vst2q:
18489   case Intrinsic::arm_mve_vst4q: {
18490     Info.opc = ISD::INTRINSIC_VOID;
18491     // Conservatively set memVT to the entire set of vectors stored.
18492     Type *VecTy = I.getArgOperand(1)->getType();
18493     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
18494     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18495     Info.ptrVal = I.getArgOperand(0);
18496     Info.offset = 0;
18497     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18498     // volatile stores with MVE intrinsics not supported
18499     Info.flags = MachineMemOperand::MOStore;
18500     return true;
18501   }
18502   case Intrinsic::arm_ldaex:
18503   case Intrinsic::arm_ldrex: {
18504     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18505     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
18506     Info.opc = ISD::INTRINSIC_W_CHAIN;
18507     Info.memVT = MVT::getVT(PtrTy->getElementType());
18508     Info.ptrVal = I.getArgOperand(0);
18509     Info.offset = 0;
18510     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18511     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18512     return true;
18513   }
18514   case Intrinsic::arm_stlex:
18515   case Intrinsic::arm_strex: {
18516     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18517     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
18518     Info.opc = ISD::INTRINSIC_W_CHAIN;
18519     Info.memVT = MVT::getVT(PtrTy->getElementType());
18520     Info.ptrVal = I.getArgOperand(1);
18521     Info.offset = 0;
18522     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18523     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18524     return true;
18525   }
18526   case Intrinsic::arm_stlexd:
18527   case Intrinsic::arm_strexd:
18528     Info.opc = ISD::INTRINSIC_W_CHAIN;
18529     Info.memVT = MVT::i64;
18530     Info.ptrVal = I.getArgOperand(2);
18531     Info.offset = 0;
18532     Info.align = Align(8);
18533     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18534     return true;
18535 
18536   case Intrinsic::arm_ldaexd:
18537   case Intrinsic::arm_ldrexd:
18538     Info.opc = ISD::INTRINSIC_W_CHAIN;
18539     Info.memVT = MVT::i64;
18540     Info.ptrVal = I.getArgOperand(0);
18541     Info.offset = 0;
18542     Info.align = Align(8);
18543     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18544     return true;
18545 
18546   default:
18547     break;
18548   }
18549 
18550   return false;
18551 }
18552 
18553 /// Returns true if it is beneficial to convert a load of a constant
18554 /// to just the constant itself.
18555 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
18556                                                           Type *Ty) const {
18557   assert(Ty->isIntegerTy());
18558 
18559   unsigned Bits = Ty->getPrimitiveSizeInBits();
18560   if (Bits == 0 || Bits > 32)
18561     return false;
18562   return true;
18563 }
18564 
18565 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
18566                                                 unsigned Index) const {
18567   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
18568     return false;
18569 
18570   return (Index == 0 || Index == ResVT.getVectorNumElements());
18571 }
18572 
18573 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
18574                                         ARM_MB::MemBOpt Domain) const {
18575   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18576 
18577   // First, if the target has no DMB, see what fallback we can use.
18578   if (!Subtarget->hasDataBarrier()) {
18579     // Some ARMv6 cpus can support data barriers with an mcr instruction.
18580     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
18581     // here.
18582     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
18583       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
18584       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
18585                         Builder.getInt32(0), Builder.getInt32(7),
18586                         Builder.getInt32(10), Builder.getInt32(5)};
18587       return Builder.CreateCall(MCR, args);
18588     } else {
18589       // Instead of using barriers, atomic accesses on these subtargets use
18590       // libcalls.
18591       llvm_unreachable("makeDMB on a target so old that it has no barriers");
18592     }
18593   } else {
18594     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
18595     // Only a full system barrier exists in the M-class architectures.
18596     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
18597     Constant *CDomain = Builder.getInt32(Domain);
18598     return Builder.CreateCall(DMB, CDomain);
18599   }
18600 }
18601 
18602 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
18603 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
18604                                                  Instruction *Inst,
18605                                                  AtomicOrdering Ord) const {
18606   switch (Ord) {
18607   case AtomicOrdering::NotAtomic:
18608   case AtomicOrdering::Unordered:
18609     llvm_unreachable("Invalid fence: unordered/non-atomic");
18610   case AtomicOrdering::Monotonic:
18611   case AtomicOrdering::Acquire:
18612     return nullptr; // Nothing to do
18613   case AtomicOrdering::SequentiallyConsistent:
18614     if (!Inst->hasAtomicStore())
18615       return nullptr; // Nothing to do
18616     LLVM_FALLTHROUGH;
18617   case AtomicOrdering::Release:
18618   case AtomicOrdering::AcquireRelease:
18619     if (Subtarget->preferISHSTBarriers())
18620       return makeDMB(Builder, ARM_MB::ISHST);
18621     // FIXME: add a comment with a link to documentation justifying this.
18622     else
18623       return makeDMB(Builder, ARM_MB::ISH);
18624   }
18625   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
18626 }
18627 
18628 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
18629                                                   Instruction *Inst,
18630                                                   AtomicOrdering Ord) const {
18631   switch (Ord) {
18632   case AtomicOrdering::NotAtomic:
18633   case AtomicOrdering::Unordered:
18634     llvm_unreachable("Invalid fence: unordered/not-atomic");
18635   case AtomicOrdering::Monotonic:
18636   case AtomicOrdering::Release:
18637     return nullptr; // Nothing to do
18638   case AtomicOrdering::Acquire:
18639   case AtomicOrdering::AcquireRelease:
18640   case AtomicOrdering::SequentiallyConsistent:
18641     return makeDMB(Builder, ARM_MB::ISH);
18642   }
18643   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
18644 }
18645 
18646 // Loads and stores less than 64-bits are already atomic; ones above that
18647 // are doomed anyway, so defer to the default libcall and blame the OS when
18648 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18649 // anything for those.
18650 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18651   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
18652   return (Size == 64) && !Subtarget->isMClass();
18653 }
18654 
18655 // Loads and stores less than 64-bits are already atomic; ones above that
18656 // are doomed anyway, so defer to the default libcall and blame the OS when
18657 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18658 // anything for those.
18659 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
18660 // guarantee, see DDI0406C ARM architecture reference manual,
18661 // sections A8.8.72-74 LDRD)
18662 TargetLowering::AtomicExpansionKind
18663 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18664   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
18665   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
18666                                                   : AtomicExpansionKind::None;
18667 }
18668 
18669 // For the real atomic operations, we have ldrex/strex up to 32 bits,
18670 // and up to 64 bits on the non-M profiles
18671 TargetLowering::AtomicExpansionKind
18672 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18673   if (AI->isFloatingPointOperation())
18674     return AtomicExpansionKind::CmpXChg;
18675 
18676   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18677   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18678   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
18679              ? AtomicExpansionKind::LLSC
18680              : AtomicExpansionKind::None;
18681 }
18682 
18683 TargetLowering::AtomicExpansionKind
18684 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18685   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18686   // implement cmpxchg without spilling. If the address being exchanged is also
18687   // on the stack and close enough to the spill slot, this can lead to a
18688   // situation where the monitor always gets cleared and the atomic operation
18689   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
18690   bool HasAtomicCmpXchg =
18691       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18692   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
18693     return AtomicExpansionKind::LLSC;
18694   return AtomicExpansionKind::None;
18695 }
18696 
18697 bool ARMTargetLowering::shouldInsertFencesForAtomic(
18698     const Instruction *I) const {
18699   return InsertFencesForAtomic;
18700 }
18701 
18702 // This has so far only been implemented for MachO.
18703 bool ARMTargetLowering::useLoadStackGuardNode() const {
18704   return Subtarget->isTargetMachO();
18705 }
18706 
18707 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
18708   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18709     return TargetLowering::insertSSPDeclarations(M);
18710 
18711   // MSVC CRT has a global variable holding security cookie.
18712   M.getOrInsertGlobal("__security_cookie",
18713                       Type::getInt8PtrTy(M.getContext()));
18714 
18715   // MSVC CRT has a function to validate security cookie.
18716   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
18717       "__security_check_cookie", Type::getVoidTy(M.getContext()),
18718       Type::getInt8PtrTy(M.getContext()));
18719   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
18720     F->addAttribute(1, Attribute::AttrKind::InReg);
18721 }
18722 
18723 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
18724   // MSVC CRT has a global variable holding security cookie.
18725   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18726     return M.getGlobalVariable("__security_cookie");
18727   return TargetLowering::getSDagStackGuard(M);
18728 }
18729 
18730 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
18731   // MSVC CRT has a function to validate security cookie.
18732   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18733     return M.getFunction("__security_check_cookie");
18734   return TargetLowering::getSSPStackGuardCheck(M);
18735 }
18736 
18737 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
18738                                                   unsigned &Cost) const {
18739   // If we do not have NEON, vector types are not natively supported.
18740   if (!Subtarget->hasNEON())
18741     return false;
18742 
18743   // Floating point values and vector values map to the same register file.
18744   // Therefore, although we could do a store extract of a vector type, this is
18745   // better to leave at float as we have more freedom in the addressing mode for
18746   // those.
18747   if (VectorTy->isFPOrFPVectorTy())
18748     return false;
18749 
18750   // If the index is unknown at compile time, this is very expensive to lower
18751   // and it is not possible to combine the store with the extract.
18752   if (!isa<ConstantInt>(Idx))
18753     return false;
18754 
18755   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
18756   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
18757   // We can do a store + vector extract on any vector that fits perfectly in a D
18758   // or Q register.
18759   if (BitWidth == 64 || BitWidth == 128) {
18760     Cost = 0;
18761     return true;
18762   }
18763   return false;
18764 }
18765 
18766 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
18767   return Subtarget->hasV6T2Ops();
18768 }
18769 
18770 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
18771   return Subtarget->hasV6T2Ops();
18772 }
18773 
18774 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
18775   return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
18776 }
18777 
18778 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
18779                                          AtomicOrdering Ord) const {
18780   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18781   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
18782   bool IsAcquire = isAcquireOrStronger(Ord);
18783 
18784   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
18785   // intrinsic must return {i32, i32} and we have to recombine them into a
18786   // single i64 here.
18787   if (ValTy->getPrimitiveSizeInBits() == 64) {
18788     Intrinsic::ID Int =
18789         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
18790     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
18791 
18792     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18793     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
18794 
18795     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18796     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18797     if (!Subtarget->isLittle())
18798       std::swap (Lo, Hi);
18799     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18800     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18801     return Builder.CreateOr(
18802         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
18803   }
18804 
18805   Type *Tys[] = { Addr->getType() };
18806   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
18807   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
18808 
18809   return Builder.CreateTruncOrBitCast(
18810       Builder.CreateCall(Ldrex, Addr),
18811       cast<PointerType>(Addr->getType())->getElementType());
18812 }
18813 
18814 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
18815     IRBuilder<> &Builder) const {
18816   if (!Subtarget->hasV7Ops())
18817     return;
18818   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18819   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
18820 }
18821 
18822 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
18823                                                Value *Addr,
18824                                                AtomicOrdering Ord) const {
18825   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18826   bool IsRelease = isReleaseOrStronger(Ord);
18827 
18828   // Since the intrinsics must have legal type, the i64 intrinsics take two
18829   // parameters: "i32, i32". We must marshal Val into the appropriate form
18830   // before the call.
18831   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
18832     Intrinsic::ID Int =
18833         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
18834     Function *Strex = Intrinsic::getDeclaration(M, Int);
18835     Type *Int32Ty = Type::getInt32Ty(M->getContext());
18836 
18837     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
18838     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
18839     if (!Subtarget->isLittle())
18840       std::swap(Lo, Hi);
18841     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18842     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
18843   }
18844 
18845   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
18846   Type *Tys[] = { Addr->getType() };
18847   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
18848 
18849   return Builder.CreateCall(
18850       Strex, {Builder.CreateZExtOrBitCast(
18851                   Val, Strex->getFunctionType()->getParamType(0)),
18852               Addr});
18853 }
18854 
18855 
18856 bool ARMTargetLowering::alignLoopsWithOptSize() const {
18857   return Subtarget->isMClass();
18858 }
18859 
18860 /// A helper function for determining the number of interleaved accesses we
18861 /// will generate when lowering accesses of the given type.
18862 unsigned
18863 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
18864                                              const DataLayout &DL) const {
18865   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
18866 }
18867 
18868 bool ARMTargetLowering::isLegalInterleavedAccessType(
18869     unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const {
18870 
18871   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
18872   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
18873 
18874   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
18875     return false;
18876 
18877   // Ensure the vector doesn't have f16 elements. Even though we could do an
18878   // i16 vldN, we can't hold the f16 vectors and will end up converting via
18879   // f32.
18880   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
18881     return false;
18882   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
18883     return false;
18884 
18885   // Ensure the number of vector elements is greater than 1.
18886   if (VecTy->getNumElements() < 2)
18887     return false;
18888 
18889   // Ensure the element type is legal.
18890   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
18891     return false;
18892 
18893   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
18894   // 128 will be split into multiple interleaved accesses.
18895   if (Subtarget->hasNEON() && VecSize == 64)
18896     return true;
18897   return VecSize % 128 == 0;
18898 }
18899 
18900 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
18901   if (Subtarget->hasNEON())
18902     return 4;
18903   if (Subtarget->hasMVEIntegerOps())
18904     return MVEMaxSupportedInterleaveFactor;
18905   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
18906 }
18907 
18908 /// Lower an interleaved load into a vldN intrinsic.
18909 ///
18910 /// E.g. Lower an interleaved load (Factor = 2):
18911 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
18912 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
18913 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
18914 ///
18915 ///      Into:
18916 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
18917 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
18918 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
18919 bool ARMTargetLowering::lowerInterleavedLoad(
18920     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
18921     ArrayRef<unsigned> Indices, unsigned Factor) const {
18922   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18923          "Invalid interleave factor");
18924   assert(!Shuffles.empty() && "Empty shufflevector input");
18925   assert(Shuffles.size() == Indices.size() &&
18926          "Unmatched number of shufflevectors and indices");
18927 
18928   auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
18929   Type *EltTy = VecTy->getElementType();
18930 
18931   const DataLayout &DL = LI->getModule()->getDataLayout();
18932 
18933   // Skip if we do not have NEON and skip illegal vector types. We can
18934   // "legalize" wide vector types into multiple interleaved accesses as long as
18935   // the vector types are divisible by 128.
18936   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
18937     return false;
18938 
18939   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
18940 
18941   // A pointer vector can not be the return type of the ldN intrinsics. Need to
18942   // load integer vectors first and then convert to pointer vectors.
18943   if (EltTy->isPointerTy())
18944     VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
18945 
18946   IRBuilder<> Builder(LI);
18947 
18948   // The base address of the load.
18949   Value *BaseAddr = LI->getPointerOperand();
18950 
18951   if (NumLoads > 1) {
18952     // If we're going to generate more than one load, reset the sub-vector type
18953     // to something legal.
18954     VecTy = FixedVectorType::get(VecTy->getElementType(),
18955                                  VecTy->getNumElements() / NumLoads);
18956 
18957     // We will compute the pointer operand of each load from the original base
18958     // address using GEPs. Cast the base address to a pointer to the scalar
18959     // element type.
18960     BaseAddr = Builder.CreateBitCast(
18961         BaseAddr,
18962         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
18963   }
18964 
18965   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
18966 
18967   auto createLoadIntrinsic = [&](Value *BaseAddr) {
18968     if (Subtarget->hasNEON()) {
18969       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
18970       Type *Tys[] = {VecTy, Int8Ptr};
18971       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
18972                                                 Intrinsic::arm_neon_vld3,
18973                                                 Intrinsic::arm_neon_vld4};
18974       Function *VldnFunc =
18975           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
18976 
18977       SmallVector<Value *, 2> Ops;
18978       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18979       Ops.push_back(Builder.getInt32(LI->getAlignment()));
18980 
18981       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18982     } else {
18983       assert((Factor == 2 || Factor == 4) &&
18984              "expected interleave factor of 2 or 4 for MVE");
18985       Intrinsic::ID LoadInts =
18986           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
18987       Type *VecEltTy =
18988           VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
18989       Type *Tys[] = {VecTy, VecEltTy};
18990       Function *VldnFunc =
18991           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
18992 
18993       SmallVector<Value *, 2> Ops;
18994       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
18995       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18996     }
18997   };
18998 
18999   // Holds sub-vectors extracted from the load intrinsic return values. The
19000   // sub-vectors are associated with the shufflevector instructions they will
19001   // replace.
19002   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
19003 
19004   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
19005     // If we're generating more than one load, compute the base address of
19006     // subsequent loads as an offset from the previous.
19007     if (LoadCount > 0)
19008       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
19009                                             VecTy->getNumElements() * Factor);
19010 
19011     CallInst *VldN = createLoadIntrinsic(BaseAddr);
19012 
19013     // Replace uses of each shufflevector with the corresponding vector loaded
19014     // by ldN.
19015     for (unsigned i = 0; i < Shuffles.size(); i++) {
19016       ShuffleVectorInst *SV = Shuffles[i];
19017       unsigned Index = Indices[i];
19018 
19019       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
19020 
19021       // Convert the integer vector to pointer vector if the element is pointer.
19022       if (EltTy->isPointerTy())
19023         SubVec = Builder.CreateIntToPtr(
19024             SubVec,
19025             FixedVectorType::get(SV->getType()->getElementType(), VecTy));
19026 
19027       SubVecs[SV].push_back(SubVec);
19028     }
19029   }
19030 
19031   // Replace uses of the shufflevector instructions with the sub-vectors
19032   // returned by the load intrinsic. If a shufflevector instruction is
19033   // associated with more than one sub-vector, those sub-vectors will be
19034   // concatenated into a single wide vector.
19035   for (ShuffleVectorInst *SVI : Shuffles) {
19036     auto &SubVec = SubVecs[SVI];
19037     auto *WideVec =
19038         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
19039     SVI->replaceAllUsesWith(WideVec);
19040   }
19041 
19042   return true;
19043 }
19044 
19045 /// Lower an interleaved store into a vstN intrinsic.
19046 ///
19047 /// E.g. Lower an interleaved store (Factor = 3):
19048 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
19049 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
19050 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
19051 ///
19052 ///      Into:
19053 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
19054 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
19055 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
19056 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
19057 ///
19058 /// Note that the new shufflevectors will be removed and we'll only generate one
19059 /// vst3 instruction in CodeGen.
19060 ///
19061 /// Example for a more general valid mask (Factor 3). Lower:
19062 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
19063 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
19064 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
19065 ///
19066 ///      Into:
19067 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
19068 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
19069 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
19070 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
19071 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
19072                                               ShuffleVectorInst *SVI,
19073                                               unsigned Factor) const {
19074   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
19075          "Invalid interleave factor");
19076 
19077   auto *VecTy = cast<FixedVectorType>(SVI->getType());
19078   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
19079 
19080   unsigned LaneLen = VecTy->getNumElements() / Factor;
19081   Type *EltTy = VecTy->getElementType();
19082   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
19083 
19084   const DataLayout &DL = SI->getModule()->getDataLayout();
19085 
19086   // Skip if we do not have NEON and skip illegal vector types. We can
19087   // "legalize" wide vector types into multiple interleaved accesses as long as
19088   // the vector types are divisible by 128.
19089   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
19090     return false;
19091 
19092   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
19093 
19094   Value *Op0 = SVI->getOperand(0);
19095   Value *Op1 = SVI->getOperand(1);
19096   IRBuilder<> Builder(SI);
19097 
19098   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
19099   // vectors to integer vectors.
19100   if (EltTy->isPointerTy()) {
19101     Type *IntTy = DL.getIntPtrType(EltTy);
19102 
19103     // Convert to the corresponding integer vector.
19104     auto *IntVecTy =
19105         FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
19106     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
19107     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
19108 
19109     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
19110   }
19111 
19112   // The base address of the store.
19113   Value *BaseAddr = SI->getPointerOperand();
19114 
19115   if (NumStores > 1) {
19116     // If we're going to generate more than one store, reset the lane length
19117     // and sub-vector type to something legal.
19118     LaneLen /= NumStores;
19119     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
19120 
19121     // We will compute the pointer operand of each store from the original base
19122     // address using GEPs. Cast the base address to a pointer to the scalar
19123     // element type.
19124     BaseAddr = Builder.CreateBitCast(
19125         BaseAddr,
19126         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
19127   }
19128 
19129   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
19130 
19131   auto Mask = SVI->getShuffleMask();
19132 
19133   auto createStoreIntrinsic = [&](Value *BaseAddr,
19134                                   SmallVectorImpl<Value *> &Shuffles) {
19135     if (Subtarget->hasNEON()) {
19136       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
19137                                                  Intrinsic::arm_neon_vst3,
19138                                                  Intrinsic::arm_neon_vst4};
19139       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
19140       Type *Tys[] = {Int8Ptr, SubVecTy};
19141 
19142       Function *VstNFunc = Intrinsic::getDeclaration(
19143           SI->getModule(), StoreInts[Factor - 2], Tys);
19144 
19145       SmallVector<Value *, 6> Ops;
19146       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
19147       for (auto S : Shuffles)
19148         Ops.push_back(S);
19149       Ops.push_back(Builder.getInt32(SI->getAlignment()));
19150       Builder.CreateCall(VstNFunc, Ops);
19151     } else {
19152       assert((Factor == 2 || Factor == 4) &&
19153              "expected interleave factor of 2 or 4 for MVE");
19154       Intrinsic::ID StoreInts =
19155           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
19156       Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
19157           SI->getPointerAddressSpace());
19158       Type *Tys[] = {EltPtrTy, SubVecTy};
19159       Function *VstNFunc =
19160           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
19161 
19162       SmallVector<Value *, 6> Ops;
19163       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
19164       for (auto S : Shuffles)
19165         Ops.push_back(S);
19166       for (unsigned F = 0; F < Factor; F++) {
19167         Ops.push_back(Builder.getInt32(F));
19168         Builder.CreateCall(VstNFunc, Ops);
19169         Ops.pop_back();
19170       }
19171     }
19172   };
19173 
19174   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
19175     // If we generating more than one store, we compute the base address of
19176     // subsequent stores as an offset from the previous.
19177     if (StoreCount > 0)
19178       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
19179                                             BaseAddr, LaneLen * Factor);
19180 
19181     SmallVector<Value *, 4> Shuffles;
19182 
19183     // Split the shufflevector operands into sub vectors for the new vstN call.
19184     for (unsigned i = 0; i < Factor; i++) {
19185       unsigned IdxI = StoreCount * LaneLen * Factor + i;
19186       if (Mask[IdxI] >= 0) {
19187         Shuffles.push_back(Builder.CreateShuffleVector(
19188             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
19189       } else {
19190         unsigned StartMask = 0;
19191         for (unsigned j = 1; j < LaneLen; j++) {
19192           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
19193           if (Mask[IdxJ * Factor + IdxI] >= 0) {
19194             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
19195             break;
19196           }
19197         }
19198         // Note: If all elements in a chunk are undefs, StartMask=0!
19199         // Note: Filling undef gaps with random elements is ok, since
19200         // those elements were being written anyway (with undefs).
19201         // In the case of all undefs we're defaulting to using elems from 0
19202         // Note: StartMask cannot be negative, it's checked in
19203         // isReInterleaveMask
19204         Shuffles.push_back(Builder.CreateShuffleVector(
19205             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
19206       }
19207     }
19208 
19209     createStoreIntrinsic(BaseAddr, Shuffles);
19210   }
19211   return true;
19212 }
19213 
19214 enum HABaseType {
19215   HA_UNKNOWN = 0,
19216   HA_FLOAT,
19217   HA_DOUBLE,
19218   HA_VECT64,
19219   HA_VECT128
19220 };
19221 
19222 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
19223                                    uint64_t &Members) {
19224   if (auto *ST = dyn_cast<StructType>(Ty)) {
19225     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
19226       uint64_t SubMembers = 0;
19227       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
19228         return false;
19229       Members += SubMembers;
19230     }
19231   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
19232     uint64_t SubMembers = 0;
19233     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
19234       return false;
19235     Members += SubMembers * AT->getNumElements();
19236   } else if (Ty->isFloatTy()) {
19237     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
19238       return false;
19239     Members = 1;
19240     Base = HA_FLOAT;
19241   } else if (Ty->isDoubleTy()) {
19242     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
19243       return false;
19244     Members = 1;
19245     Base = HA_DOUBLE;
19246   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
19247     Members = 1;
19248     switch (Base) {
19249     case HA_FLOAT:
19250     case HA_DOUBLE:
19251       return false;
19252     case HA_VECT64:
19253       return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
19254     case HA_VECT128:
19255       return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
19256     case HA_UNKNOWN:
19257       switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
19258       case 64:
19259         Base = HA_VECT64;
19260         return true;
19261       case 128:
19262         Base = HA_VECT128;
19263         return true;
19264       default:
19265         return false;
19266       }
19267     }
19268   }
19269 
19270   return (Members > 0 && Members <= 4);
19271 }
19272 
19273 /// Return the correct alignment for the current calling convention.
19274 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
19275                                                        DataLayout DL) const {
19276   const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
19277   if (!ArgTy->isVectorTy())
19278     return ABITypeAlign;
19279 
19280   // Avoid over-aligning vector parameters. It would require realigning the
19281   // stack and waste space for no real benefit.
19282   return std::min(ABITypeAlign, DL.getStackAlignment());
19283 }
19284 
19285 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
19286 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
19287 /// passing according to AAPCS rules.
19288 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
19289     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
19290   if (getEffectiveCallingConv(CallConv, isVarArg) !=
19291       CallingConv::ARM_AAPCS_VFP)
19292     return false;
19293 
19294   HABaseType Base = HA_UNKNOWN;
19295   uint64_t Members = 0;
19296   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
19297   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
19298 
19299   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
19300   return IsHA || IsIntArray;
19301 }
19302 
19303 Register ARMTargetLowering::getExceptionPointerRegister(
19304     const Constant *PersonalityFn) const {
19305   // Platforms which do not use SjLj EH may return values in these registers
19306   // via the personality function.
19307   return Subtarget->useSjLjEH() ? Register() : ARM::R0;
19308 }
19309 
19310 Register ARMTargetLowering::getExceptionSelectorRegister(
19311     const Constant *PersonalityFn) const {
19312   // Platforms which do not use SjLj EH may return values in these registers
19313   // via the personality function.
19314   return Subtarget->useSjLjEH() ? Register() : ARM::R1;
19315 }
19316 
19317 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
19318   // Update IsSplitCSR in ARMFunctionInfo.
19319   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
19320   AFI->setIsSplitCSR(true);
19321 }
19322 
19323 void ARMTargetLowering::insertCopiesSplitCSR(
19324     MachineBasicBlock *Entry,
19325     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
19326   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
19327   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
19328   if (!IStart)
19329     return;
19330 
19331   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19332   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
19333   MachineBasicBlock::iterator MBBI = Entry->begin();
19334   for (const MCPhysReg *I = IStart; *I; ++I) {
19335     const TargetRegisterClass *RC = nullptr;
19336     if (ARM::GPRRegClass.contains(*I))
19337       RC = &ARM::GPRRegClass;
19338     else if (ARM::DPRRegClass.contains(*I))
19339       RC = &ARM::DPRRegClass;
19340     else
19341       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
19342 
19343     Register NewVR = MRI->createVirtualRegister(RC);
19344     // Create copy from CSR to a virtual register.
19345     // FIXME: this currently does not emit CFI pseudo-instructions, it works
19346     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
19347     // nounwind. If we want to generalize this later, we may need to emit
19348     // CFI pseudo-instructions.
19349     assert(Entry->getParent()->getFunction().hasFnAttribute(
19350                Attribute::NoUnwind) &&
19351            "Function should be nounwind in insertCopiesSplitCSR!");
19352     Entry->addLiveIn(*I);
19353     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
19354         .addReg(*I);
19355 
19356     // Insert the copy-back instructions right before the terminator.
19357     for (auto *Exit : Exits)
19358       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
19359               TII->get(TargetOpcode::COPY), *I)
19360           .addReg(NewVR);
19361   }
19362 }
19363 
19364 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
19365   MF.getFrameInfo().computeMaxCallFrameSize(MF);
19366   TargetLoweringBase::finalizeLowering(MF);
19367 }
19368